I am just curious about that "Why null propagation operator does (or can) not give any information about the type such as returning null in type of Nullable<int>
?"
Since it returns null
without type, resulting value can not pass an extension method.
class User {
public string Name { get; set; }
public User Father { get; set; }
}
var user = new User ( );
public static class Extensions {
public static string X (this string p) => "EXTENSION METHOD";
}
C# Interactive Window:
> var user = new User();
> user.Father
null
> user.Father.Name
Object reference not set to an instance of an object.
> user.Father?.Name
null
> user.Father?.Name.X()
null
EDIT:
Nullable<string>
is a non compilable code.
But I am not fixing it. Because the question already answered with this example, and any body can easily get the problem what I asked for.The problem is not the return type, it is the fact that .? does not process the right hand side at all in the event of null.
You could think of
var result = user.Father?.Name.X()
executed as
string result;
var testObject = user.Father;
if(!Object.RefrenceEquals(testObject, null))
{
result = testObject.Name.X();
}
else
{
result = null;
}
Because Father
was null nothing beyond it was executed.
If you add a parentisis to it to force the result of the .?
to be used with the extension method it works fine
var result = (user.Father?.Name).X()
executed as
string tempResult;
var testObject = user.Father;
if(!Object.RefrenceEquals(testObject, null))
{
tempResult = testObject.Name;
}
else
{
tempResult = null;
}
var result = tempResult.X();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With