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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...