Abstract keyword in C#

Abstract keyword in C#

Hello technology thirsty guys, I was thinking why not I should pick the basics and the main pillar of C #and OOPs , which is C# keywords.  So I would like to first picked Abstract Keyword in C#. Let us look into deeply in Abstract Keyword in C#. You will see all C# keywords in upcoming tutorials.

Brief introduction to Abstract Keyword in c#

Abstract is a modifier which is used to do partial or we can say no implementation. Abstract modifier would be used with class, method, properties, events and indexers. Use of Abstract modifier in a class declaration is intended to base class of other class.

Now we would take examples and try to concept why, where, when and how to use Abstract Keyword in C#:

Example 1: Object Declaration- Abstract Class

We cannot initialize abstract class as traditional class this is the main difference between abstract class and traditional classes.

abstractErrorOnDeclaration

As you can see in image, Visual studio has prompt for the error.

Example 2:

abstract class Test
{
    protected int myVar = 10;

    public abstract int MyProperty
    {
        get;
        set;
    }
    public void B()
    {
        Console.WriteLine("Method B called...");
    }
    public abstract void A(int add);
}
sealed class Example1 : Test
{
    public override int MyProperty
    {
        get { return myVar + 10; }
        set { myVar = value; }
    }

    public override void A(int add)
    {
        Console.WriteLine("Example1");
        Console.WriteLine("myVar:" + (MyProperty + add));
    }
}

class Program
{
    static void Main()
    {
        // Reference Example1 through Test type.
        Example1 objExample1 = new Example1();
        objExample1.A(10);
        Test ObjTest = new Example1();
        ObjTest.A(10);
        ObjTest.B();
        Console.ReadKey();
    }
}

//OUTPUT:
//Example1
//myVar:30
//Example1
//myVar:30
//Method B called...

From the above example we can conclude as below:

Abstract class Features:

  • Abstract class cannot be initiated as shown above but Abstract class can have constructor.
  • Abstract class may have or may not have abstract method or properties.
  • Derived class must have all the method and properties’ implementation of base class with abstract modifier.

Abstract Method Features:

  • An abstract method is implicitly a virtual method.
  • Abstract method only have declaration. As above example:

public abstract void A(int add);

  • Abstract method declarations are only permitted in abstract classes.

Abstract Properties Features:

  • It is an error to use the abstract modifier on a static property.
  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

Please note we can’t make static abstract class or members.

Leave a Reply