Abstract Class in C# with examples

Abstract classes are an important concept that can help you design flexible and maintainable code. In this article, we'll take a deep dive into the Abstract Class C# example.

An abstract class in C# contains at least one abstract method, and thus cannot be instantiated. Instead, it serves as a base or parent class for other classes to derive from. Abstract classes provide a way to enforce a certain structure and functionality on derived classes. It is used to define a behavior that can be inherited by multiple derived classes.

KEY TAKEAWAYS:

  1. Abstract class C# serves as a base or parent class for derived classes, enforcing structure and functionality.
  2. Abstract classes in C# contain at least one abstract method, cannot be instantiated, and require implementation in derived classes.
  3. The advantages of abstract classes in C# include defining a common interface, enabling polymorphism, and facilitating flexible code.
  4. We have code Examples that demonstrate abstract class usage in inheritance, interfaces, properties, constructors, static methods, generics, delegates, lambda expressions, and LINQ.
  5. Abstract classes promote modular, maintainable, and extensible code for easier future modifications.

Abstract Class in C# with example

Declaring an abstract class in C# is very similar to declaring a regular class. However, you must use the abstract keyword before the class keyword. Additionally, you can declare one or more abstract methods within the abstract class by using the abstract keyword before the method signature. Here is an abstract class example in c#:

public abstract class Shape
{
    public abstract double GetArea();
    public abstract double GetPerimeter();
}

The Shape class, in the above example of abstract class in c# is an abstract class that defines two abstract methods, GetArea and GetPerimeter. Any derived class that inherits from the Shape class must implement these methods.

To create a derived class that inherits from an abstract class, you can use the colon (:) symbol followed by the name of the base class. Here is an example:

public class Rectangle : Shape
{
    private double length;
    private double width;

    public Rectangle(double l, double w)
    {
        length = l;
        width = w;
    }

    public override double GetArea()
    {
        return length * width;
    }

    public override double GetPerimeter()
    {
        return 2 * (length + width);
    }
}

In this c# abstract class example, the Rectangle class inherits from the Shape class and implements the GetArea and GetPerimeter methods.

Advantages of Abstract Classes in C#

There are several advantages of using abstract classes in C#. First, they enable you to define a common interface or behavior that can be inherited by multiple derived classes. This makes it easier to write maintainable and scalable code. Second, abstract classes enable polymorphism, which means that you can create objects of derived classes and treat them as objects of the base class. This can help you write more flexible and generic code.

Example of abstract class in c#

