Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 211
MothraTL Avatar asked Jun 19 '12 15:06

MothraTL


People also ask

How do you check for DBNull?

The only way to test for a DbNull value is to use IsDbNull.

What does DBNull value mean?

The DBNull class represents a nonexistent value. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.

How do you use DBNull value?

If a database field has missing data, you can use the DBNull. Value property to explicitly assign a DBNull object value to the field. However, most data providers do this automatically. To evaluate database fields to determine whether their values are DBNull, you can pass the field value to the DBNull.

What is DBNull in VB net?

The System. DBNull value indicates that the Object represents missing or nonexistent data.


1 Answers

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.

like image 99
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet