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.
You should change the line
this.MyDateTime = myNewDT.MyDateTime.Value;to justthis.MyDateTime = myNewDT.MyDateTime;The exception you were receiving was thrown in the
.Valueproperty of the NullableDateTime, as it is required to return aDateTime(since that’s what the contract for.Valuestates), but it can’t do so because there’s noDateTimeto return, so it throws an exception.In general, it is a bad idea to blindly call
.Valueon a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a.HasValuecheck).EDIT
Here’s the code for
DateTimeExtendedthat does not throw an exception:I tested it like this:
Adding the
.Valueonother.MyDateTimecauses an exception. Removing it gets rid of the exception. I think you’re looking in the wrong place.