[Mono-list] Please help me with polimorfism, etc. (possible bug in the compiler?)

Jonathan Pryor jonpryor@vt.edu
Thu, 23 Sep 2004 06:24:51 -0400


On Thu, 2004-09-23 at 01:27, Roberto Jimeno wrote:
> Now I think I'm simply being confused about inheritance, 

A particular way of implementing the substitutability principle.  There
are other techniques used by other languages, but inheritance is
currently the "most popular".

> polimorfism, 

That's polymorphism.  It means that when an action is performed on a
pointer/reference to a base-class object, the *actual* action performed
is the one provided by the derived class.

This is why calling .ToString() on an object invokes the derived-class
implementation, not the System.Object implementation (unless the derived
class didn't override Object.ToString()).

As it happens, polymorphism isn't actually used in your example: you are
using/overriding no virtual functions.

> substitutability principle and such. 

Means that a derived class instance can be used anywhere a base class
instance could be used.  This is commonly referred to as IS_A.

> Please compile and execute the small example (attached file). You will
> see the string:
> 
> "Types of self and argument are derivedClass and derivedClass
> respectively."
> 
> , while I was expecting to see
> 
> "Types of self and argument are derivedClass and baseClass
> respectively."
> 
> Can you tell me which changes (a suggestions is commented out in the
> code) should I apply to my code in order to obtain the "baseClass"
> expected result?

The problem here is you have a misconception of what Object.GetType()
returns.  It's not polymorphic, nor can it be (it's not virtual).  It
returns the System.Type object for the *run-time* type of the object. 
This is *always* true:

	new derivedClass().GetType().Equals (typeof(derivedClass));

What your code *wants* to happen is for this to be true, which is false:

	new derivedClass().GetType().Equals (typeof(baseClass));

A derivedClass can be *substituted* for a baseClass (because of the
substitutability principle, IS_A), but a derivedClass IS NOT EXACTLY a
baseClass; it's a derivedClass which can be used like a baseClass.

Consequently, to get the message you want to get, you'd have to do this:

	public static void Main ()
	{
		baseClass d = new derivedClass ();
		baseClass b = new baseClass ();
		d.show (b);
	}

This way, the runtime type of `this' is derivedClass, and the runtime
type of the argument is `baseClass'.

 - Jon