I'm facing the following error while applying a null coalescing operator.
private decimal _currentImpulseId;
// ... later on used in public property getter as follows
public decimal CurrentImpulseId
{
get { return _currentImpulseId ?? 0M; }
set { _currentImpulseId = value; }
}
Following error is returned:
Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'
Why doesn't this work? Does the null coalescing operator not work with decimals or am I missing something here? I know how I can work around this without using the operator, but this somewhat baffled me so I wonder if you know the correct answer on this?
Thanks!
You are getting this error because
decimal
is a value type, not a nullable value type (e.g.decimal?
) or a reference type.From MSDN:
The default value of a variable of type
decimal
is zero, so I am not quite sure why you would want to use this operator in this scenario.Also, the backing field variable (
_currentImpulseId
) is not required as of .NET 3.0, since the introduction of auto-implemented properties means you can just write