Tangible Software Solutions

The Most Trusted Name in Source Code Conversion

  • Trusted for over 12 Years
  • Saves Valuable Time
  • Accurate and Reliable
  • Responsive Support

VB Equivalent to C# Casts

The closest VB equivalent to the standard C# casting operator is the DirectCast operator.  However, use of this operator is invalid in many cases where standard C# casting is used:


This C# code works fine:
i = (int)someDouble;

but the following VB code will not compile:
i = DirectCast(someDouble, Integer)

For this reason, the more reliable equivalent in VB is the CType macro and the related shortcut VB macros (CInt, CBool, etc.).

A further complication is that C# integer casts always truncate, while the VB integer conversion macros always round.  For this reason, in order to achieve the same results as the C# casts, a call to the .NET Math.Truncate function is required prior to the call to the CInt, CLng, and CShort macros when converting C# integer casts.


This C# code:
i = (int)someDouble;

has this VB equivalent:
i = CInt(Math.Truncate(someDouble))

The C# as operator always converts to the VB TryCast operator, except for the case of nullable types, in which case you must use the CType operator.

If you need to convert from C# to VB and you are depending on the results being reliable and accurate, then you will want to have Instant VB, the best C# to VB converter.

Copyright © 1997 - 2017 Tangible Software Solutions Inc.