Reputation: 45
Well this is one of method to handle DBNull.value
,
But I want a syntax using null-coalescing operator to handle DBNull.value
This will work
decimal UnitPrice = row["UnitPrice"] == DBNull.Value ? 0.00m : (decimal)row["UnitPrice"];
Well I have tried these, none of them works,
decimal UnitPrice = (decimal)row["UnitPrice"] ?? 0.00m
UnitPrice = Convert.ToDecimal(row["UnitPrice"]) ?? 0.00m
UnitPrice = Decimal.Parse(row["UnitPrice"].ToString()) ?? 0.00m
I am getting this
Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'
I may ask the wrong question or the question may be invalid with my knowledge even if so please let there be light :)
Upvotes: 4
Views: 925
Reputation: 43046
The problem is that DBNull.Value is not null. It seems that you want to replace DBNull.Value with 0.0m, but a better solution would be to use nullable types. That is, use decimal?
rather than decimal
. Then you can use the as
operator:
decimal? unitPrice = row["UnitPrice"] as decimal?;
If you can't do that, you can do this instead:
decimal unitPrice = (row["UnitPrice"] as decimal?) ?? 0.0m
or
decimal unitPrice = (row["UnitPrice"] as decimal?).GetValueOrDefault();
A helper function would make it slightly less verbose, if you do this a lot:
T FromObject<T>(object o) where T : struct { return (o as T?).GetValueOrDefault(); }
then
decimal unitPrice = FromObject<decimal>(row["UnitPrice"]);
If you need a non-zero default value:
T FromObject<T>(object o, T defaultValue) where T : struct
{
return (o as T?).GetValueOrDefault(defaultValue);
}
then
decimal unitPrice = FromObject<decimal>(row["UnitPrice"], Decimal.MinValue);
The drawback to this approach is that if you change the underlying type of the database column, you will start getting spurious zeros back instead of exceptions. That's because if the object is, for example, 1.2f
, then o as decimal?
will return null, which will then be replaced by 0.0m. The expression o == DBNull.Value ? 0.0m : (decimal)o
, however, will be equivalent to (decimal)(object)1.2f
, which will fail with an InvalidCastException, which is better than giving all of your products away for free.
Upvotes: 2
Reputation: 101681
decimal
is a value type and cannot be null
. You can use ??
operator with only reference types.
You can keep using first way or you can do something like:
decimal UnitPrice = (object)row["UnitPrice"] ?? default(decimal)
Upvotes: 0