Nick Nick - 11 months ago 35 Question

No warning in VB.NET when function has no return

Some comments on Stack Overflow question Why doesn't the C# compiler stop properties from referring to themselves? regarding warnings got me thinking about old issues that always goofed me up when I was writing more VB.NET code.

One of them was the fact that the compiler didn't warn if you declared a Function but never did an explicit Return statement or assign to the Function name. Running Visual Studio 2008, I just made a small experimental project, and it seems as though the behavior has never been fixed. I created a Visual Basic Console application, with the following code:

Module MainModule

Sub Main()

Dim test As Boolean = TestWarning()

End Sub

Function TestWarning() As Boolean

Console.WriteLine("There is no Return Statement")

End Function

End Module

I also went into the Project Settings and turned
On Option Strict
Option Explicit
. I also set the Warning Configurations so that "Function/Operator with no return value" was set to Error.

I compiled the project and got no warning, and no error on the TestWarning() Function. This seems like a great place to put a warning, because it will default to False, and you may have simply forgotten to do a return. C# will error without a return statement. I thought that VB.NET did the same thing with the "Function/Operator with no return value" configuration. Is this a bug, or is there something I'm missing?

Further Experimentation

Function TestWarning() As Boolean

If DateTime.Now.DayOfWeek = DayOfWeek.Monday Then
Return False
Console.WriteLine("There is no Return Statement")
End If

End Function

If I have an explicit
in an
, and nothing in the
, there is also no warning or error. It will simply take the default, even though you likely intended (via programming style) to have an explicit return. In this case, I explicitly returned
(which is the default for Boolean), so it's likely a hidden bug that I should have returned
in the

Answer Source

The warning will only let you know when a function is going to return Nothing by default.

You would get a warning if return value was of a reference type.

But your function has a return value of a value type, and those cannot be Nothing. Therefore, no warning.

This is because function name inside this very function acts as a result variable. You can return a value by assigning it to the function name instead of using Return. And all variables are initialized with default values, including the function-name variable. This is not the case in C, hence the different meaning of the warning.

Compare this to using variables before initializing them:

Dim x As Integer
CallFunction(x)  'No warning, x is implicitly and properly initialized to 0.

Dim y as Object
CallFunction(y)  'A warning: variable used before a value is assigned to it