1

In C#, I have a List that has a fixed number of items, 6 to be precise. These are called out in a Razor template, by using a Find(). However, if that Find cannot find the associated list item, it throws a NullReference exception.

The problem is, if an item doesn't exist, then the view won't load.

I need it to instead provide an empty string to the variable.

I've tried:

var video1 = Model.Videos.FirstOrDefault(x => x.VideoType == "Video1") ?? string.Empty;

But this still returns null.

Could anybody help in getting this to work?

TheJackah
  • 29
  • 1
  • 7

2 Answers2

3

You could use the null-propagation operator as described in C# : The New and Improved C# 6.0

An example of usage would be:

var video1 = Model?.Videos?.FirstOrDefault(x => x.VideoType == "Video1") ?? string.Empty;

The above will ensure that no NullReferenceException will be thrown when Model or Videos are null.

mishamosher
  • 1,003
  • 1
  • 13
  • 28
1

It's throwing a NullReferenceException because you are trying to get a property/call a function on a null object.

Looking at your code, we are calling Videos on Model, and then calling FirstOrDefault on Videos.

A NullReferenceException being thrown means that either:

  • Model is null, so when you call Model.Videos you get a NullReferenceException (because you cannot get the property Videos of null)
  • Videos is null, so when you call Videos.FirstOrDefault you get a NullReferenceException (because you cannot call the function FirstOrDefault on null.
James Monger
  • 10,181
  • 7
  • 62
  • 98