Tips for Converting Between VB & C#
Even though much of the conversion process
between VB and C# seems clearly defined, there are a few insidious
and subtle differences between VB and C# — here are just a few examples:
- You use the upper bound to initialize
arrays in VB; whereas, you use the number of elements in C#.
Instant C# and Instant VB correctly adjust all array initializations.
- The ending condition of a VB
"For" loop is only tested once, on the first entry to the loop;
while a C# "for" loop tests the ending condition on every
iteration. Instant C# inserts temporary variables set to the ending condition when the
ending condition is not constant.
- The "Not" operator in VB has
significantly different operator precedence than the "!" operator
in C#. So, just substituting one for the other will often produce
incorrect code.
- The following set of translations
shows how keyword overlap can be confusing:
- The VB phrase "x Is y" translates to "x
== y"
- The VB phrase "TypeOf x Is y" translates
to "x is y"
- The VB global method "GetType(x)"
translates to "typeof(x)"
("x.GetType()" remains "x.GetType()" since this is a .NET
intrinsic object method).
- Calls to the VB "IIf" function can't be always
reliably replaced by the "?" operator and vice versa since the "?" operator uses
short-circuit logic (resolving only the required return value) and
calls to the "IIf" function do not (since "IIf" is a function, both
possible return values are resolved even though only one is ever
required). The "If" ternary operator in
VB9 and above behaves identically to the C# ternary operator.
- VB still allows assigning method
return values to the method name (using the method name as a
temporary variable). These values are returned by the method
upon exiting the method even though a return statement may not
have been executed. Further complicating this situation is
the fact that VB allows mixing return statements and assignments
to the method name. Instant C# correctly converts these to coherent C# code.
Use
Instant C#
and
Instant VB
to convert between VB.NET and C#.
Additional resource:
VB.NET and C# Equivalents
Copyright © 2004 – 2024 Tangible Software Solutions, Inc.