Why doesn't the C # Null Conditional operator return a Nullable <T>?
I'm just wondering, "Why doesn't the NULL propagation operator (or can't) give any type information, such as returning null to type Nullable<int>?"
Since it returns nullwithout a type, the resulting value cannot pass the 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:
- Since @ScottChamberlain noted that it
Nullable<string>is not compiled code. But I do not correct it. Since this question has already answered this question, and any body can easily solve the problem that I asked about.
+4
1 answer
, , .? null.
var result = user.Father?.Name.X()
string result;
var testObject = user.Father;
if(!Object.RefrenceEquals(testObject, null))
{
result = testObject.Name.X();
}
else
{
result = null;
}
Father , , .
, .? ,
var result = (user.Father?.Name).X()
string tempResult;
var testObject = user.Father;
if(!Object.RefrenceEquals(testObject, null))
{
tempResult = testObject.Name;
}
else
{
tempResult = null;
}
var result = tempResult.X();
+13