Why does testB in this example not give a "warning CS0184: The given expression is never of the provided ('MyClass2') type" the same way that testA does?
class Program
{
void Main()
{
var a = new MyClass1();
var b = (IMyInterface)new MyClass1();
//Get a CS0184 Warning on this line
var testA = a is MyClass2;
//No warning on this line
var testB = b is MyClass2;
}
}
interface IMyInterface
{
}
class MyClass1 : IMyInterface
{
}
class MyClass2
{
}
Because the type of
bisIMyInterface. The compiler does not analyse the code to find the actual runtime type of the object you assigned tob.It is possible for a variable of type
IMyInterfaceto beis MyClass2. For example, ifbrefers to an instance ofMyClass3:Of course, if
MyClass2issealed,MyClass3cannot exist, sobcan never beis MyClass2in that case, and you get the warning as expected.This is also why it is possible to cast an expression of a non-sealed class type to any interface type, e.g.
Even if
MyClass2doesn't implementIMyInterface, at runtime it may be referring to some subclass that does implementIMyInterface.