Home > Mobile >  Checking if 2 variables are not the same type using the "is not" operator doesn't wor
Checking if 2 variables are not the same type using the "is not" operator doesn't wor

Time:03-03

So i am trying to know if a variable is NOT a BuiltInClass type. This BuiltInClass type is just a class that i've written in C#. After a StackOverflow search i saw that using the "is" and "is not" operator i could test if a variable is a certain type. Now, i tried this and it is working, but for some reason if i put that condition in an if-statement it doesn't work.

This is my code to check the types. I left some additional info in the comments.

Console.WriteLine(value.GetType()); //Prints Acrylian.BuiltInClass
Console.WriteLine($"value is BuiltInClass == {value is BuiltInClass}"); //Prints "value is BuiltInClass == True"

if (value is not BuiltInClass || value is not ClassValue) // "is not" operator so should return false
{                                                           //but this code is still run
    Console.WriteLine("Setting context");
    value.SetContext(context);
}

Here is my "value" variable definition:

dynamic? value = context.symbolTable.Get(varName);

I just don't get why on line 1 and 2 in the snippet it clearly says that they are the same type but the code in the if statement still gets run.

Just to make it clear: I know that i'm using the "is NOT" operator but this should make the code DON'T run when they are the same type right?

Regards

CodePudding user response:

I found the solution thanks to the comment section. So i changed if (value is not BuiltInClass || value is not ClassValue) to if (!(value is BuiltInClass || value is ClassValue)) and now it works.

CodePudding user response:

You have misunderstood the boolean expression.

Suppose value is of type BuiltInClass:

Then

  • value is not BuiltInClass will be false.
  • value is not ClassValue will be true.

Thus

value is not BuiltInClass || value is not ClassValue

resolves to

false || true => true

You "fixed" this by using if (!(value is BuiltInClass || value is ClassValue)) instead, but that is NOT equivalent to your original code!

It would be equivalent to this:

if (value is not BuiltInClass && value is not ClassValue) 

Note the use of && instead of ||.

For more information about boolean transforms, see De Morgan's laws.

In particular, note the transformation:

not (A or B) = (not A) and (not B)

Your fix is not (A or B), but you could have fixed it by changing it to (not A) and (not B) as per De Morgan's laws.

  • Related