[Mono-list] An inheritance dilemma

Abe Gillespie abe.gillespie at gmail.com
Sun Nov 21 13:49:45 EST 2010


Don't call base in SampleMethod -> this skips your override /
virtualization.  SampleMethod should be:

        public override void SampleMethod () {
            SampleMethod();
            Console.WriteLine (this.BuildString());
        }

Note that you can also do:

A a = new B();
a.SampleMethod();

and you'll get B's implementation of SampleMethod.

Good luck.
-Abe

On Sun, Nov 21, 2010 at 1:13 PM, Francisco M. Marzoa <fmmarzoa at gmx.net> wrote:
> Hello,
>
> I'll start by the code, because I think it's the best way of
> illustrating the problem in this case:
>
> using System;
>
> namespace Dummy
> {
>    class MainClass
>    {
>        public static void Main (string[] args)
>        {
>            B b = new B();
>            b.SampleMethod();
>        }
>    }
>
>    public class A {
>        protected virtual string GetClassName() {
>            return "Class A";
>        }
>
>        protected string BuildString () {
>            return this.GetClassName() + " method";
>        }
>
>        public virtual void SampleMethod () {
>            Console.WriteLine (this.BuildString());
>        }
>    }
>
>    public class B : A {
>        protected override string GetClassName() {
>            return "Class B";
>        }
>
>        public override void SampleMethod () {
>            base.SampleMethod();
>            Console.WriteLine (this.BuildString());
>        }
>    }
>
> }
>
>
> The output of this code is:
>
> Class B method
> Class B method
>
> While what I want to get is:
>
> Class A method
> Class B method
>
> I've tried with some minor changes, like removing "virtual" and
> "override" from GetClassName, getting:
>
> Class A method
> Class A method
>
> But I didn't been able to get the output that I want. Perhaps using
> reflection???
>
>
> _______________________________________________
> Mono-list maillist  -  Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
>


More information about the Mono-list mailing list