c# base class code example
Example 1: acess base class in c#
using System;
public class A
{
private int value = 10;
public class B : A
{
public int GetValue()
{
return this.value;
}
}
}
public class C : A
{
}
public class Example
{
public static void Main(string[] args)
{
var b = new A.B();
Console.WriteLine(b.GetValue());
}
}
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);
}
Example 3: c# inheritance
class Parent
{
protected int ID;
public Parent()
{
ID = 0;
}
public Parent(int Id)
{
ID = Id;
}
public virtual void Method1 (string someInput)
{
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");
}
}
class Child : Parent
{
pritave int count;
public Parent()
{
count = 0;
}
public Parent(int Id) : base (Id)
{
count = 0;
}
public override void Method1 (string someInput)
{
base.Method1 (someInput);
}
protected new void Method2 ()
{
Console.WriteLine("Make it do something different");
}
public sealed override void Method3 ()
{
Console.WriteLine("Make it do something different");
}
public void Method4 (string someInput, int count)
{
base.Method1 (someInput);
this.count = count;
}
}
Example 4: Base class c#
class Motore:Veicoli
{
public bool Cavalletto { get; set; }
public Motore (String marca, String modello, int cilindrata, bool cavalletto): base (marca,modello,cilindrata)
{
this.Cavalletto = cavalletto;
}
override
public void Accelera(double velocitacorrente )
{
this.VelocitaCorrente += velocitacorrente;
}
}