简体   繁体   中英

Why C# Null Conditional operator does not return Nullable<T>?

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:

  • As @ScottChamberlain noted that 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM