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;
    _data.Remove(testInstance.Id);
}

In VB.Net the equivalent is:

If (TypeOf instance Is TestDomainObject) Then
    Dim testInstance = TryCast(instance, TestDomainObject)
    _data.Remove(testInstance.Id)
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

DirectCast

Any data types

One type must inherit from or implement the other type

Throws InvalidCastException

TryCast

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.

0 comments:

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.