C# Abstract Class

Tutorials PanelPosted by

In this lesson, you will learn about abstract classes with example. Also, you will learn when to use abstract classes in your program. 

Definition of abstract class

In c#, abstract class are mostly used to define base class. As discussed previously in the inheritance lesson, we learned that a base class is to top class in the hierarchy of group of classes. However, the abstract class can’t be initiated but only inherited from. The abstract class contains abstracting of objects and can contains only top-level properties to be inherited from derived class. For example, the class Animal can be abstracted so it not getting used in the code other than for inheritance purpose from the Dogs, Cats, Birds, etc…

So why do we need to use abstract class? Well, if you are creating an application that will used somewhere else in that application, or other application, such as DLL or framework, the abstraction will help you to have top level classes that can’t be initiated but to serve the purpose of inheritance for derived class, and help whoever is using your DLL or application to understand what the class concept is about. 

The abstract class can inherit from a class. It can contain methods, properties, constants, fields, and can have instructors and destructors.  again, the difference between an abstract class and base class is that an abstract class cannot be initiated, where a base class can. 

Example of Abstract Class

   public abstract class Animal
    {
        public string AnimalType;
        public abstract string WriteToConsole();

    }

Now create classes that inherit from the Abstract Class above:

    class Dog : Animal
    {
        public override string WriteToConsole()
        {
            base.AnimalType = "I'm a dog";
            return base.AnimalType;
        }
    }
    class Cat : Animal
    {
        public override string WriteToConsole()
        {
            base.AnimalType = "I'm a cat";
            return base.AnimalType;

        }
    }

Now create instantce of these classes in the main method:

        public static void Main(string[] args)
        {
            Dog dog = new Dog();
            Cat cat = new Cat();
            Console.WriteLine(dog.WriteToConsole());
            Console.WriteLine(cat.WriteToConsole());
            Console.ReadKey();
        }

Output

I’m a dog
I’m a cat

Now let try to create an instance of the abstract class:

Animal _animal = new Animal();

Run the application, the following build error will occur:

Error 1 Cannot create an instance of the abstract class or interface ‘YourApp.Program.Animal

Leave a Reply