The Conservative Nature of VB (Part 1) – Implicit Conversion

vb-179I have been spending the last few days, long days, fixing code I have inherited.  I have posted on here about the problems with bad coding which I have seen a great deal in this application.  That said I am wanting to convey the beauty and danger of Visual Basic as a language and how bad programming can creep in because VB just simply looks at it and determines it knows what is going on.

So, thankfully you can look at the way VB is looking at your code and the way in which it can report back issues.  The warnings configuration within the compile options are the area.  These options are for all warning that the compiler would tell you is a warning, but from here you can choose to ignore them, display them still as a warning or make them throw an error to prevent your application from compiling (and subsequently you will need to fix before a build is done.).

image

Above is the compile options for Visual Basic in a Visual Studio 2012 project.  To get to the compile options, Right Click the Visual Basic Project, Click Properties.  Click the Compile tab, you will then see this list of items.

These are warnings that you can turn on and off in the IDE, none will prevent the application from compiling but could cause, dependant on circumstances, cause an exception at runtime.

If they could cause an exception at run time why not simply make them errors.  Simple, if all of these items were errors in the compiler, I would be still trying to get the application to compile possible have several deep gouges in my head as I would have banged it repeatedly on the desk.  So for one I am glad I have this option.  But at the same time it can hide bad coding practises.  Of which I will look at each option provide an example and provide my opinion on it.

BIG FAT NOTE – If you turn any of these options to Error, they will be treated as errors and your project won’t build.  You have been warned.

Implicit Conversion

When you perform various abilities and functions on variables in your code.  When you look at the following code it will make more sense.

Dim x As String = "Hello"
Dim y As Integer = 5

x &= " " & y
Console.WriteLine(x)

x = y
Console.WriteLine(x)

See line 10.  This is the implicit conversion.  Converting an integer into a string, this doesn’t seem like an issue and under default circumstances it isn’t, change the Implicit Conversion from None to Error or Warning and you will see the message come up about;

Error    1    Implicit conversion from ‘Integer’ to ‘String’.   
Module1.vb    10    13    ConsoleApplication5

Is this wrong or bad?  No, but there could be other forms of implicit conversion that might fail.

Dim x As String = "Hello"
Dim y As Integer = 5

x &= " " & y
Console.WriteLine(x)

y = x
Console.WriteLine(y)

In the above example, there has been one small change made, I have made y = x.  This comes up as the same error.  Now in the instance of x = y, it will never fail.  An integer will always convert safely into a string.  BUT, when converting a string into an integer, this could very well fail at runtime, and in fact this current code would.

This is what happens when you run the following.

Unhandled Exception: System.InvalidCastException: Conversion from string “Hello 5” to type ‘Integer’ is not valid. —> System.FormatException: Input string was  not in a correct format.
   at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat)
   at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)

   — End of inner exception stack trace —
   at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)

   at ConsoleApplication5.Module1.Main() in c:\users\m1roge\documents\visual studio 2012\Projects\ConsoleApplication5\ConsoleApplication5\Module1.vb:line 10

This shows what happens, certainly straight exception dumps are never a good thing.  But what you can see is, it is trying to perform a couple of conversions, it is trying to see if it will convert to a Double and then to an Integer.  Turning this on as a warning at least highlights the problem and you can deal with it as you see fit.  A way around it is to make sure you code the conversion properly

Dim x As String = "Hello"
Dim y As Integer = 5

x &= " " & y
Console.WriteLine(x)

If Integer.TryParse(x, y) Then
    y = x
End If
Console.WriteLine(y)

The above shows this is the correct way to do it, but that is a lot of extra code to write if you know, without a doubt that x will always be convertible to a number.  But don’t just see this as an issue between strings and integers, this very same error will popup for converting from one type into another (beyond the intrinsic types).

My recommendation with these is take them as they come.  When you are creating your own classes make cure you use the Override the default conversion operators if you are needing to convert these classes, use the intrinsic converters , CInt, CStr, CDbl and so on, see Type Conversion @MSDN for more information, you can use the Convert class, but the data types like Integer, Double they have static members like Parse and TryParse which enable checking the conversion before performing it, Try Parse will put the result into one of the parameters as a reference type, but if fails it will put 0 in there (so if you need the value that is in there, be careful.

NOTE – Because VB supports an Object type which is a reference type, some of the time is not a reason to use it simply because you don’t want to deal with conversion issues when it comes to certain types.   VB treats this different to the way other languages that use the CLR type Object.  So use it when you need to not because you want to fix issues.

Advertisements

Posted on January 13, 2014, in Article, Development and tagged , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: