c# get inherited class code example
Example 1: c# get all inherited classes of a class
using System.Reflection;
Type[] GetInheritedClasses(Type MyType)
{
return Assembly.GetAssembly(MyType).GetTypes().Where(TheType => TheType.IsClass && !TheType.IsAbstract && TheType.IsSubclassOf(MyType));
}
Type[] ChildClasses Assembly.GetAssembly(typeof(YourType)).GetTypes().Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(YourType))));
foreach (Type Type in
Assembly.GetAssembly(typeof(BaseView)).GetTypes()
.Where(TheType => TheType.IsClass && !TheType.IsAbstract && TheType.IsSubclassOf(typeof(BaseView))))
{
AddView(Type.Name.Replace("View", ""), (BaseView)Activator.CreateInstance(Type));
}
Example 2: 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);
}