Evaluating DBNull: checking for equality or using the is operator?

I have a C # question. I just wanted to ask the community about using System.DBNull in combination with using DataReader.

When querying a database and checking for null values, which is more appropriate / preferred?

Using the operator:

reader["fieldname"] is DBNull 

or just check the value:

 reader["fieldname"] == DBNull.Value 

Both seem to work. I just wanted other opinions.

+6
source share
3 answers

Given that DBNull.Value is the only nonzero value for the DBNull class, the two are equivalently equivalent. What do you think is more readable? Personally, I really like the first version, but your mileage may vary.

This is unlikely to be a performance issue in any case.

+7
source

You can also check this as follows:

 Convert.IsDBNull(reader["field name"]); 
+4
source

I think that Microsoft usually recommends using Convert.IsDBNull, since they usually want you to use Convert for more verification of conversions and equivalence.

From http://msdn.microsoft.com/en-us/library/system.dbnull.aspx :

You can determine if the value obtained from the database field is DBNull by passing the value of this field to DBNull.Value.Equals. However, some languages ​​offer methods for delivering database objects that make it easier to determine if the value of a database field is DBNull.Value. These include the Visual Basic IsDBNull function, the Convert.IsDBNull method, the DataTableReader.IsDBNull method, and the IDataRecord.IsDBNull method.

+2
source

Source: https://habr.com/ru/post/918487/


All Articles