I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:
public decimal myDecimal{ get; set; }
and then I have
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
I am trying:
if (rdrSelect[23] != DBNull.Value)
{
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
}
But I am getting this:
the result of the expression is always 'true' since a value of type 'decimal' is never equal to null
How can I check if that decimal number has some value?
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable
object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
decimal
is a value type
in .NET. And value types can't be null
. But if you use nullable type
for your decimal
, then you can check your decimal
is null
or not. Like myDecimal?
Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
if (myDecimal.HasValue)
But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal
.
You can also create a handy utility functions to handle values from DB in cases like these. Ex. Below is the function which gives you Nullable Decimal from object type.
public static decimal? ToNullableDecimal(object val)
{
if (val is DBNull ||
val == null)
{
return null;
}
if (val is string &&
((string)val).Length == 0)
{
return null;
}
return Convert.ToDecimal(val);
}
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull
object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull
, or replace your null check afterwards with a check on rdrSelect[23]
for DBNull
.
Source: Stackoverflow.com