Direct casting vs as casting
There are two primary ways to cast in C#, Direct casting and ‘as’ casting.
Here are some examples of Direct/Implicit casting
byte source = 1; int value = source; object source = 1; //this assignment defaults to an int int value = (int)source; /* or */ byte value = (byte)source;
Implicit casts can be used when converting from one type to another without any loss of information. In this example from a byte to a higher order numeric value.
Double. You cannot, however, cast down from
Byte without doing an explicit cast.
The second example shows an explicit cast from an integer to a byte. The explicit cast here is required because there could be a loss of information going from a larger
int (4 bytes) to a
byte (1 byte).
Casting using the
The types must be nullable or reference objects in this case.
object animal = new Dog(); var value = animal as Dog; /* value, is this instance, will be `null` */ var value = animal as Plankton;
As casting basically does a check to see if the type is convertible and if so returns the value. If not it returns null.
Are these the same?
IL_0007: isinst CastClassVsIsInst.Dog IL_0007: castclass CastClassVsIsInst.Dog
From a little bit of testing it seems that ‘as’ is also faster. Others could confirm this but in tight loops
isinst performs significantly faster than
Charts courtesy of Jon Galloway
Here’s my quick-and-dirty test.
Feel free to fork it and make improvements. There might be instances where castclass is faster.
It’s not perfect but enough to convince me that
isinst is a bit faster in tight loops than