Behind the Scenes Look at C#: Type Conversions
(Page 1 of 6 )
Type conversion is a big subject that we will address in this article. We begin the article with an introduction to type conversion and casting. You will learn why you need to convert between types. You will also learn what the casting operator is, and we will discuss the cast concept in its abstract meaning. We will look at implicit conversions and explicit conversions with built-in value-types and reference-types; then we will discuss user-defined type conversions.
Introduction to Type Conversion
As we discussed in the first few articles of the series, a .NET type is just a representation of bits associated with the operations that translate those bits into an understandable value. For example, the System.Int32 structure represents a value that ranges from negative 2,147,483,648 up to positive 2,147,483,647. This structure is a 4 byte type. The structure UInt32 is also a 4 byte type, but it represents values that range from 0 to 4,294,967,295.
Although both structures are 4 byte types, they represent different ranges of numbers. That's because the System.Int32 Structure uses 1 bit to represent the negative or positive sign and uses the other 31 bits to represent the value itself, but the System.UInt32 Structure uses the whole 32 bits to represent the number. That's why we don't have a negative sign bit here, and we have a range from 0 to 4,294,967,295.
C# is a type-safe language, which means that every value must has a type, and this type knows exactly how to use the value. When you assign a value to a different type (other than the type that this value adheres to), a type conversion operation is needed. You need this operation in order to use the value with other types. For example, you have the value 255 of type byte (declared using the statement byte x = 255;) and you need to assign this value to the variable y, which is of type short (declared using the statement short y = x;). A type conversion operation needed for this assignment. In the next sections we will be talking about implicit and explicit type conversions.
Before we go on with the article I want to explain what a cast is. A cast means forming a value from one type to fit into another type; the value may lose some data. I will discuss casting further in this article, but for now I will give you two examples to make everything clear in your mind. Because cast operation side effects are different between value-types and reference-types, I will give one example that covers value-types and another example that covers reference-types.
Next: The Value-Type Example >>
More C# Articles
More By Michael Youssef