Thursday, 10 October 2013

Inheritance in c#

Inheritance makes programs less complicated and quicker. With inheritance, we tend to build many varieties upon a typical abstraction. Then we tend to later bear upon all those varieties through the abstraction. we tend to examine inheritance and polymorphism within the C# language.

Base class:
The category another class inherits from. within the C# language, the final word base category is that the object category.

Derived class:
The category with a base class.
A derived category might have multiple levels of base categories.

When you specify that derives from another class, you produce acquires all the options of the bottom class. If the derived category contains a few additional options however is otherwise an equivalent because the base category, this can be a decent approach.


Example:
using System;
using System.Collections.Generic;

class Net
{
    public virtual void Act()
    {
    }
}

class Perl : Net
{
    public override void Act()
    {
 Console.WriteLine("Perl.Act");
    }
}

class Python : Net
{
    public override void Act()
    {
 Console.WriteLine("Python.Act");
    }
}

class Program
{
    static void Main()
    {
 // Use base class and derived types in a List.
 List<Net> nets = new List<Net>();
 nets.Add(new Perl());
 nets.Add(new Python());

 // Call virtual method on each instance.
 foreach (Net net in nets)
 {
     net.Act();
 }
    }
}

What will this program show? It uses a straightforward object model that options 2 derived categories from one base category. we tend to produce an inventory of the bottom category sort, so add derived categories to that.

When we finally decision the Act technique through the bottom category references within the List, we tend to invoke the overridden performs through the virtual base function. so the derived varieties retain all their options however share a kind.

It is doable to use forged operators to check or convert a base sort to a additional derived sort. However, in several cases, if your program uses a base category however should forged to additional derived varieties, it's going to have a style flaw.

Multiple base categories:
You cannot specify multiple base categories on a kind declaration. This restriction was obligatory on the C# language to cut back the complexness of inheritance and eliminate some issues. You can, however, implement multiple interfaces.

Inheritance allows you to form complicated models which will scale back your program size and improve its modularity and performance. it's vital, though, to not overuse or abuse inheritance.

0 comments:

Post a Comment