DBNull and DBNull.Value.Equals ()

I'm curious what are the pros and cons of using if(some_value is DBNull) versus if(DBNull.Value.Equals(some_value)) . Personally, I prefer if(some_value is DBNull) because I find it more readable. I know that Microsoft recommends using if(DBNull.Value.Equals(some_value)) in accordance with https://msdn.microsoft.com/en-us/library/system.dbnull%28v=vs.110%29.aspx .

+7
c # dbnull
source share
3 answers

I would go the DBNull.Value.Equals path.

Why?

Beacuse is checks for type equality. He must look for the type of left hand and match it with the right type, which he must also look for. After that, it can compare types, most likely by checking referential equality.

This will be less efficient than just checking the reference equality that DBNull.Value.Equals does. Since there is only one instance of DBNull.Value , this check is very accurate and very fast.

+2
source share

value is DBNull really checks if value instance of the DBNull class, while value == DBNull.Value actually does a reference comparison between value and a single instance of the singleton DBNull class.

value is DBNull checks if value instance of DBNull , which is only possible if value == DBNull.Value , since DBNull is single.

The advantage of using value == DBNull.Value is that it does a direct comparative comparison, which will be more efficient than defining types for comparing is DBNull .

+2
source share

some_value is DbNull : type check DBNull on type DBNull . This can be used if you can either create an instance of DBNull OR or inherit it. But no, this class has private constructors and is sealed.

DBNull.Value.Equals(some_value) : checks the value values ​​of some_value to the value represented by DBNull.Value .

0
source share

All Articles