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

Models in ASP.NET MVC

Models in ASP.NET MVC Explained A model is a class that contains the business logic of your application. It also used for accessing data from the database. The model class does not handle directly input from the browser. In MVC, it is the Controller that handle input from the browser directly and process the request by receiving data from the model and pass it back to view as response. It does not contain any HTML code either. It is a best practice but not mandatory for developers to not have any communications with the view directly, models should only contain a POCO ( Plain Old CLR Objects ) classes. All processing logic and communication with the view should be handled by another layer called Viewmodels. Models are also refers as objects that are used to implement conceptual logic for the application. A controller interacts with the model, access the data, perform the logic and pass that data to the view. Note that it is not mandatory, but it is a good programming...

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...