john
john

Reputation: 33

ASP.NET MVC Model in View (ViewModel) ternary operator null check

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.

Upvotes: 1

Views: 853

Answers (2)

Lews Therin
Lews Therin

Reputation: 3777

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();

Upvotes: 1

DarthTommy
DarthTommy

Reputation: 457

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();
 }

Upvotes: 0

Related Questions