Casting Variables in C#

C# is a strongly typed language. This means that when a variable is defined we have to specify what type of data the variable will hold. Languages which aren’t strongly typed attempt to do the type conversion within their compiler or interpreter themselves. While this can make it easier on the casual programmer, it does allow subtle bugs to enter the program if considerable care isn’t exercised. By having a strongly typed language, variable type bugs are eliminated. However, there can be times where you want to move a value from one type of variable to another. This is where casting comes in.

In C#, there are several different kinds of casting you can use depending upon the situation.

The first type of casting we’ll look at is the standard C++ and Java syntax style casting. C#, being akin to these languages, uses this same syntax.

string MyString = (string)MyObject;

This is sometimes called explicit casting. The casting operation is applied to the full equation to the right. So, in this example, Var1 would not be cast by itself but the entire equation, Var1+Var2 would be.

string MyString = (string)Var1+Var2;

There may also be occasions when you do only want to cast part of an equation chain. In that circumstance, you can use parentheses to indicate the part you wish to cast, as shown here:

string MyString = ((Form)MyObject).Text;

In this example, we’ll be converting the variable MyObject to a Form and then extracting the Text property from the newly cast Form object.

It is important to note that if a particular value cannot be cast as a particular variable type either the program won’t compile or a runtime exception will occur. Which happens depends on if the compiler can detect the problem.

The second type of C# casting is the ‘as’ casting operator. It works just like the explicit casting except that, in the case of a conversion failure, it will cause the value to be set to null rather than throwing an exception. However, it is important to remember that you can only use this kind of casting for reference and nullable variable types and not for non-nullable types like integers. Here’s an example of using the as casting operator.

Object MyObject = new TextBox();
Button MyButton = MyObject as Button;

I hope this has helped go over the basics of casting variables in C# for you.


Theme Provided By Free HTML Layouts