C# class can not disguise to be another class because GetType method cannot be override

Posted by zinking on Stack Overflow See other posts from Stack Overflow or by zinking
Published on 2013-06-26T03:27:16Z Indexed on 2013/06/26 4:21 UTC
Read the original article Hit count: 250

Filed under:

there is a statement in the CLR via C# saying in C#, one class cannot disguise to be another, because GetType is virutal and thus it cannot be override

but I think in C# we can still hide the parent implementation of GetType.

I must missed something

if I hide the base GetType implementation then I can disguise my class to be another class, is that correct?

The key here is not whether GetType is virutal or not, the question is can we disguise one class to be another in C#

Following is the NO.4 answer from the possible duplicate, so My question is more on this. is this kind of disguise possible, if so, how can we say that we can prevent class type disguise in C# ? regardless of the GetType is virtual or not

While its true that you cannot override the object.GetType() method, you can use "new" to overload it completely, thereby spoofing another known type. This is interesting, however, I haven't figured out how to create an instance of the "Type" object from scratch, so the example below pretends to be another type.

public class NotAString {
    private string m_RealString = string.Empty;
    public new Type GetType()
    {
        return m_RealString.GetType();
    } } 

After creating an instance of this, (new NotAString()).GetType(), will indeed return the type for a string.

share|edit|flag answered Mar 15 at 18:39

Dr Snooze 213 By almost anything that looks at GetType has an instance of object, or at the very least some base type that they control or can reason about. If you already have an instance of the most derived type then there is no need to call GetType on it. The point is as long as someone uses GetType on an object they can be sure it's the system's implementation, not any other custom definition. – Servy Mar 15 at 18:54 add comment

© Stack Overflow or respective owner

Related posts about c#