Yathish kumar
Yathish kumar

Reputation: 35

Need to check the condition if the value is `YES` or `NO`. And for the invalid values it should throw some error message

Here is the code what I have tried:

  if(!string.IsNullOrEmpty(Taskinfo.DoRollOver) &&(Taskinfo.DoRollOver != "YES" || Taskinfo.DoRollOver != "NO"))
  {
     throw new DataException("DoRollOver is not valid");
  }

But if I try to give the valid data such as YES or NO still it throws an exception.

Upvotes: 1

Views: 1795

Answers (5)

Vytautas Plečkaitis
Vytautas Plečkaitis

Reputation: 861

I'd say that you inverted logic a little bit.

if((Taskinfo.DoRollOver == "YES")||(Taskinfo.DoRollOver == "NO"))
{
  // do something
}
else
  throw new DataException("DoRollOver is not valid");

Also if TaskInfo.DoRollOver is string I would use TaskInfo.DoRollOver.ToUpper() - just in case.

Upvotes: 1

Vashdev Heerani
Vashdev Heerani

Reputation: 679

Try to change conditions like this

if (string.IsNullOrEmpty(Taskinfo.DoRollOver) ||(Taskinfo.DoRollOver != "YES" && T0askinfo.DoRollOver != "NO"))
{
    throw new DataException("DoRollOver is not valid");
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 311163

This condition is always true. If Taskinfo.DoRollOver is "YES" it is not equal to "NO", and vise-versa. You should use the && logical operator, not the || logical operator:

if (string.IsNullOrEmpty(Taskinfo.DoRollOver) ||
    (Taskinfo.DoRollOver != "YES" && // Here!
     T0askinfo.DoRollOver != "NO"))
{
    throw new DataException("DoRollOver is not valid");
}

Upvotes: 2

M Bagheri
M Bagheri

Reputation: 21

maybe this can help you

 if(!string.IsNullOrEmpty(Taskinfo.DoRollOver))
  {
    if(Taskinfo.DoRollOver != "YES" && Taskinfo.DoRollOver != "NO")
      {
       throw new DataException("DoRollOver is not valid");
      }
  }else
  {
    //Do Something
  }

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37347

Aiming for readability and simplicity I would split conditions:

if(Taskinfo.DoRollOver == "YES")
{
  // do smoething
}
else if(Taskinfo.DoRollOver == "NO")
{
  // do smoething else
}
else
  throw new DataException("DoRollOver is not valid");

Upvotes: 1

Related Questions