In my database, v1 field is nullable field. but I define 0 (default) if the value is null.
public decimal? v1 {
get {
return this._v1;
}
set {
this._v1 = value ?? 0M;
}
}
so now, the v1 is not nullable variable anymore.
but I can not do this,
decimal v2 = v1;
The error message say, Cannot implicitly convert type ‘decimal?’ to ‘decimal’.
In this case, Do I have to convert to decimal, like this?
decimal v2 = Convert.ToDecimal(v1);
It very annoying job. and codes are look dirty too.
Anyone know better solution? please advice me.
No you don’t have to convert the
decimal?, you have access to the underlying value from theNullabletype e.g.Assigning a default value to a
Nullabletype does not make it non-nullable, it just means it has a value. Nullable types have aHasValueproperty which helps you determine this.Just for the record, I wouldn’t recommend defaulting the value to
0it would probably make more sense letting it default tonullconsidering it can indeed be null. If you need to have a default value in your app you will probably want to use theGetValueOrDefaultmethod e.g.