7

In VB.NET on a boolean function if you run an Exit Function line will it return false?

2
  • 4
    This is why I don;t like VB :) In C# the compiler forces you to return explicity. Commented Apr 3, 2009 at 14:46
  • 2
    Actually compiler tells you as a warning (and/or visually) if you don't return anything explicitly, I'm not quite sure if it's possible to make it mandatory. Commented Apr 3, 2009 at 14:58

4 Answers 4

11

That is correct, with the caveat that in VB the function name can also be a variable that is returned. If you've previously set that to true, it will return true.


More completely, in VB.Net, if I have a boolean function Foo() defined like so:

Public Function Foo() As Boolean
   '...

...the body of that function has an implied variable also named Foo that matches the return type of the function — Boolean in this case, but Object if the return type is omitted (you should be using Option Strict, which requires a return type). This implied variable is initialized to use the default value for that type.

If you fail to Return a value from the function, whether via Exit Function or simply by reaching the end, this implied variable is returned instead. Therefore, a Boolean function will return False if you Exit Function early without making other changes, because that is the default value in the implied variable used with the function. But you could also set that variable to True first if you wanted, and then Exit Function would cause it to return True instead.

These days people don't often use the implied variable, but there are situations where it can save you a few lines of code without costing anything in clarity.

Sign up to request clarification or add additional context in comments.

2 Comments

Possibly this is a matter of clarity, but this works in VB because that function output variable is init'd to false and without an explicit return it's that variable which is returned
To be clear, if I have a function returning type long, Exit Function returns the default value (0). Furthermore, if, in my Function Foo() as Long, I Return Foo, I am, in fact, returning 0. Correct? I could technically replace Exit Function with Return Foo?
3

Regardless if it does or not (the compiler gives a null-reference warning only), you should still explicitly return false, if only for readability.

1 Comment

The actual answer to the question is still useful if you want to clean up such Exit Function usage though.
2

As long as you have not set that function to True before you exit

Comments

2

I always do "Return True" or "Return False" to exit a method instead of the exit statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.