Return what ???

I was looking at Lisa’s latest blog entries, and the second last screen shot made me sit back and say “what”:


In that example of Lisa’s, the local variable surfaceArea is actually the one that VB creates for you by default, allowing you to assign to the function name. If you don’t explicitly return a value the value of that auto generated local variable is returned for you.  But should it be in intellisense following a Return statement ?  Like in this example, you could see Lisa could easily select the first variable shown. The code would compile without warning, but it would return 0.  And due to the similarity in the local variable she used and the function name, it’s one of those bugs you can stare at all day and just not see.

Personally, I would like tot see that auto-generated variable become a project wide option to raise either a warning or an exception.  I don’t see the need for it other than those who want some sort of backward compatibility.  Secondly, and more importantly, this should raise a warning about using a variable before it is assigned to. Sure it’s a value type note a reference type, but if a value isn’t assigned, then what is it returning.

2 Comments so far

  1.   Marc Brooks on January 10th, 2008          

    But the thing is that the autogenerated variable is there to support the VB6 way of assigning the return value…

    Function Ten() as Integer
    Ten = 9
    End Function

    Internally, the End Function is actually ALWAYS:
    Return Ten
    End Function

  2.   bill on January 10th, 2008          

    Hi Marc,

    Right, that’s why it would be good if it was an option to be able to turn that off. If you aren’t using it, why have it ? If your method doesn’t return a value on all bracnches it’s good to be warned, rather than have some implicit value returned.

    Also: Return Ten: would be and is totally superfulous when using the function name. The only time you might want to do that is if you previously assigned to the value and you want multiple exit points. Again a warning of some sort would be good here if the value has not been already assigned to.