Abstraction in C# is the concept of hiding complex implementation details and showing only the essential features of an object. It helps reduce programming complexity and effort.
An abstract class
cannot be instantiated. It can contain abstract methods (no body) and non-abstract methods (with body).
abstract class Animal
{
public abstract void MakeSound(); // Abstract method
public void Sleep() // Regular method
{
Console.WriteLine("Sleeping...");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark!");
}
}
class Program
{
static void Main()
{
Dog d = new Dog();
d.MakeSound(); // Output: Bark!
d.Sleep(); // Output: Sleeping...
}
}
An interface
is like a contract. It defines methods without implementing them. A class that implements the interface must define all its members.
interface IShape
{
void Draw();
}
class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
class Program
{
static void Main()
{
IShape shape = new Circle();
shape.Draw(); // Output: Drawing Circle
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!