In C#, like many object-oriented programming languages, abstraction is a foundational principle. The abstract keyword is one of the ways C# implements this principle.

What is ‘abstract’?

In C#, the abstract keyword can be used with classes and class members (methods, properties, indexers, and events). An abstract class cannot be instantiated directly. Instead, it serves as a base class from which other classes can be derived.

Why Use ‘abstract’?

  • Forced Implementation: By declaring a method as abstract, you ensure that any derived non-abstract class will implement that method. This is particularly useful when you have a general idea for a method, but its exact implementation depends on the specific derived class.
  • Control: Abstract classes allow you to dictate certain aspects of a class’s design while leaving other details to the specific derived classes.

How to Declare an Abstract Class or Member

Class: To declare a class as abstract, you simply prefix the class declaration with the abstract keyword.

abstract class Shape
{
    // class body
}

Member: Similarly, to declare a member as abstract, you prefix the member’s declaration with the abstract keyword. Remember, abstract members cannot have any body.

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

Important Points to Remember

  • Abstract classes cannot be instantiated.
  • Derived classes from an abstract class must implement all of its abstract members unless the derived class is also abstract.
  • Abstract members cannot be private, because they are meant to be overridden in derived classes.
  • An abstract class can have regular methods with implementations, not just abstract methods.

Practical Example

Imagine a scenario where you’re building a graphics application, and you have various shapes to draw:

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

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

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

In the above example, we have an abstract Shape class with an abstract Draw method. The derived classes, Circle and Square, provide concrete implementations of the Draw method.

Conclusion

The abstract keyword in C# provides a powerful way to ensure a level of consistency and structure in your object-oriented designs. While it comes with certain constraints, the benefits of clear contracts and forced implementations can lead to cleaner, more organized, and more predictable code. Personally, I prefer composition over inheritance but that will be talked about in another blog post.

Leave a comment

Trending