Search

Inheritance in C#

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon


using System;


namespace Tutorial
{
public class Parent
{
string parentString;
public Parent() // Constructor
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString) // Constructor takes "myString" as parameter.
{
parentString = myString; // Assigns parameter to parentString
Console.WriteLine(parentString);
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent // Inheritance
{
public Child()
: base("From Derived") //Inherits and calls the base class constructor.
{
Console.WriteLine("Child Constructor.");
}
public void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
public static void Main() //Static main method, init of application
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
}

The new class—the derived class—then gains all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself. The new class then has two effective types: the type of the new class and the type of the class it inherits.