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 call MyTesting.A (), is it dynamic polymorphism? I did not include a keyword Virtualor any Overridehere?

Your inputs

+3
source share
3 answers

No, there is no polymorphism. You have a non-virtual non-virtual method call. Unlike some other languages, methods and properties in C # are not virtual by default.

To demonstrate truly valid polymorphism, you need to:

  • Declare a virtual method in a base class
  • Use override modifier in derived class
  • Use a variable with the compilation time type of the base class to call, but initializing it with an object of a derived type.

, , :

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
    }
}
+5

, . , . , , . :

        Testing_Class MyTesting = new Testing();
        MyTesting.A();
+3

You do not redefine, but hide. Since you did not mark this method.

That is, you can hide virtual methods, but you cannot override usually derived methods.

        class TestBase
        {
            public void GoForIt() {}
        }

        class Test : TestBase
        {
            public virtual new void GoForIt() {}
        }


        class Other : Test
        {
            public override void GoForIt() {}
            public new void GoForIt() {}
        }

if you forget the keyword new, the compiler will warn you:

The new keyword is required on "Other.GoForIt ()" because it hides the inherited member

+2
source

Source: https://habr.com/ru/post/1788259/


All Articles