C Sharp

The Type System

At the center of the Microsoft .NET Framework is a universal type system called the .NET Common Type System (CTS). In addition to defining all types, the CTS also stipulates the rules that the Common Language Runtime (CLR) follows with regard to applications declaring and using these types.

In this tutorial, we'll look at this new type system so that you can learn the types available to C# developers and understand the ramifications of using the different types in C# programs. We'll begin by exploring the concept that every programming element is an object in .NET. We'll then look at how .NET divides types into the two categories—value types and reference types—and we'll discover how boxing enables a completely object-oriented type system to function efficiently. Finally, we'll cover how type casting works in C#, and we'll start looking at namespaces.

Everything Is an Object

Most object-oriented languages have two distinct types: those types that are intrinsic to the language (primitive types), and those types that can be created by users of the language (classes). As you might guess, primitive types are usually simple types such as characters, strings, and numbers, and classes tend to be more elaborate types.

Having two discrete sets of types causes a lot of problems. One problem relates to compatibility. For example, let's say you wanted to have a collection of ints in a traditional system with these two sets of types. You'd need to create a class specifically to hold values of type int. And if you wanted a class to hold a collection of doubles, you'd have to do the same for that type. The reason for this is that these primitive types normally have nothing in common. They aren't real objects, so they don't derive from a common base class. They are more like magic types that have to be dealt with individually on their own terms. A similar problem surfaces in these traditional systems when you want to specify that a method can take an argument of any type supported by the language. Because these primitive types are incompatible, you can't specify an argument like this unless you write wrapper classes for each primitive type.

Thankfully, this is no longer an issue in the world of .NET and C# because everything in the CTS is an object. In fact, not only is everything an object but, even more importantly, all objects implicitly derive from a single base class defined as part of the CTS. This base class, called System.Object,will be covered in the section "Boxing and Unboxing." -