Public Enum TestEnum Foo = 1 Bar Baz End Enum '... Dim enum_value as TestEnum = MyEnum.Foo Dim str as String = MethodThatReturnsAString(enum_value) '... Private Function MethodThatReturnsAString() As String Return "Hello World!" End FunctionWhat you see above compiles perfectly fine. And it does, even, return a value. But you're looking at this code and contemplating WHY it compiles fine. I stared at this for a good while before I had to add another brain to the mix. But, just to give those who are smarter than me a bone before giving the puzzle away, the value of
str
would equal "e". For some of you, that may have done it, you now know what's going on. The rest of you may require a little background on the design of the Visual Basic language. I agree that simplicity is the best way to go, but simplicity at the cost of clarity is detrimental.
VB Simplification 1: Parentheses to delineate Function/Subroutine parameters are optional in certain circumstances. So assigning to a variable the value of a parameterless function, right hand part of the assignment may not look any different than a variable?
VB Simplification 2: Parentheses have a dual purpose in VB. Method parameters (as common in most languages) & the index operator (in C based languages this is the square brackets []). During an assignment, the right hand side can easily be mistaken as a method call.
The full blow solution, if you have yet to come up with it yourself, goes like this:
- MethodThatReturnsAString returns "Hello World!"
- As MethodThatReturnsAString does not take any parameters and therefore the parentheses are not necessary. The compiler, avoiding a compile error, assumes that the value of enum_value is not a parameter, but indeed an indexer to the string that was just returned.
- str is assigned the value of "e".
- The compiler is happier than a pig in slop.
- I'm not happy as all I have is an "e"...
"Visual Basic did many other things to waste my time as well. If every one of them were written down, I suppose that even the whole world would not have room for the books that would be written." - 1 Coders 21:25
No comments:
Post a Comment