Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading and polymorphism

class Program
    {
        static void Main(string[] args)
        {
            List<A> myList = new List<A> {new A(), new B(), new C()};

            foreach (var a in myList)
            {
                Render(a);
            }

            Console.ReadKey();
        }

        private static void Render(A o)
        {
            Console.Write("A");
        }

        private static void Render(B b)
        {
            Console.Write("B");
        }

        private static void Render(C c)
        {
            Console.Write("C");
        }
    }

    class A
    {

    }

    class B : A
    {

    }

    class C : A
    {

    }

The output is: AAA

Is it possible to somehow use method overloading, so that the output would be: ABC?

like image 338
sventevit Avatar asked Feb 07 '11 13:02

sventevit


2 Answers

The following ought to do the trick, where we control the behaviour when working with a type within that type:

class A
{
    public virtual void Render()
    {
        Console.WriteLine("A");
    }
}

class B : A
{
    public override void Render()
    {
        Console.WriteLine("B");
    }
}

class C : A
{
    public override void Render()
    {
        Console.WriteLine("C");
    }
}

static void Main(string[] args)
{
    var myList = new List<A> { new A(), new B(), new C() };
    foreach (var a in myList)
    {
        a.Render();
    }
    Console.ReadKey();
}

And if you want the defined behaviour of a type to be additive to that of its parent, then call the method implemented in the base after executing your own logic, for example:

class B : A
{
    public override void Render()
    {
        Console.WriteLine("B");
        base.Render();
    }
}
like image 175
Grant Thomas Avatar answered Oct 18 '22 08:10

Grant Thomas


You can use dynamic typing if you're using C# 4:

foreach (dynamic a in myList)
{
    Render(a);
}

Within static typing, overload resolution is performed at compile-time, not at execution time.

For the implementation to be chosen at decision time, you either have to use overriding instead of overloading, or use dynamic typing as above.

like image 32
Jon Skeet Avatar answered Oct 18 '22 09:10

Jon Skeet