[c#] Check if decimal value is null

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?

This question is related to c# asp.net decimal

The answer is


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP