How to Instantiate Abstract Class in C#
In C#, abstract classes cannot be directly instantiated because they are incomplete and may contain abstract methods or properties that need to be implemented by child classes.
To instantiate an abstract class, you need to create a concrete subclass that inherits from the abstract class, and then instantiate an object using the subclass. An example is shown below.
abstract class Animal
{
public abstract void MakeSound();
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main()
{
Animal myDog = new Dog();
myDog.MakeSound();
}
}
In the example above, the Animal class is an abstract class that contains an abstract method MakeSound. We then create a concrete subclass Dog, which implements the MakeSound method. Finally, in the Main method, we instantiate an Animal object myDog using the subclass Dog and call the MakeSound method to output “Woof”.