I have had the following code to assign a value to nullable int variable:
ParentCommentId = lac.ParentCommentId ?? lac.ParentCommentId.Value,
However, with this code I was receiving the Nullable object must have a value
error.
Then, I revised the code as follows:
ParentCommentId = lac.ParentCommentId.HasValue ? lac.ParentCommentId.Value : null,
And, now everything works fine. I wonder why ??
operand does not work in this case. Am I using it wrong? In what cases, ??
would be more suitable?
Nullable object must have a value
is a runtime exception that occurs when you try to access .Value
of a nullable with .HasValue
false.
Your code:
ParentCommentId = lac.ParentCommentId ?? lac.ParentCommentId.Value
gets translated to:
if (lac.ParentCommentId.HasValue)
{
ParentCommentId = lac.ParentCommentId.Value;
}
else
{
ParentCommentId = lac.ParentCommentId.Value;
}
As you can see, both branches are doing the same and you would be accessing .Value
even if HasValue
is false (and will result in that exception).
The operator ??
is used to take the first not-null value. You can write
var value = value1 ?? value2 ?? value3;
The first of value1
, value2
, value3
that is not null
will be assigned to value
, if all are null
then value
will be set to null
.