locked
Function overloading: Add result type to parameter signature RRS feed

  • Question

  • Can someone on the VB language team explain why a function result type is not part of the parameter signature?
    If it were then function overloads would also work for functions that only differ by the result type. 
    In some cases, this is useful (aka cleaner code) especially when you have strongly typed data.

    Other languages have this and implement it by considering the function result as an OUT parameter either as param 0 or at the end of the param list (stack) so existing type matching verification can be performed by the compiler.

    In VB, the workaround is just messy and would be easily fixed by a language change.

    -- This example is overly simplified and not meant as a solid justification for the request

    Say you have a parse requiirement that takes a comma delimited string in the form: "31,32,33,34" or "bob,carol,ted,alice"
    In you code,
     
    You want to define
    Private Function Parse( ByRef s as String) as String
    Private Function Parse( ByRef s as String) as Integer

    and use the functions this way
    Dim name as String = Parse(s1)
    Dim age as Integer = Parse(s2)

    Or you could have a source string: "bob,33,carol,34,ted,35,alice,36"
    Dim name as String = Parse(s1)  -- assuming the parse deleting the parsed value
    Dim age as Integer = Parse(s1)

    But NO....Can't do this.....the parameter signature is the same...

    However, you can achive the same result by ...
    Private Sub Parse( ByRef s as String, ByRef name as String)
    Private Sub Parse( ByRef s as String, ByRed age as Integer)

    Dim age as Integer
    Parse(s1,age)
    Dim name as String
    Parse(s2,name)

    The result is what I want, but its messy and misleading. A function result would be cleaner. 
    Also I have to code to work around what the compiler can easily figure out if it considered the function result in the parameter signature.
    Can someone explain why functions cannot become a little bit smarter?

    Thanks

    Monday, December 7, 2009 7:53 PM

Answers

  • Generics can be used to specify an output type, but I think it is a bad practice


        Private Function Parse(Of T)(ByRef s As String) As T
            Dim result As T
        End Function


    Now you will likely end up testing for type inside of that Function, which just wastes the power that you can leverage from Generics.

    I was not part of the .NET design team so I cannot explain why the return value was not part of the signature.
    I don't think the issue has anything to do with VB at all.


    Mark the best replies as answers. "Fooling computers since 1971."
    Monday, December 7, 2009 8:38 PM