C# is the standard coding language for developers at ImageSource, but it wasn’t always that way. Before, VB.NET was the predominant language of choice. When converting some of the codebases over from VB.NET, we consistently run into areas where VB.NET specific commands have been used. These commands either do not exist in C# or require use of the Microsoft.VisualBasic library. Either make code conversion very frustrating when they are used.
Below are some examples of commands that should be avoided in .NET code:
Cint, Cstr, CDate, CDbl
Use the equivalent call in the System.Convert class.
- CInt – Convert.ToInt32
- CStr – Convert.ToString
- CDate – Convert.ToDateTime
- CDbl – Convert.ToDouble
This one is a bit trickier and requires more work, but can be a lot more useful. C# does not have an equivalent type checker, but you can use the TryParse methods located in the primitive objects. For example, the following VB.NET code can be used to check if a string is an integer value.
Dim i As Integer = 0 Dim test As String = "213" If Integer.TryParse(test, i) Then 'Hey, this check worked! 'And the integer has already been converted so you 'can start using it. End If
The new line command in VB, necessary because VB.NET does not allow you to write special characters in strings, so special characters need to be concatenated onto the strings. Instead of VBCRLF, use the Environment.NewLine command, as this exists in both VB.NET and C#.
- Optimally, code converted to C# should convert any instances of VBCRLF to \n in the string. However, using Environment.NewLine will at least get it to compile without need for the Microsoft.VisualBasic library.
Avoid the With statement, as it does not exist in C# and you’ll just end up having to put the object reference in anyway. It is not that much harder to just write the objectName.Method or objectName.Property, and it makes the code easier to understand.
So hopefully this brief overview will help you to write better VB.NET code. Remember, the .NET framework exists in both VB and C# form, and making the two easily compatible helps code maintainability and portability.