derived class c# code example
Example 1: list of 2 different inherent classes c#
public interface IPrinter
{
void Send();
string Name { get; }
}
public class PrinterType1 : IPrinter
{
public void Send() { }
public string Name { get { return "PrinterType1"; } }
}
public class PrinterType2 : IPrinter
{
public void Send() { }
public string Name { get { return "Printertype2"; } }
public string IP { get { return "10.1.1.1"; } }
}
var printers = new List<IPrinter>();
printers.Add(new PrinterType1());
printers.Add(new PrinterType2());
foreach(var p in printers)
{
p.Send();
var p2 = p as PrinterType2;
if(p2 != null)
Console.WriteLine(p2.IP);
}
Example 2: inheritance in c#
public class A
{
public void Method1()
{
}
}
public class B : A
{ }
public class Example
{
public static void Main()
{
B b = new B();
b.Method1();
}
}
Example 3: how to get derived class from base class C#
class Base {
[...]
}
class Derived : Base {
[...]
}
Base baseInstance = new Derived();
Derived derivedFromInstance = (Derived)baseInstance;