Cannot explain what is going on the following program. GetType is returning the type I want to return and not the original one. Does that mean we cannot rely on GetType? is operator is right though. Can anybody please explain it in detail?
using System;
namespace ConsoleApplication2
{
public class MyClass
{
public Type GetType()
{
return typeof(Program);
}
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
if (mc.GetType() == typeof(Program))
{
Console.WriteLine("Confused.");
}
if(mc is Program)
{
Console.WriteLine(mc.GetType()); // Don't get inside the if. Why?
}
}
}
}
Update: I am reading the book CLR via C# 3rd edition. In chapter 4 (2nd page) when it explains different methods in System.Object it says
“The GetType method is nonvirtual,
which prevents a class overriding this
method and lying about its type”
While I agree about the first statement, I am lying about MyClass type. ain’t I?
is operator implemented in terms of as operator and finally use isinst IL instruction. And of course this instruction don’t know about your not virtual GetType method that you define in some class in your inheritance hierarchy.
To understand this “confusing” behavior lets “implement” our own version of the “is operator”: