Named arguments and generic type inference in C# 4.0

Solution 1:

Inference is not something that will work at many nested levels in compilation. It is kind of a guess based on arguments supplied. I feel the compiler writers did not consider inferring logic along with named parameter. If you consider abstract syntax tree, Even though the logic is same, but both F(()=>"xyz") And F(f:()=>"xyz") Are different abstract syntax trees from compiler's perspective.

I feel it's just a rule missed by compiler designer where even the compiler itself is a program with huge set of rules. One rule matches first case but no rule matches second one. It may be conceptually right but compiler is just a program and all rules are human coded.

Ok, I guess as others have determined, its a bug and should be reported to Microsoft !!

Solution 2:

Just want to let you know this is a bug specific to C# (and @leppie I have confirmed it does fail with the standard csc.exe, not even in Visual Studio). Redundantly specifying a named argument shouldn't cause a change in behaviour at all.

The bug has been reported at Microsoft Connect.

The equivalent VB works fine (because it does compile I added a little bit to confirm the runtime behaviour is as expected):

Imports System

Module Test
  Function F(Of T)(ByVal fn As Func(Of T)) As T
    Return fn()
  End Function

  Function Inc(ByRef i as Integer) As String
    i += 1
    Return i.ToString
  End Function

  Sub Main()
    Dim s As String
    s = F(Of String)(Function()"Hello World.")
console.writeline(s)
    s = F(Function()"Hello, World!")
console.writeline(s)
    s = F(Of String)(fn:=Function()"hello world.")
console.writeline(s)
    s = F(fn:=Function()"hello world")
console.writeline(s)
    Dim i As Integer
    Dim func As Func(Of String) = Function()"hello world " & Inc(i)
    s = F(Of string)(func)
console.writeline(s)
    s = F(func)
console.writeline(s)
    s = F(Of string)(fn:=func)
console.writeline(s)
    s = F(fn:=func)
console.writeline(s)
  End Sub
End Module

Output:

Hello World.
Hello, World!
hello world.
hello world
hello world 1
hello world 2
hello world 3
hello world 4