Type Safety: It makes the C# world go ’round

I'll admit this may not be a subject on the tip of America's tongue, but there are some things that are bugging me about the state of the software development profession, and I thought that perhaps a good place to start would be with something that's working extraordinarily well.

Type safety, by the way, has nothing to do with an airbag on your keyboard, so this article will be a bit technical, but I'll try to keep my explanations simple enough for a wide audience. You may also recall a recent article about Generics -- these concepts are very closely related, as you'll seen shortly.

The concept of type safety in a programming language simply means that the compiler and runtime environment know the type of each variable, and can use that information to protect you from a lot of errors you might otherwise see. A variable's type can be a primitive type, like a string, or an integer, or a Date. It can also be a complex type or an object. A Customer object, also has a type, and it's different from an Invoice object.

What good are types?

Types help us in two main ways. First, the compiler can produce much safer code. When the compiler can check the types of our variables, we aren't allowed to shove square pegs into round holes, and we are safe from many type conversion bugs that plague non-typed languages.

The second contribution we get is coding support from our development environment. In Visual Studio, for instance, its intellisense features help with things like auto-complete and refactoring. None of these features is due strictly to how .Net handles types, but many of them are made possible when we know about our variables' types.

There are some downsides, too. There are times when you know full well that you're copying one variable to another, and they're supposed to be of the same type, but the compiler gives you an error. These problems are easier to take once you get the hang of explicit type declarations and even easier to take when you see the types of errors these checks prevent.

You may have made the connection to Generics by now. Generics simply let us extend all of this type-safe goodness to classes where a type will take multiple forms depending on where it's used.

The overall affect on the developer is to make it much easier to crank out lots of code in a hurry, with a reasonable expectation that it'll run right when it's compiled. The development environment actually predicts what I'm going to type in some cases because it knows enough about my objects to be able to understand the most typical coding patterns as I start them.

It's also possible for all that help to lead to developer dysfunction, but that's a topic for another day.

One Reply to “Type Safety: It makes the C# world go ’round”

Comments are closed.