EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Abstract Class in C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » Abstract Class in C#

Abstract Class in C#

What is Abstract Class in C#?

The word abstract means a thought or an idea that does not have any physical form of its own but acts as a base for other things. The same is the concept behind the abstract class. In this article, we would be discussing Abstract Classes in C#. An abstract class is a special class in C# that cannot be instantiated, i.e. you cannot create objects of an abstract class. The purpose of an abstract class is to provide a skeletal structure for other classes to derive from. Abstract classes have no implementation of their own. They require the developers and programmers to derive from the abstract class and build upon the skeletal structure, i.e. write their implementation. An abstract class can also have abstract method declarations inside. Again, these methods cannot have any definitions.

The syntax of declaring abstract classes and methods involves placing the keyword abstract before the declaration. As simple as that.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

abstract class ClassName
{
public abstract void MethodName();
}

Remember, abstract methods cannot have definitions. Thus, the abstract method declarations end with a semicolon. They can only be declared. The definitions must be provided in derived non-abstract classes.

How does Abstract Class work in C#?

The abstract keyword instructs the compiler that the class is a base class skeletal structure to be implemented in derived classes. If the compiler finds any class deriving the abstract base class, it checks whether all the abstract methods and properties are overridden and implemented in the derived class.

Abstract Class vs Interface

Now, you may be wondering what all this are and what the interface does. So, how is an abstract class different from an interface?

Let us understand this with an example. Let us say we run a publishing company and have hired a few editors to write columns for our magazine. Let us assume they are experts in different genres, write articles to be published on a specific day of the week, and are all hired at the same salary.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Let’s define the abstract Employee class for our editors.

Code:

abstract class EmployeeEditors
{
public abstract void Genre();
public abstract string PublishDay();
public int Payment()
{
Console.Write(“Monthly salary is {0}$.”, 1000);
}
}

We could easily implement the Payment method, knowing that it would be the same for all. The other two methods were declared abstract to be implemented by the derived class. One could declare a normal class for each editor deriving from the abstract class and can then implement the abstract methods to define the genres and days. Now, assume that the salary of each editor is also different. One way to change our code is to declare the Payment method as abstract. The other way would be to declare the whole EmployeeEditor as an interface and give full freedom to inheriting classes.

Public interface EmployeeEditors
{
public abstract void Genre();
public abstract string PublishDay();
public abstract int Payment();
}

Thus, an abstract class is a base class for other classes to build upon. Whereas an interface is a blueprint for other classes to refer to and build from scratch.

Rules of Abstract Class in C#

There are certain rules to follow when working with abstract classes.

  • Since abstract classes have incomplete method definitions, hence they cannot be instantiated. Any attempt to create an object of an abstract class would result in a compile-time error.
  • Abstract methods cannot be defined in abstract classes but only declared. The method body must be defined in derived classes.
  • Derived classes must implement all the abstract methods.
  • Abstract methods cannot be static or virtual.

Example of Abstract Class in C#

Problem Statement: Let us take another real-world example. Assume that you are asked to automate the process of offer letter generation for a certain organization. The current process is completely manual and requires editing existing offer letters, which is prone to error. There are certain things that would be common for all offer letters, such as work location, work timings, company title, company branding, etc. Other things such as employee name, position, salary, joining date, etc., are specific to each offer letter.

Solution: You would design an abstract class for the purpose above. Let us see how.

Code:

ode: using System;
abstract class OfferLetter
{
public abstract string Name(string name);
public abstract string Designation(string designation);
public abstract int Payment(int pay);
public abstract string DOJ(string doj);
public string CompanyName()
{
return "XYZ Corporation Pvt. Ltd.";
}
public string OfficeAddress()
{
return "512, Manhattan, NY";
}
public string CompanyBranding()
{
return this.CompanyName() + " is a privately owned regsitered corporation operating \n under the license provided by the state of New York.";
}
public string Disclaimer()
{
return "This letter and its contents are confidential in nature and are intended only \n for the recipient."+
"\nIf you are not the correct recipient, kindly return it immediately \n to " + this.CompanyName() + " " + this.OfficeAddress() + ".";
}
}
class PrintOfferLetter : OfferLetter
{
public override string Name(string name)
{
return name;
}
public override string Designation(string designation)
{
return designation;
}
public override int Payment(int pay)
{
return pay;
}
public override string DOJ(string doj)
{
return doj;
}
}
public class Program
{
public static void Main()
{
PrintOfferLetter ltr = new PrintOfferLetter();
string empName = "Mr. ABC", designation = "Senior Consultant", doj = "20-02-2020";
int pay = 50000;
Console.WriteLine(ltr.CompanyName() + " is very happy to extend this offer letter to \n" + ltr.Name(empName)
+ " at the designation of " + ltr.Designation(designation) + " with an annual pay of " + ltr.Payment(pay) + "$.");
Console.WriteLine("\nYou are required to report at " + ltr.OfficeAddress() + " from " + ltr.DOJ(doj) + " (dd-mm-yyyy).");
Console.WriteLine("\n\n" + ltr.CompanyBranding());
Console.WriteLine("\n\n" + ltr.Disclaimer());
}
}

Output:

Abstract Class in C#

Conclusion

In a nutshell, an abstract class is simply an incomplete or partially complete class that other classes can derive and build their logic on top of it. In this article, we have seen how an abstract class is declared, and it is working. We saw real-life examples of the usage of abstract classes and how they are different from interfaces. It is recommended to try and use abstract classes as much as possible in your code. This is a crucial practice of good programming.

Recommended Articles

This is a guide to Abstract Class in C#. Here we discuss the Definition and How Abstract Class Works in C# along with Rules and an Example. You can also go through our other related articles to learn more –

  1. Abstract Classes in JavaScript
  2. Abstract Class in C++
  3. Abstract Class in PHP
  4. TextWriter in C#

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More