The output of stringVar.Value
and stringVar
in second statement are same. I just want to know when to use stringVar.Value
and stringVar
.
var stringVar= dbContext.tbl.FirstOrDefault(x => x.id == id)?.ColumnName;
return stringVar!= null ? stringVar.Value : 0;
CodePudding user response:
.Value
is a property of Nullable
data type. When there is class member defined with Nullable data type, then to get actual value, you should use .Value
property.
In your case, you used FirstOrDefault()
with Null propagation
operator, which will propagate null if there is no value found for specific id
.
In next line you checked if the stringVar
is not null
then to get actual value you used .Value
property otherwise return 0
CodePudding user response:
Just refer to the declaration of Nullable<T>
, Value
is read-only and gives the actual value.
[Serializable]
[NonVersionable] // This only applies to field layout
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Nullable<T> where T : struct
{
private readonly bool hasValue; // Do not rename (binary serialization)
internal T value; // Do not rename (binary serialization) or make readonly (can be mutated in ToString, etc.)
[NonVersionable]
public Nullable(T value)
{
this.value = value;
hasValue = true;
}
public readonly bool HasValue
{
[NonVersionable]
get => hasValue;
}
public readonly T Value
{
get
{
if (!hasValue)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_NoValue();
}
return value;
}
}