Consider these two functions:
'Overload 1
<Extension()>
Function ComputeReturnValue(Of TSource, TResult)(ByVal source As TSource, ByVal IfTrueFunc As
System.Func(Of TSource, TResult), ByVal IfFalseFunc As System.Func(Of TSource, TResult)) As TResult
Return If([some test is true], IfTrueFunc(source), IfFalseFunc(source))
End Function
'Overload 2
<Extension()>
Function ComputeReturnValue(Of TSource, TResult)(ByVal source As TSource, ByVal IfTrueValue As
TResult, ByVal IfFalseFunc As TResult) As TResult
Return If([some test is true], IfTrueValue, IfFalseValue)
End Function
In words, ComputeReturnValue performs some test (not important right now) and returns different values depending on the result. I have two versions, because sometimes I want to return the result of calling a function to form the result, and sometimes I just want to return fixed values.
The problem is that when I (try to) call overload 1, instead of invoking the right function, the compiler calls overload 2, and returns the Func(Of TSource, TResult) object and not the result of calling the function. I see that this is because overload 2 doesn’t constrain the types, and so a Func is a valid argument for this routine, and I’m willing to believe that the compiler is choosing the overload correctly in this case.
My question is: what is the right way to accomplish this to resolve the ambiguity so that I can pass value or references types and get overload 2, but pass Functions and get overload 1? Can I constrain the types in some way to make this happen? Or should I just name them different names and avoid the problem?
(I know I could just keep the Func version, and pass in a trivial Function() IfTrueValue for when I want to return a value, but I’m trying to make this as syntactic sugary as possible.)
Definitely give them different names. Whenever you fight against overload resolution, think of whoever’s coming after you – and is likely to be less familiar with the code. Anything that’s tricky for you will be even trickier for them, whereas giving the methods different, descriptive names will make everyone’s life better.