Checking Nullable Values in .NET


Offen programmer read data from DB & directly start processing those without even verifying it's state wheather it's null or not. This might result into crash at the end.

C# provide the way to check the value of field read from DB are null or not. Have a look at the bellow code first

int transactionId

if (dr["TransactionId"] == DBNull.Value)
   TransactionId = 0;
else
    TransactionId = dr["TransactionId"];

You can later check the value TransactionId to ensure value of the output is null or not. Nullable types gives solution to this problem. You can store the data returned from the database into a nullable variable without worry about an exception being thrown at that time. You still may have to perform the check for a valid value later, depending upon exactly how you are using the variable. You can declare a value type variable as nullable using the "?" type modifier. Nullable types have two read-only properties that you use to get information about the variable. HasValue returns false if the value is null; otherwise, it returns true. If HasValue returns true, you can access the Value property, which contains the currently stored value. If you attempt to use the Value property when HasValue is false, an exception will be thrown. Here is what the example above would look like using a nullable type:

int? TransactionId;
TransactionId = dr["TransactionId"];
if(TransactionId.HasValue)
{
 // Process the data
}
else
{
 // Alternate Flow for Error Handling
}

Nullable types can be used in comparisons and expressions just like normal numeric expressions. If the nullable variable has a non-null value, everything will work as you would expect. If the nullable variable is null, you need to realize that the result of the expression could be null and make sure that case is handled appropriately.


 

Up Next
    Ebook Download
    View all
    Learn
    View all