Follwoing you will see multiple example of abstract class in c#.

  1. Basic Abstract Class C# Example : Declaring and Using an Abstract Class in C#

    public abstract class Vehicle
    {
        public abstract void Start();
        public abstract void Stop();
    }
    
    public class Car : Vehicle
    {
        public override void Start()
        {
            Console.WriteLine("Starting Car");
        }
    
        public override void Stop()
        {
            Console.WriteLine("Stopping Car");
        }
    }
    
    public class Motorcycle : Vehicle
    {
        public override void Start()
        {
            Console.WriteLine("Starting Motorcycle");
        }
    
        public override void Stop()
        {
            Console.WriteLine("Stopping Motorcycle");
        }
    }
    
    // Create objects of derived classes and call their methods
    Vehicle car = new Car();
    car.Start();
    car.Stop();
    
    Vehicle motorcycle = new Motorcycle();
    motorcycle.Start();
    motorcycle.Stop();
    
  2. Another Abstract Class Example in C# with Inheritance

    public abstract class Animal
    {
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    public class Cow : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Moo");
        }
    }
    
    // Create objects of derived classes and call their methods
    Animal cat = new Cat();
    cat.MakeSound();
    
    Animal dog = new Dog();
    dog.MakeSound();
    
    Animal cow = new Cow();
    cow.MakeSound();
    
  3. C# Abstract Class Example with Properties

    public abstract class Employee
    {
        public abstract string Name { get; set; }
        public abstract int Age { get; set; }
    }
    
    public class Manager : Employee
    {
        private string name;
        private int age;
    
        public override string Name
        {
            get { return name; }
            set { name = value; }
        }
    
        public override int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
    
    // Create an object of the derived (child) class and set its properties
    Employee manager = new Manager();
    manager.Name = "John Doe";
    manager.Age = 40;
    
    // Display the values of the properties
    Console.WriteLine(manager.Name);
    Console.WriteLine(manager.Age);
    
  4. C# Abstract Class Example with Constructors

    public abstract class Animal
    {
        protected string name;
    
        public Animal(string n)
        {
            name = n;
        }
    
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public Cat(string n) : base(n)
        {
        }
    
        public override void MakeSound()
        {
            Console.WriteLine(name + " says Meow");
        }
    }
    
    // Create an object of the derived class and call its method
    Animal cat = new Cat("Fluffy");
    cat.MakeSound();
    
  5. Abstract Class in C# with example of Static Methods

    When you declare a static method into C# abstract class, you must provide its implementation into that abstract class. Static methods are not directly associated with instances of the class, and it should be called using the class name.

    public abstract class Shape
    {
        public abstract double GetArea();
    
        public static double CalculatePerimeter(Shape shape)
        {
            double perimeter = 0;
            Type type = shape.GetType();
    
            if (type == typeof(Rectangle))
            {
                Rectangle rectangle = (Rectangle)shape;
                perimeter = 2 * (rectangle.Length + rectangle.Width);
            }
            else if (type == typeof(Circle))
            {
                Circle circle = (Circle)shape;
                perimeter = 2 * Math.PI * circle.Radius;
            }
    
            return perimeter;
        }
    }
    
    public class Rectangle : Shape
    {
        public double Length { get; set; }
        public double Width { get; set; }
    
        public override double GetArea()
        {
            return Length * Width;
        }
    }
    
    public class Circle : Shape
    {
        public double Radius { get; set; }
    
        public override double GetArea()
        {
            return Math.PI * Radius * Radius;
        }
    }
    
    // Create objects of derived classes and call the static method
    Rectangle rectangle = new Rectangle() { Length = 10, Width = 5 };
    double rectanglePerimeter = Shape.CalculatePerimeter(rectangle);
    Console.WriteLine(rectanglePerimeter);
    
    Circle circle = new Circle() { Radius = 5 };
    double circlePerimeter = Shape.CalculatePerimeter(circle);
    Console.WriteLine(circlePerimeter);
    
  6. Example of Abstract Class in C# with Interfaces

    public interface IAnimal
    {
        void MakeSound();
    }
    
    public abstract class Animal : IAnimal
    {
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    // Create objects of derived classes and call their methods
    IAnimal cat = new Cat();
    cat.MakeSound();
    
    IAnimal dog = new Dog();
    dog.MakeSound();
    
  7. Example of Abstract Class in C# with Generics

    public abstract class Animal
    {
        public string Name { get; set; }
    
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    public class AnimalList<T> where T : Animal
    {
        private List<T> animals = new List<T>();
    
        public void Add(T animal)
        {
            animals.Add(animal);
        }
    
        public void MakeSounds()
        {
            foreach (T animal in animals)
            {
                animal.MakeSound();
            }
        }
    }
    
    // Create objects of derived classes and add them to the generic list
    AnimalList<Cat> cats = new AnimalList<Cat>();
    cats.Add(new Cat() { Name = "Fluffy" });
    cats.Add(new Cat() { Name = "Whiskers" });
    
    AnimalList<Dog> dogs = new AnimalList<Dog>();
    dogs.Add(new Dog() { Name = "Fido" });
    dogs.Add(new Dog() { Name = "Rex" });
    
    // Call the method to make the animals in the list make sounds
    cats.MakeSounds();
    dogs.MakeSounds();
    
  8. Abstract Class C# example with Delegates

    public abstract class Animal
    {
        public string Name { get; set; }
    
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    public delegate void AnimalSoundHandler();
    
    public class AnimalHandler
    {
        public event AnimalSoundHandler AnimalSoundEvent;
    
        public void MakeAnimalSound()
        {
            if (AnimalSoundEvent != null)
            {
                AnimalSoundEvent();
            }
        }
    }
    
    // Create objects of derived classes and add them to an event handler
    Cat cat = new Cat() { Name = "Fluffy" };
    Dog dog = new Dog() { Name = "Fido" };
    
    AnimalHandler animalHandler = new AnimalHandler();
    animalHandler.AnimalSoundEvent += new AnimalSoundHandler(cat.MakeSound);
    animalHandler.AnimalSoundEvent += new AnimalSoundHandler(dog.MakeSound);
    
    // Call the event handler to make the animals make sounds
    animalHandler.MakeAnimalSound();
    
  9. Abstract Class C# example with Lambda Expressions

    public abstract class Animal
    {
        public string Name { get; set; }
    
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    public class AnimalList
    {
        private List<Animal> animals = new List<Animal>();
    
        public void Add(Animal animal)
        {
            animals.Add(animal);
        }
    
        public void MakeSounds()
        {
            animals.ForEach(animal => animal.MakeSound());
        }
    }
    
    // Create objects of derived classes and add them to the list using lambda expressions
    AnimalList animalList = new AnimalList();
    animalList.Add(new Cat() { Name = "Fluffy" });
    animalList.Add(new Dog() { Name = "Fido" });
    
    // Call the method to make the animals in the list make sounds using a lambda expression
    animalList.MakeSounds();
    
  10. Abstract Class Example in C# with LINQ

    public abstract class Animal
    {
        public string Name { get; set; }
    
        public abstract void MakeSound();
    }
    
    public class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }
    
    public class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Woof");
        }
    }
    
    public class AnimalList
    {
        private List<Animal> animals = new List<Animal>();
    
        public void Add(Animal animal)
        {
            animals.Add(animal);
        }
    
        public List<Animal> GetAnimalsThatMakeSound(string sound)
        {
            return animals.Where(animal => animal.GetType().Name == sound).ToList();
        }
    }
    
    // Create objects of derived classes and add them to the list
    AnimalList animalList = new AnimalList();
    animalList.Add(new Cat() { Name = "Fluffy" });
    animalList.Add(new Dog() { Name = "Fido" });
    animalList.Add(new Cat() { Name = "Whiskers" });
    animalList.Add(new Dog() { Name = "Rex" });
    
    // Call the method to get the animals in the list that make a certain sound using LINQ
    List<Animal> meowingAnimals = animalList.GetAnimalsThatMakeSound("Cat");
    List<Animal> barkingAnimals = animalList.GetAnimalsThatMakeSound("Dog");
    
    // Call the method to make the animals in the list make sounds using a for loop
    foreach (Animal animal in meowingAnimals)
    {
        animal.MakeSound();
    }
    
    foreach (Animal animal in barkingAnimals)
    {
        animal.MakeSound();
    }
    

Summary

In this article, we have discussed what abstract classes are and how they can be used in C# with 10 code samples. Abstract classes provide a way to define a blueprint for derived classes while also providing default implementations for some or all of their members. By using abstract classes, you can create more modular and maintainable code that can be easily extended and modified in the future.

We have covered a variety of scenarios in which abstract classes can be used, including inheritance, polymorphism, encapsulation, interfaces, generics, delegates, lambda expressions, and LINQ. By providing concrete examples for each of these scenarios, we hope that you have a better understanding of how to use abstract classes in your own C# projects.

Strengthen your knowledge about What is Abstract Class in C#, by reading our other detailed articles on this topic we have for you! C# Abstract Class, Difference between abstract class and interface in c#, Abstract class vs Interface c#.