Inheritance in C#

As we know object-oriented programming enables you to declare and use a new class as a descendant of another class. This process is known as Inheritance. Inheritance saves you the trouble of re-writing code and provides the luxury of code re-use.

C# denies support to multiple inheritance. Multiple inheritance causes major confusion when applications get complex and are also considered to be inefficient programming in terms of memory overload. However, multiple interface implementation is possible in C#. Interfaces will be dealt with in a later post. Let us now go ahead and see how we can implement single inheritance in C#.

Example 9:

Implementing OOP Concepts in C# Example 9

The output of Example 9 would be:

This is the Delete Method of the BaseIO class

Notice that in Example 9 we have not declared a Delete method for the class ImageIO, neither the FileName property. We have created Obj as an object of ImageIO and using this Obj object we are able to access the FileName and Delete members. This is because the class ImageIO was inherited from the class BaseIO.

1.   Sealing a Class

Now consider that you do not want any other class to inherit from a particular class. What do you do? You can just “seal” the class. The syntax for sealing a class is given below.

sealed class classOne
 {
 // Class Implementation
 }

Any class can be sealed by specifying the sealed keyword.

You may want to seal a class when the class comprises only of static members. Also sealing a class in certain situations increases the performance of the application.

The concepts of access modifiers and constructors in inheritance are not very different from the general OOP concepts, so we will not discuss them in detail.

Leave a comment