DirectCast - VB.Net

If this conversion is not possible then an exception is thrown.
This is another way to convert between different datatypes.
The DirectCast works in a similar way to the CType operator but has a few imporatant differences:

  • It only works with arguments that are reference type. If you pass a Value type then a compilation error will occur.

  • It cannot perform widening conversions from Short to Integer.

  • It cannot perform widening conversions from Single to Double.

  • This method is slightly faster that CType so you should use CType when you need to cast rather than convert a value.


DirectCast requires an inheritance or implementation relationship between the datatypes of the two arguments.
This means that one type must inherit from or implement the other.


This is a cast operator that has the same syntax as CType and is useful in certain narrowing situations
The DirectCast gives you the CLR supported conversions rather than using any of the other conversion functions.



DirectCast(objObject, Integer) will generate an exception if objObject doesn't contain an integer.
CType(objObject, Integer) will work if objObject is a Long, Double, String etc


Using DirectCast instead of CType can make the conversion that little bit faster and should only be used when you know exactly what you are converting.


For example

Dim arArray As New ArrayList() 
Dim i as Integer
arArray.Add(100)
i = DirectCast(arArray(0), Integer)

DirectCast is twice as fast for value types (integers, etc) and marginally faster for reference types.
There is no boxing in DirectCast
DirectCast only works if the specified type and the run-time type of the expression are the same.


If the argument cannot be converted to the target type it ill throw an InvalidCastException error.




© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext