Sep 26, 2008

Method Hiding... Polymorphism in C#

In the following code:

interface IBand
{
int ID {get;set;}
string Name {get;set;}
void GetStatus();
}
public class Band : IBand
{
public int ID { get; set; }
public string Name { get; set; }

public Band()
{
GetStatus();
}
public void GetStatus()
{
ID = 555;
Name = "Ring";
Console.WriteLine("Base Class Called");
}
}

public class ABand : Band, IBand
{
public string Update { get; set; }

public ABand() : base() {}

public new void GetStatus()
{
ID = 655;
Name = "TEsst";
Update = "ddd";
Console.WriteLine("Derived class Called");
}
}
class Program
{
static void Main(string[] args)
{
IBand band = new ABand();
band.GetStatus();
}

}

We have 2 classes, Band and ABand which implement the IBand interface explicitly.

Now the call to band.GetStatus in Main will display "Derived class called". This will only happen if the Derived class (ABand) also implements the interface IBand explicitly (not in the literal sense in that it does not implement the methods using the IBand.GetStatus syntax)

If the ABand class does not implement the IBand interface explicitly (but implicitly since it inherits from Band which implements IBand) then the above code will output "Base class called"

However note one thing, that when the CTor for ABand is invoked it will invoke the ctor Band class and which will call GetStatus() method from within Band class hence this will output "Base class called" even though the ABand class has implemented the IBand interface explicilty.

kick it on DotNetKicks.com

No comments: