Difference between CType and DirectCast

In VB.NET, both CType and DirectCast are used for casting or converting objects from one type to another. However, there are some important differences between the two.

CType

CType is a general-purpose conversion function that can perform both widening and narrowing conversions. It can convert compatible data types within the inheritance hierarchy or between compatible value types. CType also supports conversions between numeric types, strings, dates, and other common data types. It performs both compile-time and run-time type checking, and if the conversion is not valid, it will throw an exception.

Here's an example of using CType to convert an object to a specific type:

Dim obj As Object = "12345" Dim number As Integer = CType(obj, Integer)

In this example, we have an object obj containing a string value. We use CType to convert it to an integer by specifying the target type Integer. If the conversion is successful, the number variable will hold the integer value 12345.

DirectCast

DirectCast is a more specific and restrictive casting operator that is used for performing reference type conversions within an inheritance hierarchy. It is used when you need to cast an object to a specific type, ensuring that the cast succeeds only if the object being cast is of that exact type or a derived type. DirectCast performs only compile-time checking, so it does not perform run-time type checking. If the object being cast is not of the specified type, an exception will be thrown.

Here's an example of using DirectCast:

Dim obj As Object = New DerivedClass() Dim derived As DerivedClass = DirectCast(obj, DerivedClass)

In this example, we have an object obj that is of type DerivedClass, which is derived from a base class. We use DirectCast to explicitly cast it to the DerivedClass type. Since the object is indeed of that type, the cast will succeed, and the derived variable will hold a reference to the object of type DerivedClass.

Conclusion

CType is more versatile and can handle various types of conversions, including widening and narrowing conversions, while DirectCast is specifically used for casting within an inheritance hierarchy, ensuring the exact type match. It's important to choose the appropriate casting operator based on the specific requirements of your code and the type safety you need to enforce.