Today we will take a look at inheritance, one of the four major principles of object oriented programming. Inheritance is used to crate new class based on existing one, which means reuse of properties and method from parent class. It’s important to mention that C# does not support multiple inheritance of classes, but it does support inheritance of multiple interfaces. In c# you can crate chains of connections by inheriting from parent class that inherits from another parent class, this way you can keep properties from multiple classes.

Inheritance is marked by colon( ” : ” ) in the new class declaration, between the name of child class and name of the parent class

class <child_class> : <parent_class>
  //class body


Lets take a look at example of simple implementation

using System;
namespace InheritanceApplication

 //Parent Class
 class Shape
 //Values of parent class should be protected 
 //so it can not be overriten in child class
 protected int side;
 public void setBase(int a)
 side = a;

 // Child class
 class Square : Shape
 public int getArea()
 return (side * side);

 class MainClass
 static void Main(string[] args)
 Square Box = new Square();
 //Method from parent class
 //Method from child class

 // Print the area of the square.
 Console.WriteLine("Total area: " + Box.getArea());

We can see that we can use methods from both classes. We used the protected keyword because the accessibility of a member in the child class depends upon its declared accessibility in the parent class.

Creating child class is useful when we want to extend functionality of existing class without changing it(part of SOLID design). Child class can overwrite the methods from parent class, by rewriting the method declaration. But this is part of another key principle of oop called Polymorphism. We will take a look on this in next post. Stay Awesome!






Author: indiedevart

Indie Games Developer

2 thoughts on “Inheritance”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s