0

I'm trying to get record and store data into variable

Image Image = _context.Images.FirstOrDefault(u => u.imgID== Images.imgID);
var ImageName = Image.Name;

I'm getting this error. probably something is null in record.

System.NullReferenceException: 'Object reference not set to an instance of an object.'
    
    <Image>5__11 was null.

I'm trying to do null check but probably I do something wrong

if (Image == null || Image.ImageName == null) Image.ImageName = "";

But I'm getting same error. How can I fix this ?

David
  • 4,332
  • 13
  • 54
  • 93
  • You should be doing that null check before you do `var ImageName = Image.Name;` You could include the null checks as part of the assignment like this: `var ImageName = Image?.Name ?? "";` – itsme86 Jun 25 '20 at 21:51
  • 1
    You can't set the `ImageName` property on the `Image` object if the `Image` object is null. Try `var ImageName = Image?.Name ?? string.Empty;` That will set `ImageName` to be the empty string if `Image` or `Image.Name` is null. – Heretic Monkey Jun 25 '20 at 21:54
  • 1
    Does this answer your question? [Checking if an object is null in C#](https://stackoverflow.com/questions/6417902/checking-if-an-object-is-null-in-c-sharp) – Heretic Monkey Jun 25 '20 at 21:58

2 Answers2

2

You can do simple null check as follow:

Image Image = _context.Images.FirstOrDefault(u => u.imgID== Images.imgID);

// If Image is not null, then use Image.Name, else when it is null, then assing empty string.
var ImageName = Image != null ? Image.Name : String.Empty;

Also depends on your function that this is in, but you can utilize something called Null guards.

Tomáš Filip
  • 727
  • 3
  • 6
  • 23
  • 1
    Or `var ImageName = Image?.Name ?? string.Empty;`, though that would also assign `string.Empty` if `Name` was null. – Rufus L Jun 25 '20 at 22:31
  • @RufusL Agreed. It is basically the same, but since he is begginer my version should be more easy to read for him. – Tomáš Filip Jun 26 '20 at 08:48
1

David,

When you use FirstOrDefault it means that if it can't find any item in your _context.Images collection that matches your criteria, it will return null. So therefore in your first line, imagine it results in this:

Image Image = null;

This means that the 2nd line will return you a NullReferenceException because you are essentially doing this in the code:

var ImageName = null.Name; // YOU CAN'T ACCESS the Name property because the Image was null!

Does this make sense? To avoid the NullReferenceException, you should always check for null before trying to access its properties. Like this:

Image Image = _context.Images.FirstOrDefault(u => u.imgID== Images.imgID);

if (Image != null)
{
    var ImageName = Image.Name;
}
Tam Bui
  • 2,940
  • 2
  • 18
  • 27