Nullable Object Must Have a Value?

Nullable Object Must Have a Value?

On the line: bool travel = fill.travel.Value; I am getting the following error:

Nullable object must have a value

and i am not sure why. All I want to do is get the value in the database of travel which is currently false. Any help would be appreciated.

using (var db = new DataClasses1DataContext())
{
    var fill = (from f in db.expenseHdrs
                where f.rptNo == getPkRowReport()
                select f).FirstOrDefault();

    txtReportDesc.Text = fill.description;
    txtPeriod.Text = fill.period;
    txtPurpose.Text = fill.purpose;

    bool travel = fill.travel.Value;
    chkTravel.Checked = travel 
 }
9

8 Answers

You can always switch to

 fill.travel.GetValueOrDefault()

To provide the default (false), or the value of the boolean column from the database. Or you can specify the default with an overload. Either way, the nullable currently doesnt have a value, which is why you get that exception.

You are trying to access property from the nonexistent object (your fill.travel is null, and you calling prop from it), you can use coalesce operator (.Net 4.0):

bool travel = fill.travel ?? false;

You will get a InvalidOperationException if you access the Nullable.Value property when the HasValue property is false.

You can check if nullable variable has some value like this before your actually access its value

if(fill.travel.HasValue)
{
   bool travel = fill.travel.Value;
}

The value coming from the database is a nullable boolean. When you call Nullable.Value, and the value is null, you will get this exception. Consider checking the property Nullable.HasValue before calling .Value.

I had this happen because there was code like this:

bool? someVariable = (bool)someNullableBool;

The someNullableBool was null and this error was thrown.

The solution was to re-write it as:

bool? someVariable = (bool?)someNullableBool;
1

Null is not false. See Eric Lippert's blog article series about this at:

You need to process a null result into a false, if that is how you want to translate it.

To make this case clear, consider this code:

bool travel;
bool? temptravel = fill.travel.Value;
if( temptravel == true )
    travel = true;
else
    travel = false;

Or just use Val Bakhtin's solution if you are using .Net 4

You can always use the classic C ? operator like this:

bool travel = (fill.travel == null ? false : fill.travel.Value);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.