Inheritance in C#

Inheritance allows you to create several classes that are distinct but share a common functionality. Specialized classes, called derived classes, inferit from a common class called the base class. A derived class is also said to extend a base class. The base class encapsulates the common functionality that will be present in each derived class, while the derived classes provide additional functionality specific to each class
  • If you want to declare that a class derives from another class, use the following syntax: 
   class MyDerivedClass : MyBaseClass
   {
     //Function and data members here

   }



Example:

   class MyDerivedClass : MyBaseClass
   {
     //Function and data members here
   }
    public class MyBaseClass
    {
        public void Method()
        {
            Console.WriteLine("Inheritance in C#");
        }
    }

    public class MyDerivedClass : MyBaseClass
    {
        //implementation

    }

  • This syntax is very similar to C++ and Java syntax. However, C++ programmers, who will be used to the concepts of public and private inheritance, should note that C# does not support private inheritance,hence the absence of a public or private qualifier on the base class name. Supporting private inheritance would have complicated the language for very little gain: In practice private inheritance is used extremely rarely in C++ anyway. 


  • If a class  also derives from interfaces, then the list of base class and interfaces is separated by commas:

public class MyDerivedClass : MyBaseClass, Interface
{
  // etc.
}









  • If you do not specify a base class in a class definition, the C# compiler will assume that System.Object  is the base class. Hence the following two pieces of code yield the same result: 

class MyClass : Object // derives from System.Object
{
     // etc.
}

And

class MyClass // derives from System.Object
{
   // etc.


No comments:

Post a Comment