Sobes.tech
Junior — Middle

Is it possible to instantiate an abstract class directly in the code?

sobes.tech AI

Answer from AI

In C#, an abstract class cannot be instantiated directly. This is because an abstract class may contain abstract methods without implementation, and the compiler will not allow creating an object of such a class.

To use an abstract class, you need to create a derived class that implements all abstract methods, and then you can instantiate this derived class.

Example:

abstract class Animal
{
    public abstract void MakeSound();
}

class Dog : Animal
{
    public override void MakeSound() {
        Console.WriteLine("Woof!");
    }
}

// Error: cannot create an object of an abstract class
// Animal a = new Animal(); 

// Correct:
Animal dog = new Dog();
dog.MakeSound(); // Outputs "Woof!"