MothraTL
MothraTL

Reputation: 229

evaluating DBNull: checking for equality or using the 'is' operator?

I've got a C# question. I just wanted to ask the community about the use of System.DBNull in conjunction with using a DataReader.

When querying a database and checking for null values, which is more appropriate/preferred?

Using the 'is' operator:

reader["fieldname"] is DBNull

or just checking the value:

reader["fieldname"] == DBNull.Value

Both seem to work. I just wanted to get some other opinions.

Upvotes: 6

Views: 3548

Answers (3)

Rich
Rich

Reputation: 2347

I think Microsoft generally recommends using Convert.IsDBNull since they tend to want you to use Convert for most conversion and equivalency checking.

From http://msdn.microsoft.com/en-us/library/system.dbnull.aspx:

You can determine whether a value retrieved from a database field is a DBNull value by passing the value of that field to the DBNull.Value.Equals method. However, some languages and database objects supply methods that make it easier to determine whether the value of a database field is DBNull.Value. These include the Visual Basic IsDBNull function, the Convert.IsDBNull method, the DataTableReader.IsDBNull method, and the IDataRecord.IsDBNull method.

Upvotes: 2

aleroot
aleroot

Reputation: 72646

You can check also in this way :

Convert.IsDBNull(reader["field name"]);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502116

Given that DBNull.Value is the only non-null value for the DBNull class, the two are effectively equivalent. Which do you find more readable? Personally I quite like the first version, but your mileage may vary.

It's unlikely to be a problem in terms of performance either way.

Upvotes: 7

Related Questions