Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding null value in Dataset - DataRow.IsNull method vs ==DbNull.Value - c#

What are the benefits of using the c# method DataRow.IsNull to determine a null value over checking if the row equals DbNull.value?

if(ds.Tables[0].Rows[0].IsNull("ROWNAME")) {do stuff}

vs

if(ds.Tables[0].Rows[0]["ROWNAME"] == DbNull.value) {do stuff}
like image 225
Jarrod Avatar asked Apr 08 '11 18:04

Jarrod


People also ask

Is DBNull equal to null?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value. DBNull. Value is completely different and is a constant which is returned when a field value contains NULL.

What is the difference between DBNull and null?

In an object-oriented programming language, null means the absence of a reference to an object, whereas DBNull represents an uninitialized field or nonexistent database column.


2 Answers

There is no real practical benefit. Use whichever one seems more readable to you.

As to the particular differences between them, the basic answer is that IsNull queries the null state for a particular record within a column. Using == DBNull.Value actually retrieves the value and does substitution in the case that it's actually null. In other words, IsNull checks the state without actually retrieving the value, and thus is slightly faster (in theory, at least).

It's theoretically possible for a column to return something other than DBNull.Value for a null value if you were to use a custom storage type, but this is never done (in my experience). If this were the case, IsNull would handle the case where the storage type used something other than DBNull.Value, but, again, I've never seen this done.

like image 183
Adam Robinson Avatar answered Sep 20 '22 08:09

Adam Robinson


DBNull.Value != null

DBNull.Value stands for a column having the value <NULL>. Pop open a table and return some rows, see if any column in any row contains the <NULL>(ctrl 0) value. If you see one that is equivalent to DBNull.Value.

if you set a value to null or DBNull.Value then you will want to use IsNull(). That returns true if the value was set to either null or DBNull.Value.

Consider the following:

row["myCol"] = null;

row["myCol"] = DBNull.Value

if (row["myCol"] == DBNull.Value) //returns true

if (row["myCol"] == null) //returns false

if (row.IsNull("myCol")) //returns true

The point is if you are just checking for null or DBNull.Value use IsNull, if you are only checking for DBNull.Value explicitly say so and use that.

like image 28
JonH Avatar answered Sep 19 '22 08:09

JonH