C# abstract keyword

C# abstract keyword

In this tutorial, we would learn about abstract keyword in c# programming language.

abstract: This modifier indicates that thing being modified has a missing or incomplete implementation.

This modifier in C# language applies to the following :

  1. Class

  2. Method

  3. Properties

  4. Indexers

  5. Events

Abstract class

A class declared with abstract modifier is an abstract class.

  • abstract classes are intended to be a base class of other classes - the developer can not create an Object of an abstract class.

  • an abstract class can have both abstract methods ( methods with definition) and non-abstract methods (methods without definition).

  • As an object can not be created for an abstract class, a derived class must be created for an abstract class.

    public abstract class Asset {
        public abstract decimal BuyPrice { get; }
        public abstract decimal SellPrice { get; }
        public abstract decimal CalculateProfit();
    }
    public class Stock : Asset {
        public override decimal BuyPrice => 100;
        public override decimal SellPrice => 150;
        public override decimal CalculateProfit() {
            return (SellPrice - BuyPrice);
        }
    }
  • An abstract class must provide implementation for all interface members

  • An abstract class that implements an interface might map the interface methods onto abstract methods.

      interface I {
          void M();
      }
      abstract class C : I {
          public abstract void M();
      }
    

Abstract methods / Properties

  • abstract method declaration doesn't provide any implementation.

      public abstract class Asset {
              public abstract decimal CalculateProfit();
          }
    
  • An abstract method is implicitly a virtual method - base class must provide its implementation.

  • It is an error to use static or virtual modifiers in an abstract method declaration.

  • Abstract method declarations are only permitted in abstract classes.

  • Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax..

That's it for this article. Thanks for reading this, please share your feedback in the comments section below.

Did you find this article valuable?

Support Deepak Kumar Jain by becoming a sponsor. Any amount is appreciated!