top of page

C# Tutorial For Beginners: Inheritance (Derived and Base Class)

Updated: Aug 22, 2021

As an object-oriented language, we can define a Top-level class (AKA: Base Class) and additional classes (AKA: Derived Class) that will inherit its methods and fields. To inherit from a base class, we will need to use the ‘:’ symbol.


Note: if you want to block inheritance from one class to another, use the ‘sealed’ keyword (sealed <class> <class name>)


Code Example:


public class Animal //Base Class

{

//Class Properties

public string AnimalName { get; set; }

public int AnimalAge { get; set; }


//Class Ctor's


public Animal()

{


}

public Animal(string animalname , int animalage)

{

AnimalName = animalname;

AnimalAge = animalage;

}


//Class Methods

public void printAnimalName()

{

Console.WriteLine("Test");

}

}


class Dog:Animal //Derived Class

{

public string DogColor { get; set; }

}

class Program

{

static void Main(string[] args)

{

//create a new dog object

Dog dog_1 = new Dog();

dog_1.AnimalAge = 10;//Animal Class

dog_1.AnimalName = "Bentz";//Animal Class

dog_1.DogColor = "Brown"; //Dog Class

dog_1.printAnimalName();//Animal Class

}

}



6 views0 comments