Friday, 10 September 2010

Type checking in VB.Net

OK, here’s another little reminder about VB.Net syntax.

Take the following C# fragment:

if (instance is TestDomainObject)
    var testInstance = instance as TestDomainObject;

In VB.Net the equivalent is:

If (TypeOf instance Is TestDomainObject) Then
    Dim testInstance = TryCast(instance, TestDomainObject)
End If

Note the use of the TypeOf keyword.

Note also that casting in VB.Net takes a bit of getting used to. There are essentially 3 ways to perform casting:

Keyword Data types Argument relationship Run-time failure

CType Function

Any data types

Widening or narrowing conversion must be defined between the two data types

Throws InvalidCastException


Any data types

One type must inherit from or implement the other type

Throws InvalidCastException


Reference types only

One type must inherit from or implement the other type

Returns Nothing (Visual Basic)

See DirectCast Operator (Visual Basic) to get started. You might also like to checkout Convert.ChangeType Method.


Post a Comment

By all means leave a comment. I may not be able to get back to you as quickly as I'd like but I'll do my very best.