Abstract Class in C# with Example

Abstract Class in C# with Example
Rating: 5 - 1 Votes

Abstract Class in C# with Example

Abstract Class in C# with Example

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.

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.

Output:

Print Method A
Print Method B
Press any key to continue . . .