Alan2
Alan2

Reputation: 24572

Is there a way to force a variable to 0 if an assignment returns a null?

I have this code:

var btns = "(BTNACOUNT + BTNBCOUNT + BTNCCOUNT + BTNDCOUNT)";
int abc = db2.ExecuteScalar<int>("SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd);

The query on the right will return a number or null.

Is there a one line way to set the value of abc to a 0 if a null is returned on the right ?

Upvotes: 0

Views: 69

Answers (2)

mordechai
mordechai

Reputation: 851

ExecuteScalar returns DBNull instead of null, you can check if abc is DBNull and set the value;

if(abs is DBNull) 
abc=0;

alternative, you can wrap your sql statement with select isnull((original statement...),0)

int abc = db2.ExecuteScalar<int>("select isnull((SELECT " + btns + " FROM CLICKHISTORY WHERE YYMMDD = " + yymmdd),0)");

Upvotes: 0

hnefatl
hnefatl

Reputation: 6037

Use the null coalescing operator ??:

int abc = db2.ExecuteScalar<int>(...) ?? 0;

If the LHS of the operator is non-null, it returns that - otherwise, it returns the RHS (kind of like a default).

Alternatively, there's Nullable<T>.GetValueOrDefault() and Nullable<T>.GetValueOrDefault(T), which do much the same thing but are more readable:

int abc = db2.ExecuteScalar<int>(...).GetValueOrDefault(0);

Upvotes: 5

Related Questions