Question

This is my code..

    object o = DBExecuteScalar(myQuery);
    if ((int.parse(o.ToString())) <= 2 || (o is null))
    {
        // my task....
    }

In this code, 'o is null' part is giving error. Any help how to deal with these both conditions in single if statement.. What I want is that the value of o should be (null,0,1,2). Any help ??

Was it helpful?

Solution

In C#, the is operator checks for type equality. You need to check for null as o == null:

object o = DBExecuteScalar(myQuery);
if ((o == null) || (int.parse(o.ToString())) <= 2)
{
        // my task....
}

You also need to check for null before you try to perform any actions on it

OTHER TIPS

when you reverse the conditions in the if, then it should work.

In your case the ToString is called first on object o. But because o is null this will result in an exception. When you reverse the order of your conditions, then the nullcheck will be first. The second part of the or (||) is only evaluated when the first part is false. This will prevent the exception from occurring

With || operator first condition is evaluated first - you want to check if is null first. Also the int.Parse is not necessary. As RGraham mentioned is null is not a proper way how to check for null.

 if (o == null || o == DBNull.Value || (int)o <= 2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top