Is there any difference between null and System.DBNull.Value? If yes, what is it?
I noticed this behavior now -
while (rdr.Read()) { if (rdr["Id"] != null) //if (rdr["Id"] != System.DBNull.Value) { int x = Convert.ToInt32(rdr["Id"]); } }
While I retrieve data from the database using a sql datareader, though there is no value returned if(rdr["Id"] != null)
returned true
and eventually threw an exception for casting a null as integer.
But, this if I use if (rdr["Id"] != System.DBNull.Value)
returns false
.
What's the difference between null and System.DBNull.Value?
In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.
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.
DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as Nothing , which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string ( "" ), which is sometimes referred to as a null string.
The two possible reasons I know of for the does not allow DBNull error are: Columns are in the wrong order, which is solved by either putting them in the same order as their Database Ordinal, or by performing a Column Mapping. KeepNulls is enabled, and DBNull. Value (or null ?) are set in the DataTable.
Well, null
is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value
, is a valid reference to an instance of System.DbNull
(System.DbNull
is a singleton and System.DbNull.Value
gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null
, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null
represents an invalid reference. The class System.DbNull
represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null
) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull
is an example of.
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