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

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

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...