4

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.
2
  • 6
    Your example is not a good one, you can't have a Nullable<string> because string is a class not a struct and the T in Nullable<T> is restricted to structs. Commented Feb 7, 2017 at 7:16
  • Great point for T is restricted to structs. Thanks for point it out. Learn new things today.-:) Commented Feb 7, 2017 at 14:18

1 Answer 1

13

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.