Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise usage of DBNull? (Ternary?)

It seems that there's some type confusion in the ternary operator. I know that this has been addressed in other SO threads, but it's always been with nullables. Also, for my case I'm really just looking for a better way.

I'd like to be able to use

proc.Parameters[PARAM_ID].Value = 
    string.IsNullOrEmpty(dest.Id) ? DBNull.Value : dest.Id;

but instead I'm stuck with this:

if (string.IsNullOrEmpty(dest.Id))
{
    proc.Parameters[PARAM_ID].Value = DBNull.Value;
}
else
{
    proc.Parameters[PARAM_ID].Value = dest.Id;
} 

The ternary operator fails because there's no conversion possible between DBNull and string, and as silly as that seems considering Value is object, the compiler kicks it back to me and I'm forced to care. The answer to the nullable version of this question is to just cast null to string and be done with it; DBNull can't be cast to string, though, so no luck there.

Is there a more concise way to do this (without using nullables, by the way?)

Thanks!

like image 349
bwerks Avatar asked Aug 09 '10 22:08

bwerks


1 Answers

You could change your first statement to:

proc.Parameters[PARAM_ID].Value = 
    string.IsNullOrEmpty(dest.Id) ? (object)DBNull.Value : dest.Id;
like image 164
Jacob Avatar answered Oct 22 '22 06:10

Jacob