Abstract Class in C# with Example
If you want to restrict your fellow team members from creating an instance of a class, you can mark that class abstract using abstract keyword. Abstract class can be used only as a base class. An abstract class may or may not have abstract members. Abstract members can only have declaration and you must use abstract keyword in front of them. Any class inheriting from abstract class should provide implementation for all of its abstract members and you must use override keyword in front of them. Abstract members can be methods, properties, indexers, and events. We cannot use private access modifier in front of an abstract class member, it should be public because you cannot override a private class member.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hello { //Abstract class abstract class Detail { public void PrintA() { Console.WriteLine("Print Method A"); } //Abstract method public abstract void PrintB(); } //Inheritance class Employee:Detail { //Abstract method implementation public override void PrintB() { Console.WriteLine("Print Method B"); } } class Program { static void Main(string[] args) { Employee emp = new Employee(); emp.PrintA(); emp.PrintB(); } } }
Output:
Print Method A
Print Method B
Press any key to continue . . .
In case, your class is inheriting from an abstract class and you are not ready to provide implementation for all of its abstract members, you can also mark that class abstract itself. Then, all the abstract class rules will be applicable to that class too. Because an abstract class can contain abstract members, so its not possible to create an instance of it, but because we know from inheritance in C# that a base class reference variable can point to the derived class object, we can create an instance of abstract class using it as a reference variable.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hello { //Abstract class abstract class Detail { public void PrintA() { Console.WriteLine("Print Method A"); } //Abstract method public abstract void PrintB(); } //Inheritance class Employee:Detail { //Abstract method implementation public override void PrintB() { Console.WriteLine("Print Method B"); } } class Program { static void Main(string[] args) { //Abstract class reference variable. Detail emp = new Employee(); emp.PrintA(); emp.PrintB(); } } }
Output:
Print Method A
Print Method B
Press any key to continue . . .