Question

Does any one have a preference on how to check if a value is DBNull? I've found these two statements give me the results I want, but just wondering if there's a preference?

if (any is System.DBNull)

same as:

if (any == System.DBNull.Value)

Thanks!

Was it helpful?

Solution

if (any == System.DBNull.Value) ...

I prefer that one, simply because I read that as comparing values, not types.

OTHER TIPS

I tend to use

if (DBNull.Value.Equals(value)) {
    //
}

or

if (Convert.IsDBNull(value)) {
    //
}

is does not use reflection as Kevlar623 says. It maps to the isinst operation in IL. On that level, comparing performance is downright silly, unless you're working on a missile guidance system.

I use value is DBNull. It just sounds right and as a paranoid developer, I can't trust that the only value ever in existence is DBNull.Value. Bugs happen.

if you're in c#, you should use ==; is uses reflection which is more expensive to compute, especially since there's only ever one instance of System.DBNull.

I like the "is System.DBNull" more because I hate the idea of comparing something to NULL and having it be true. Many other syntaxes (what the hell is the plural of that?) would have anything==NULL return NULL.

I understand that there's DBNull.Value for a reason. I know. I'm listing my PREFERENCE :)

This is a good example of form follows function. Whichever one executes more efficiently is the way to go. What it looks like, reads like, or bad names it calls you is irrelevant. Use the language efficiently, don't mold the language into a new one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top