Abstraction is an important concept in object-oriented programming (OOP) and is one of the key principles of OOP. In C#, abstraction is achieved through abstract classes and interfaces. This tutorial will guide you through the basics of abstraction in C#.
Abstraction in C#
1. Abstract Classes:
An abstract class is a class that cannot be instantiated and is typically used as a base class for other classes. It may contain abstract and non-abstract (concrete) methods. Abstract methods have no implementation in the abstract class and must be implemented by derived classes.
// Example of an abstract classabstract class Shape{public abstract void Draw(); // Abstract method with no implementationpublic void Display(){Console.WriteLine("Displaying shape");}}// Derived class implementing the abstract methodclass Circle : Shape{public override void Draw(){Console.WriteLine("Drawing a circle");}}
2. Interfaces:
An interface is a contract that defines a set of methods and properties that a class must implement. Unlike abstract classes, interfaces can be implemented by multiple classes, providing a way to achieve multiple inheritances in C#.
// Example of an interfaceinterface IDrawable{void Draw();}// Class implementing the interfaceclass Square : IDrawable{public void Draw(){Console.WriteLine("Drawing a square");}}
3. Using Abstraction in Code:
Now, let's use the abstract class and interface in a program:
class Program{static void Main(){// Using abstract classShape circle = new Circle();circle.Draw(); // Calls the overridden method in Circlecircle.Display(); // Calls the method in the abstract class// Using interfaceIDrawable square = new Square();square.Draw(); // Calls the method in Square}}
Summary:
- Abstraction helps in hiding the complex implementation details and exposing only the necessary functionalities.
- Abstract classes and interfaces provide a way to achieve abstraction in C#.
- Abstract classes can have a mix of abstract and concrete methods, while interfaces only contain method and property declarations.
- Abstract classes are used for common functionality among derived classes, and interfaces define a contract that multiple classes can implement.