Question

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!

Was it helpful?

Solution

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:

...and is used to define a default value for nullable value types or reference types

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

public decimal CurrentImpulseId { get; set; }

OTHER TIPS

Because decimal is a value type see HERE, you have to make it nullable. Try

private decimal? _currentImpulseId;
// ... later on used in public property getter as follows

public decimal? CurrentImpulseId
{
  get { return _currentImpulseId ?? 0M; }
  set { _currentImpulseId = value; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top