[c#] nullable object must have a value

There is paradox in the exception description: Nullable object must have a value (?!)

This is the problem:

I have a DateTimeExtended class, that has

{
  DateTime? MyDataTime;
  int? otherdata;

}

and a constructor

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime.Value;
   this.otherdata = myNewDT.otherdata;
}

running this code

DateTimeExtended res = new DateTimeExtended(oldDTE);

throws an InvalidOperationException with the message:

Nullable object must have a value.

myNewDT.MyDateTime.Value - is valid and contain a regular DateTime object.

What is the meaning of this message and what am I doing wrong?

Note that oldDTE is not null. I've removed the Value from myNewDT.MyDateTime but the same exception is thrown due to a generated setter.

This question is related to c# nullable invalidoperationexception

The answer is


I got this solution and it is working for me

if (myNewDT.MyDateTime == null)
{
   myNewDT.MyDateTime = DateTime.Now();
}

When using LINQ extension methods (e.g. Select, Where), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated && and || are converted to SQL's eager AND and OR. This can cause problems when you're checking for null in your lambda.

Example:

MyEnum? type = null;
Entities.Table.Where(a => type == null || 
    a.type == (int)type).ToArray();  // Exception: Nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}

Looks like oldDTE.MyDateTime was null, so constructor tried to take it's Value - which threw.


In this case oldDTE is null, so when you try to access oldDTE.Value the InvalidOperationException is thrown since there is no value. In your example you can simply do:

this.MyDateTime = newDT.MyDateTime;

I got this message when trying to access values of a null valued object.

sName = myObj.Name;

this will produce error. First you should check if object not null

if(myObj != null)
  sName = myObj.Name;

This works.


Try dropping the .value

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}