Caleb Thompson Caleb Thompson - 6 months ago 4x Question

Difference between DirectCast() and CType() in VB.Net

I am an experienced C/C++/C# programmer who has just gotten into VB.NET. I generally use CType (and CInt, CBool, CStr) for casts because it is less characters and was the first way of casting which I was exposed to, but I am aware of DirectCast and TryCast as well.

Simply, are there any differences (effect of cast, performance, etc.) between DirectCast and CType? I understand the idea of TryCast.


The first thing to note is that VB.Net does not have a direct analog to C#'s (type)instance casting mechanism. I bring that up because it's useful to use that as a starting point in comparing the two VB.Net operators (and they are operators, not functions, even though they have function semantics).

DirectCast() is more strict than the C# casting operator. It only allows you to cast when the item being cast already is the type you are casting to. It won't do any conversion. So, for example, you can't cast from short to int, like you could with a C# (int) cast. But you can cast from an IEnumerable to an array, if your underlying IEnumerable object variable really is an Array. And of course you can cast from Object to anything, assuming that the type your object instance really is somewhere below your cast type in the inheritance tree.

This is desirable because that makes it faster. There's a little less conversion and type checking that needs to take place.

CType() is less strict than the C# casting operator. It will do things like convert a string to an integer that you can't just do with a simple (int) cast. It has as much power as calling Convert.To___() in C#, where the _ is the target type of your cast. This is desirable because it's very powerful, but that power comes at the cost of performance — it's not as fast as DirectCast() or C#'s cast operator because there might be quite a lot of work to do to finish the cast.

Generally you should prefer DirectCast() when you can.

Finally, you missed one casting operator: TryCast(), which is a direct analog to C#'s as operator.