문제

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 ??

도움이 되었습니까?

해결책

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

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top