CTS Can Be Compromised

Take a closer look at this code:
class Program
{
    public static void Main()
    {
        Base b = new Base();
        Derived d = new Derived();

        Console.WriteLine("base's actual type: {0}", b.GetType());
        Console.WriteLine("derived's actual type: {0}", d.GetType());
    }
}

public class Base
{
    public new Type GetType()
    {
        return typeof(string);
    }
}

public class Derived : Base
{
}

and the outcome is:
base's actual type: System.String
derived's actual type: System.String

the new keyword
here is the axis of evil
any comments or ideas

PS: it's no brainer that any sane developer won't hide the GetType method in their source code, but there is still a possibility that the CTS can be compromised

Sheva



Answer this question

CTS Can Be Compromised

  • Andreas6483

    I'm not sure what you mean by CTS being compromised. But if you're afraid of GetType being hidden you can always do ((object)b).GetType() to call Object.GetType() and not any shadwing method in a derived class. Note also that typeof(Base) and typeof(Derived) will give you the correct result, and there's no point in instantiating the types in the code you provide.



  • CTS Can Be Compromised