c-sharp
  1. c-sharp-abstract-class

C# Abstract Class

In C#, an abstract class is a class that cannot be instantiated and serves as a base for other classes. An abstract class can define abstract and non-abstract methods, as well as variables, properties, and events. In this tutorial, we'll discuss how to define and use abstract classes in C#.

Syntax

The syntax for defining an abstract class in C# is as follows:

public abstract class MyBaseClass {
   // code
}

The abstract keyword is used to indicate that the class is abstract.

Example

Let's say we want to create an abstract class called "Shape" that defines an abstract method named "Draw". Here's how we can implement it:

public abstract class Shape {
   public abstract void Draw();
}

Now, we can define a concrete class that inherits from the Shape class:

public class Circle : Shape {
   public override void Draw() {
      Console.WriteLine("Drawing a circle");
   }
}

Now, we can create an instance of the Circle class and call the Draw method:

Circle c = new Circle();
c.Draw(); // Output: Drawing a circle

Output

When we run the example code above, the output will be:

Drawing a circle

This is because we created an instance of the Circle class, which inherits from the Shape class, and called the Draw method.

Explanation

In the example above, we created an abstract class called "Shape" that defines an abstract method named "Draw". We then defined a concrete class called "Circle" that inherits from the Shape class and implements the Draw method.

We created an instance of the Circle class and called the Draw method, which printed "Drawing a circle" to the console.

Use

Abstract classes are useful for creating a base class that defines the structure and behavior of other classes. By defining abstract methods in an abstract class, you can ensure that the classes that inherit from it implement those methods.

Important Points

  • An abstract class cannot be instantiated directly. It can only be used as a base class for other classes.
  • Abstract methods are declared without an implementation and must be implemented by the non-abstract classes that inherit from the abstract class.
  • Abstract properties and events can also be defined in an abstract class.
  • An abstract class can contain non-abstract members and a constructor.

Summary

In this tutorial, we discussed how to define and use abstract classes in C#. We covered the syntax, example, output, explanation, use, and important points of abstract classes in C#. With this knowledge, you can now use abstract classes in your C# code to define a base class that provides structure and behavior for other classes.

Published on: