简体   繁体   中英

C# LINQ NULL check

On my form I want to disable the bt_rent button if the movie has no date in the bringback colum(date type) so it means the dvd is still out and not available for renting:

var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();



if (j.Bringback==null)
{
    elerhetotext.Text = "The dvd is not available for renting";
    bt_rent.Enabled = false;
}
else
{
    elerhetotext.Text = "Rentable";
    bt_rent.Enabled = true;
}

The error I get:

Nullreferenceexpection was unhandled by user code (error at:if (j.Bringback==null)) Object reference not set to an instance of an object.

You are missing validation on j itself. It seems in this case there is no DVD with the name you're looking for so ideally you should validate if j is NULL as well, instead of

if (j.Bringback==null)

Do the following

if (j != null || (j != null && j.Bringback==null))

So you are checking if the DVD exists, and if it does, the 2nd part of the validation is based on j itself, and if Bringback is null.

The Variavle j is a type of object Rental in the given code

<pre>
var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();
</pre>

Chek j is null or not like

<pre>
if (j==null)
{
    elerhetotext.Text = "The dvd is not available for renting";
    bt_rent.Enabled = false;
}
else
{
    elerhetotext.Text = "Rentable";
    bt_rent.Enabled = true;
}
</pre>

The exception means that j itself is null , so you would need to check that j is not null before accessing j 's members:

if (j == null) {
    elerhetotext.Text = "DVD/movie does not exist";
    bt_rent.Enabled = false;
} else if (j.Bringback == null) {
    elerhetotext.Text = "The dvd is not available for renting";
    bt_rent.Enabled = false;
} else {
    elerhetotext.Text = "Rentable";
    bt_rent.Enabled = true;
}

This is only an addition to the accepted answer written by mez


Using C# 6.0's null-conditional operator one could rewrite the code as:

 var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault(); // checks whether `j´ is null or `j.Bringback´ is null if (j?.Bringback == null) { elerhetotext.Text = "The dvd is not available for renting"; bt_rent.Enabled = false; } else { elerhetotext.Text = "Rentable"; bt_rent.Enabled = true; } 


The statement

 if (j != null || (j != null && j.Bringback==null)) 

would be rewritten as

 if (j?.Bringback == null) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM