Greg is correct about the use of DirectCast vs CType in VB. DirectCast tells the compiler to try casting the object and then check for implcit/explicit casting operators on the two types in question (the one being cast and the requested type) while CType tells the compiler to try casting it first, and then check for an implicit/explicit conversion operators, and then try the Convert.ToXXX methods for backward compatibility with old VB, so in some cases, CType is slower
. Nice one Greg.
However, jjp, you're using C#, which doesn't have DirectCast or CType, it just has the cast syntax like C++:
string var = (string)someOtherVar;
or
object var = new SomeType();
((SomeType)var).SomeMethodOnThatType();
So, in C#, the casting operator is the equivalent to DirectCast (though the C# compiler will pick up on a few extra things that DirectCast won't). There is no equivalent to CType, but since it's really meant for backward compatibility with old VB, and since the C# casting picks up on a few cases where DirectCast won't you don't really need it.
One other casting worth mentioning is the "as" (C#) / TryCast (VB):
object var = new SomeType();
SomeType var2 = var as SomeType;
Dim var As Object = New SomeType()
Dim var2 As SomeType = TryCast(var, SomeType)
It can only be used with reference types (so no value types, structures, etc.). But, it will never throw an exception (hence the "Try" in the name) and it's extremely fast. It will try to cast the object, and if it fails, it returns null (Nothing in VB), hence why you need a reference type since value types cannot be null. So, if you're not absolutely positive that your object is going to be a certain type, always TryCast (as) and then test your variable on null (Nothing). That combination is actually just as fast as casting and is much faster than testing on the type of an object before casting it. If you use Reflector and look through the .NET DLLs, you'll see them use it all the time.