Abstraction in C# is a concept that allows you to define a blueprint for a class with some methods and properties without implementing the details of those methods. It focuses on what an object does rather than how it does it. Abstraction hides the complexity of the implementation and only shows the essential features of an object.
Here's a simple explanation with an example:
Suppose we want to create a basic shape interface called IShape
with a method Draw()
that every shape must implement. The actual implementation of the Draw()
method will vary depending on the specific shape.
Example
using System;
// Interface defining the blueprint for shapes
interface IShape
{
void Draw(); // Method to draw the shape
}
// Concrete class implementing the IShape interface
class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
// Concrete class implementing the IShape interface
class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
class Program
{
static void Main(string[] args)
{
IShape shape1 = new Circle(); // Creating a circle
IShape shape2 = new Rectangle(); // Creating a rectangle
shape1.Draw(); // Calls the Draw() method of Circle class
shape2.Draw(); // Calls the Draw() method of Rectangle class
}
}
In this example:
IShape
with a method Draw()
. The interface serves as a blueprint for shapes, defining what behavior they must have without specifying how that behavior is implemented.Circle
and Rectangle
, both of which implement the IShape
interface. Each class provides its own implementation of the Draw()
method suitable for its specific shape.Main
method, we create instances of Circle
and Rectangle
using the interface type IShape
. This allows us to treat different shapes uniformly, without concerning ourselves with their specific implementations.Draw()
method on each shape, the appropriate implementation for that shape is invoked, demonstrating abstraction. We don't need to know the details of how each shape is drawn; we only care that they can be drawn.Abstraction helps in managing complexity by focusing on essential features and hiding unnecessary details. It also promotes code reusability and modularity.