Check is null in c#

You are fetching values from DB and not sure if they have a null value in them.
If you directly access them without checking for a null compiler would throw an exception

Suppose r is your data reader object and you are assigning phone no. from DB to a string variable
It can easily be checked for null like this

[code]

var phone = string.empty;
If (r["phone"]!=null)
phone = r["phone"].ToString();

[/code]

Another simpler way of doing this in .Net Framework 4.0 and up is

[code]

var phone = r["phone"].ToString() ?? string.empty;

[/code]

It simply means if r[“phone”] is null return empty string without throwing an exception

Get Free Email Updates!

Signup now and receive free offers, discounts & coupon codes

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge