Team LiB
Previous Section Next Section

Casting and Class Conversion

Casting is used to convert a particular object type to another type. There are two dominant casting types: implicit/upcast and explicit/downcast.

The implicit/upcast type of cast is used to convert a smaller type into a larger type. This is done automatically for you in C#, and there is no need to explicitly cast, except to better describe your intentions, which is a good idea. Here is an example:

int X = 123456;
long Y = X;

The explicit/downcast type of cast is used to convert a larger type into a smaller type. You must do this to get the conversion to work. With this type of casting, you are converting from a more specific type to a less specific type, and you will lose some of the exactness of the object. Here is an example:

int X = 12345;
short Y = (short) X;

In addition, C# also provides two special operators to help with casting:

The following example demonstrates casting.

Code Example: Casting
Start example

using System;

namespace Client.Chapter_1___Common_Type_System
{
      class Casting
      {
            static void Main(string[] args)
            {
                  int MyInt = 12345;
                  //Implicit cast
                  long MyLong = MyInt;
                  //Explicit cast
                  short MyShort = (short)MyInt;
            }
      }
}
End example

Team LiB
Previous Section Next Section