Software & Finance





C# Abstract Class





 

Abstract class mean you can not create an instance directly for that class. In order to create an instance, you must have derived class. In this example page, shape is an abstract class. abstract keyword is used to create the abstract class unlike in c++ which uses pure virtual function to create the abstract class.

 

In C#, class is a reference type and it supports inheritance. But it does not support multiple inheritance. You can have private, protected and public members inside a class. You can also have a static methods and variables inside a class.

 

In the given example code, we have Shape is an abstract base class and Triangle is the derived class derived from the class Shape. Rectangle class has a constructor which will take 3 integers as input values.

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

 

namespace CShapeExample

{

    abstract class Shape

    {

        public Shape()

        {

            System.Console.WriteLine("Shape");

        }

 

        public virtual void draw()

        {

            System.Console.WriteLine("Drawing Shape");

        }

    }

 

    class Triangle : Shape

    {

        public int a, b, c;

 

        public Triangle(int a, int b, int c)

        {

            this.a = a;

            this.b = b;

            this.c = c;

            System.Console.WriteLine("Triangle: " + a.ToString() + " " + b.ToString() + " " + c.ToString());

        }

 

        public Triangle()

        {

            System.Console.WriteLine("Triangle");

        }

 

 

        public override void draw()

        {

            System.Console.WriteLine("Drawing Triangle");

        }

    }

 

    struct CData

    {

        public int m;

        public Shape[] objects;

 

        public CData(int count)

        {

            m = 0;

            objects = new Shape[count];

        }

    }

 

    class InheritanceSample

    {

        static void Main()

        {

            //Shape m = new Shape(); // Cannot create an instance of the abstract class CSharpExample.Shape

            CData data = new CData(2);

            data.objects[0] = new Triangle();

            data.objects[1] = new Triangle(10, 20, 30);

           

            System.Console.WriteLine("\n\nNow Drawing Objects\n");

 

            for (int i = 0; i < 2; i++)

                data.objects[i].draw();

 

            System.Console.WriteLine("\n");

        }

    }

}

Output


Shape
Triangle
Shape
Triangle: 10 20 30

 

Now Drawing Objects
Drawing Triangle
Drawing Triangle