I am using a Func in my WPF application, and before initializing it, I tried to assign it to another variable. Here’s what I encountered:
Code:
Func<string> GetFunc;
Case 1:
var func = GetFunc();
This results in a NullReferenceException, indicating that GetFunc was null.
Case 2:
var func = GetFunc;
In this case, no exception is thrown, and func is simply assigned the value null.
Can anyone explain why I get a NullReferenceException
when using ()
but not when assigning the delegate directly without ()
?
Imagine we had a similar situation that didn't involve delegates, or even fields - just local variables so it's really clear that the value is a null reference:
string x = null;
// Case 1:
var y = x; // No exception
// Case 2:
var y = x.ToUpperInvariant(); // Exception
Hopefully that's entirely familiar, and the cause of the exception is obvious.
Now let's bring delegates back in, but remove the C# shorthand for invocation:
Func<bool> x = null;
// Case 1:
var y = x; // No exception
// Case 2:
var y = x.Invoke(); // Exception
All I've done is change the type of x
and change the method being invoked from ToUpperInvariant
to Invoke
.
Now, x()
is just a shorthand C# provides for x.Invoke()
- so they should behave the same way.
At this point, it should feel entirely natural that copying the delegate reference to another variable doesn't throw an exception even if that reference is null, but invoking the delegate does throw an exception.