Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Polymorphism : Doubt

I have this code:

namespace ClassLibrary1
{
    public class Testing_Class
    {
        public string A()
        {
            int i = 3;
            Console.Write("Value if i" + i);
            string a = "John";
            return a;
        }


    }

    public class Testing : Testing_Class
    {
        public string A()
        {
            string a = "John";
            Console.Write(a);
            return a;
        }

    }



    public class Test
    {
        public void foo()
        {
            Testing MyTesting = new Testing();
            MyTesting.A(); //Dynamic Polymorphism ??

        }
    }

    }

When I am calling MyTesting.A() is this a Dynamic Polymorphism? I have not included any Virtual Keyword or any Override here?

Your inputs?

like image 724
RG-3 Avatar asked Sep 20 '26 12:09

RG-3


2 Answers

Nope, there's no polymorphism going on here. You've got a non-virtual call to a non-virtual method. Unlike some other languages, methods and properties in C# are non-virtual by default.

In order to demonstrate polymorphism really working, you'd want to:

  • Declare the method virtual in the base class
  • Use the override modifier in the derived class
  • Use a variable with a compile-time type of the base class for the invocation, but having initialized it with an object of the derived type.

Here's a short but complete program demonstrating all that:

using System;

class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Base.Foo");
    }
}

class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine("Derived.Foo");
    }
}

class Test
{
    static void Main()
    {
        Base x = new Derived();
        x.Foo(); // Prints Derived.Foo
    }
}
like image 114
Jon Skeet Avatar answered Sep 23 '26 02:09

Jon Skeet


No, this is not polymorphism. You're creating a new member with the same name on the subclass, not overriding the parent class' member. If you were to refer to your instance as an instance of the parent class, it would actually call the parent class' member, not the child class. Try it out:

        Testing_Class MyTesting = new Testing();
        MyTesting.A();
like image 34
Adam Robinson Avatar answered Sep 23 '26 00:09

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!