In my experience DBNull can be interpreted as database null. If the database returns a null, you need to check it against DBNull.value to catch it.
Cases where you would check for null
In the code
null is what gets printed out.
In the code below, we try to access a non existent field
again null is printed out.
Cases where you would check for DBNull.value
Here dr is an instance of the SqldataReader class. Assume that the database returns null as the value for the column "xxx"
However note that neither checking null of nor DBNull.value will work if the index is out of range. If we check for an index or a column that doesn't exist, it will throw an index out of range exception.
Cases where you would check for null
In the code
int? i=null;
if (System.DBNull.Value.Equals(i))
{
Console.WriteLine("DBNull");
}
else if (i == null)
{
Console.WriteLine("null");// code enters here
}
In the code below, we try to access a non existent field
DataSet ds = new DataSet();
if (System.DBNull.Value.Equals(ds.Tables[""]))
{
Console.WriteLine("DBNull");
}
else if (ds.Tables[""]== null)
{
Console.WriteLine("null");//code enters here
}
while (dr.Read())
{
if (dr["xxx"]==null)
{
Console.WriteLine("NULL");
}
else if (System.DBNull.Value.Equals(dr["xxx"]))
{
Console.WriteLine("DBNull"); // code enters here
}
}
DBNull is what gets printed out
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator