Looks like IIf
works just fine:
Dim foo As Func(Of Integer) = IIf(True, Nothing, Function() 0)
But I have to say, I have no idea why.
Update
OK, I think I have a reason. Compiler optimizes your code to following:
Dim foo As Func(Of Integer) = New Func(Of Integer)(Nothing.Invoke)
and that's why you get an exception.
Even when you don't use True
as condition, and try to use variable
Dim t = Integer.Parse(Console.ReadLine()) < 10
Dim foo As Func(Of Integer) = If(t, Nothing, Function() 0)
it's being transformed into:
Dim foo As Func(Of Integer) = New Func(Of Integer)((If((Integer.Parse(Console.ReadLine()) < 10), Nothing, New VB$AnonymousDelegate_0(Of Integer)(Nothing, ldftn(_Lambda$__1)))).Invoke)
which will throw exception anyway.