inherit class include another c# code example
Example 1: list of 2 different inherent classes c#
// a Pseudo-example using interfaces. <--- Worked great for me!
public interface IPrinter
{
void Send();
string Name { get; }
}
public class PrinterType1 : IPrinter
{
public void Send() { /* send logic here */ }
public string Name { get { return "PrinterType1"; } }
}
public class PrinterType2 : IPrinter
{
public void Send() { /* send logic here */ }
public string Name { get { return "Printertype2"; } }
public string IP { get { return "10.1.1.1"; } }
}
// ...
// then to use it
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) // it's a PrinterType2... cast succeeded
Console.WriteLine(p2.IP);
}
Example 2: c# inheritance
// ----------------- INHERITANCE and POLYMORPHISM ------------------ //
// ----- TOP CLASS ----- //
class Parent
{
protected int ID; // This will be inherited by the child class
public Parent() // This constructor will automatically be called when we create a child object
{
ID = 0;
}
public Parent(int Id) // This constructor will automatically be called when we create a child object
{
ID = Id;
}
public virtual void Method1 (string someInput) // The "virtual" keyword allows you to override this method
{
Console.WriteLine("Hi there, this method will be inherited");
Console.WriteLine(someInput);
}
protected void Method2 ()
{
Console.WriteLine("Hi there, this method will also be inherited");
}
protected void Method3 ()
{
Console.WriteLine("Hi there, this method will also be inherited");
}
}
// ----- LOWER CLASS ----- //
class Child : Parent
{
pritave int count; // This class has both the "count" and "ID" properties, since the "ID" was inherited
public Parent() // Both the parent and child base constructors are called
{
count = 0;
}
public Parent(int Id) : base (Id) // Both the parent and child second constructors are called
{
count = 0;
}
public override void Method1 (string someInput) // This will override the original Method1 funtion
{
base.Method1 (someInput); // This will call the original method from the parent that now, also belongs to the child
// ... some code ...
}
protected new void Method2 () // This will not override but will instead make it a priority over the other Method2()
{ // This is only used if you create an object like: Parent obj = new Child() and not if you create: Child obj = new Child()
Console.WriteLine("Make it do something different");
}
public sealed override void Method3 () // This "sealed" keyword will stop other subclasses that derive from the child, from overriding this method again
{
Console.WriteLine("Make it do something different");
}
public void Method4 (string someInput, int count)
{
base.Method1 (someInput); //Or just: Method1 (someInput) since, in this case, the methods are different
this.count = count;
}
}