I know that the is
operator in C# is used for type checking and I read on Microsoft Learn that it checks if the types are compatible. What exactly does ‘compatible’ mean here? Does it mean both types are in the same inheritance hierarchy? If so, does it matter if the type written before the is
operator is parent to the one written after it or the opposite? What about interfaces? Does it also matter if the implementing class is written before the is
operator or after it in relevant to the interface name?
Suppose we have two classes A and B, B inherits from A and B also implements IBable
interface:
public class A { }
public class B: A, IBable { }
Which one of those expressions will return true and which one will return false?
public void TestIs ()
{
public A a;
public B b;
Console.WriteLine(a is b);
Console.WriteLine(b is a);
Console.WriteLine(b is typeof(IBable));
Console.WriteLine(typeof(IBable) is b);
}
Note I am still a beginner so my usage of the typeof()
operator here might be incorrect lol
Also, one more question, can the is
operator be used with any object of any class/struct or should one of the operands be of the Type class (returned by the typeof()
operator)?
JPell is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.