问题
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.
回答1:
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.
回答2:
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>
回答3:
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;
}
回答4:
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)
来源:https://stackoverflow.com/questions/23193461/c-sharp-linq-null-check