CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Paul Laudeman

Helping You to Make "Smart Clients" Smarter!

Method return values in Visual Basic .NET - be careful!

While debbuging some code that I had written, I discovered a “feature” of the Visual Basic .NET language that can quickly get you into trouble. From the Visual Basic Language Reference:

If you use Exit Function without assigning a value to name, the function returns the default value appropriate to argtype. This is 0 for Byte, Char, Decimal, Double, Integer, Long, Short, and Single; Nothing for Object, String, and all arrays; False for Boolean; and #1/1/0001 12:00 AM# for Date.

The problem with this is that you don't have to explicitly call Exit Function for this to happen; if your method executes without returning a value, the default value of the return type will be returned unless you specify otherwise. The crux of the problem is that if you forget to include the return value, the compiler won't even warn you that you might have made a mistake.

Interestingly enough, C# by default will throw a compiler error stating something to the effect of “not all code paths return a value” and the build will be stopped until the error is corrected. This is, I would argue, much better than silently returning a default or null value to the caller.

To help prevent these types of errors from occurring, you should make sure you are writing unit tests for your code or using some other design by contract type mechanism (such as eXtensible C#) to make sure your method performs as intended.

UPDATE:
Looks like Paul Vick from the Visual Basic .NET compiler team blogged about this same problem over a month ago in his post about 'Flow Control Analysis'.



Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!

Our Sponsors