Paul Laudeman

Sponsors

The Lounge

Wicked Cool Jobs

News

  • I'm test-driven!
    TestDriven.NET

    MSN Messenger: plaudeman at hotmail dot com

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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'.


Posted Tue, Nov 25 2003 2:54 PM by paul.laudeman

[Advertisement]

Comments

Darrell wrote re: Method return values in Visual Basic .NET - be careful!
on Tue, Nov 25 2003 10:17 AM
The problem stems from the fact that VB creates a variable of the same name as the function of the type of the function's return type. If you never assign anything to that variable, it gets the default value per .NET, and gets returned to the calling whatever at the end of the function.

C# does not do this. If you look at the IL generated by VB.NET for a function, you will see the variable declaration... it even comes up in Intellisense! Even Option Strict/Explicit/Super-Hard-VB doesn't change this.
Devlicio.us