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?
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:
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
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With