GetType() returns the runtime type of the object instance.  In the case of a
derived class it will be the Type for the subclass, not the superclass.
Take this example:

public class Animal {
        public virtual void WriteType() {
                Console.WriteLine(this.GetType());
        }
}

public class Human : Animal {
}

public class App {
        public static void Main() {
                Animal a = new Animal();
                a.WriteType();
                Human h = new Human();
                h.WriteType();
                Animal ha = (Animal) h;
                ha.WriteType();
        }
}

It prints:

Animal
Human
Human

even though Human's WriteType method is inherited from Animal the call to
GetType returns the Type of the object instance, not the Type of the super
that contains the implemenation.

HTH,

Seang

-----Original Message-----
From: Yong Xu [mailto:[EMAIL PROTECTED]]
Sent: Friday, May 17, 2002 10:22 AM
To: [EMAIL PROTECTED]
Subject: [DOTNET] Implementing Equals


Hi there,
In Jeffrey Richter's recent book, Applied .NET Framework programming, Page
156, he demonstrated how to implement Equals for a reference type whose base
class overrides Object's Equals. He wrote this,
// let the base type compare its fields
if (!base.Equals(obj)) return false;
...
// If the objects are of different types, they can't be equal
if (this.GetType() != obj.GetType()) return false;
...
However, if the base class implements its Equals in the similar way, since
GetType is not virtual, then either base's (this.GetType() != obj.GetType())
or the derived class's one must evaluate to false. Hence the derived class's
Equals will always return false.
Do I miss anything?
TIA,
Yong

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to