I am sorry for asking this stupid question.

I know that ternary operator has made developers' life very easy. I have a question in my mind.

Suppose I have to check whether something is `DBNull.Value`

or not, if it is then assign '0' or keep the value as it is. I do this like below

`string str = dt.Rows["Col"] == DBNull.Value ? "0" : dt.Rows["Col"].ToString(): `

It works fine but if my expression is big then it results ugly code like

`int CL = (int)Math.Round((Convert.ToInt32(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'") == DBNull.Value ? 0 : dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'")) * Total_Leaves) / 100d); `

look at repetition of code in that. Can I make it look little simpler.

I know `??`

is a cleaner way to check for `null`

is there anything for `DBNull.Value`

or "" ?

Thanks

-------------Problems Reply------------

I used extension method for that. Thanks to `mike z`

for the comment :)

`public static class Extensions`

{

public static object DefaultIfDBNull(this object obj, object _default)

{

return obj == DBNull.Value ? _default : obj;

}

}

and calling code

`int CL = (int)Math.Round((Convert.ToInt32(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'").DefaultIfDBNull(0)) * Total_Leaves) / 100d);`

though it is not a proper answer but it make it cleaner and usable :)

Can I make it look little simpler.

Yes, at the minute your method checks if compute is null and then returns 0 if it is so you can start by extracting the common method

`var computed = dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'");`

int CL = (int)Math.Round((Convert.ToInt32(computed == DBNull.Value ? 0 : computed) * Total_Leaves) / 100d)

But you can go further by putting this into a method and then just returning 0 if it is null

`private int GetComputed(int Total_Leaves)`

{

var computed = dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'");

if(computed == DBNull.Value)

return 0;

return (int)Math.Round(Convert.ToInt32(computed) * Total_Leaves) / 100d;

}

You could wrap the test in a simple method something like the following:

`public static string GetString(Object testObject)`

{

return testObject == DBNull.Value ? "0" : testObject.ToString();

}

Its basically the same but you don't have your ternary test all over the place.

Your code would be something like:

`(int)Math.Round((Convert.ToInt32(GetString(dtByType.Compute("sum(NumberOfLeaves)", "Type = 'Casual Leave (Percent)'"))) * Total_Leaves) / 100d);`

It requires you to convert the string result though - so not a perfect solution for all cases.