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}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With