Skip to main content

C# Inheritance Explained

C# Inheritance Explained With Example

In c#, Inheritance is one of the primary concept of object-orientedprogramming (OOP) and it is used to inherit the behaviors and properties from one class (base) to another (child) class.

 

The inheritance will enable us to create a new class by inheriting the properties and methods from other classes to reuse, extend and modify the behavior of other class members based on our requirements.

 

In c# inheritance, the class whose members are inherited is called a base (parentclass and the class that inherits the members of base (parent) class is called a derived (child) class.class.

 

C# Inheritance Syntax

The syntax below shows how to implement an inheritance to define a derived class that inherits the properties of base class in c# programming language.

 

<access_modifier> class <base_class_name>

{

    // Base class Implementation

}

  <access_modifier> class <derived_class_name> : <base_class_name>

{

    // Derived class implementation

}

 

The above syntax, we are inheriting the properties and methods of base class into child class to improve code reusability.

 

The below code sample is a simple example of implementing inheritance in c# programming language.

 

    public class CSharp

    {

        public void GetCsharpDetails()

        {

            // Method implementation

        }

    }

 

    public class Csharpnaija : CSharp

    {

        // Derived class implementation

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Csharpnaija csharp = new Csharpnaija();

             csharp.GetCsharpDetails();

        }

     }

 

From the code sample above, we can observe that, we defined a class “CSharp” with the method called “GetCsharpDetails” and the class “Csharpnaija” is inheriting from class “CSharp”. After that, we are calling a “GetDetails” method by using an instance of derived class “Csharpnaija”.

 

In c#, it’s not possible to inherit the base class constructors in the derived class and the accessibility of other members of a base class also depends on the access modifiers which we used to define those members in a base class.

 

C# Practical Example of Inheritance


Following is practical example of implementing an inheritance by defining two classes.

 

namespace CsharpnaijaTutorial

{

 

    public class User

    {

 

        public string Name;

 

        private string Location;

 

        public User()

        {

             Console.WriteLine("Base Class Constructor (User)");

         }

         public void GetUserInfo(string location)

        {

             Location = location;

             Console.WriteLine("Name: {0}", Name);

             Console.WriteLine("Location: {0}", Location);

         }

     }

 

    public class Details : User

    {

        public int Age;

        public Details()

        {

            Console.WriteLine("Child Class Constructor");

        }

         public void GetAge()

         {

            Console.WriteLine("Age: {0}", Age);

        }

     }

 

    class Program

    {

        static void Main(string[] args)

        {

             Details d = new Details();

             d.Name = "Musa Gadabs";

             // Compile Time Error

             //d.Location = "Abuja";

             d.Age = 32;

             d.GetUserInfo("Abuja");

             d.GetAge();

             Console.WriteLine("\nPress Any Key to Exit..");

             Console.ReadLine();

         }

     }

 }

 

If you observe the above example, we defined a base class called “User” and inheriting all the properties of User class into a derived class called “Details” and we are accessing all the members of User class with an instance of Details class.

 

If we uncomment the commented code, we will get a compile-time error because the Location property in User class is defined with a private access modifier and the private members can be accessed only within the class.

 

Multi-Level Inheritance


Generally, C# supports only single inheritance that means a class can only inherit from one base class. However, in C#, the inheritance is transitive and it allows you to define a hierarchical inheritance for a set of types and it is called a multi-level inheritance.

 

For example, suppose if class C is derived from class B, and class B is derived from class A, then class C inherits the members declared in both class B and class A.

 

Example

namespace CsharpnaijaTutorial

{

    public class ClassA

    {

        public string Name;

        public void GetName()

        {

            Console.WriteLine("Name: {0}", Name);

        }

    }

 

    public class ClassB : ClassA

    {

        public string Location;

        public void GetLocation()

        {

            Console.WriteLine("Location: {0}", Location);

        }

    }

 

    public class ClassC : ClassB

    {

        public int Age;

        public void GetAge()

        {

            Console.WriteLine("Age: {0}", Age);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            ClassC c = new ClassC();

 

            c.Name = "Musa Gadabs";

 

            c.Location = "Abuja";

 

            c.Age = 32;

 

            c.GetName();

 

            c.GetLocation();

 

            c.GetAge();

 

            Console.WriteLine("\nPress Any Key to Exit..");

 

            Console.ReadLine();

        }

    }

}

C# Multiple Inheritance

As discussed in Multi-Level Inheritance, C# supports only single inheritance that means a class can only inherit from one base class. In case, if we try to inherit a class from multiple base classes, then we will get compile-time errors.

 

For example, if class C is trying to inherit from Class A and B at the same time, then we will get a compile-time error because multiple inheritance is not allowed in c#.

 

As discussed earlier, multi-level inheritance is supported in C# but multiple inheritance is not supported. In case, if you want to implement multiple inheritance in C#, we can achieve that by using interfaces.

 

References

1.     Tutlane

2.     Guru99


Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...