We are in the process of moving a number of classes to interfaces. Some of
the old code involves overload functions based on the derived type. Is there
a way to cast an interface to a derived class through knowlegde of the object
itself?
public class MyClass
{
//old code
//private Polymorphic1 polymorphic1 = null;
//private Polymorphic2 polymorphic2 = null;
//new code. Use as an interface
private IPolymorphic polymorphic1 = null;
private IPolymorphic polymorphic2 = null;
public MyClass()
{
this.InstatiateInterfaces();
}
private void InstatiateInterfaces()
{
this.polymorphic1 = new Polymorphic1();
this.polymorphic2 = new Polymorphic2();
}
public void PrintAll()
{
// This code no longer works.
//this.Print(this.polymorphic1);
//this.Print(this.polymorphic2);
//This is now needed
this.Print((Polymorphic1)this.polymorphic1);
this.Print((Polymorphic2)this.polymorphic2);
//is it possible to do something like....
//this.Print((this.polymorphic1.GetType())this.polym orphic1);
//this.Print((this.polymorphic2.GetType())this.polym orphic2);
}
private void Print(Polymorphic1 polyClass)
{
//do stuff...
Console.WriteLine(polyClass.GetValue());
}
private void Print(Polymorphic2 polyClass)
{
//do stuff...
Console.WriteLine(polyClass.GetValue());
}
}
interface IPolymorphic
{
string GetValue();
}
public class Polymorphic1 : IPolymorphic
{
public string GetValue()
{
return "Polymorphic1";
}
//specific class functionalty here....
}
public class Polymorphic2 : IPolymorphic
{
public string GetValue()
{
return "Polymorphic2";
}
//specific class functionalty here....
}