1

I know that the ternary operator ("?") can be used checking if the value is null and if it's not null proceeding to the "chained methods let's call it". Example: Model?.FirstOrDefault(); Why doesn't this work? I want to say "if the Model is not empty call the FirstOrDefault method, else don't do anything". Getting this error

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Linq.Enumerable.FirstOrDefault(...) returned null.

7
  • That's called a null-conditional operator; it isn't ternary. Commented Jun 14, 2018 at 19:34
  • stackoverflow.com/q/24148313/34397 Commented Jun 14, 2018 at 19:35
  • @SLaks I think you meant Null conditional operator. Commented Jun 14, 2018 at 19:36
  • @LewsTherin ok I read the docs anyway it should work, shouldn't it? Why doesn't it work? Commented Jun 14, 2018 at 19:44
  • Is it possible that Model is not null but also contains no elements? Commented Jun 14, 2018 at 20:03

2 Answers 2

1

You can't do this because FirstOrDefault() is an Extension Method.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

The fix would be to just not use the Null Conditional Operator which is just syntactic sugar.

string myVariable;

if (Model != null)
    myVariable = Model.FirstOrDefault();
Sign up to request clarification or add additional context in comments.

Comments

0

Typically I have used the ? for setting accessors for an API data extract as the ? means that that value can be null. I think this is more of what you are looking to do:

if (String.IsNullOrEmpty(TableName.AttributeName))
 {
   FirstOrDefault();
 }

2 Comments

? at the end of a value type declaration (like int?) is a Nullable type and is not the same as a null-conditional operator (?.).
you are right. I guess I misunderstood his intention with the '?'

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.