Typecasting in C#
Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:
object x = "hello";
...
// I know that x really refers to a string
string y = (string) x;
There are various conversion operators. The (typename) expression
form can do three different things:
- An unboxing conversion (e.g. from a boxed integer to
int
) - A user-defined conversion (e.g. casting
XAttribute
tostring
) - A reference conversion within a type hierarchy (e.g. casting
object
tostring
)
All of these may fail at execution time, in which case an exception will be thrown.
The as
operator, on the other hand, never throws an exception - instead, the result of the conversion is null
if it fails:
object x = new object();
string y = x as string; // Now y is null because x isn't a string
It can be used for unboxing to a nullable value type:
object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float
There are also implicit conversions, e.g. from int
to long
:
int x = 10;
long y = x; // Implicit conversion
Does that cover everything you were interested in?
Casting means creating a reference to an object that is of a different type to the reference you're currently holding. You can do upcasting or downcasting and each has different benefits.
Upcasting:
string greeting = "Hi Bob";
object o = greeting;
This creates a more general reference (object) from the more specific reference (string). Maybe you've written code that can handle any object, like this:
Console.WriteLine("Type of o is " + o.GetType());
That code doesn't need to be changed no matter what objects you set o to.
Downcasting:
object o = "Hi Bob";
string greeting = (string)o;
Here you want a more specific reference. You might know that the object is a string (you can test this e.g.:
if (o is string)
{ do something }
Now you can treat the reference as a string instead of an object. E.g. a string has a length (but an object doesn't), so you can say:
Console.WriteLine("Length of string is " + greeting.length);
Which you can't do with an object.
See this or this:
Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or used to store values of another type unless that type is convertible to the variable's type
...
However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions