Software & Finance





C# struct





 

In C#, struct is a value type and it does not support inheritance. so struct members can not be declared as protected. You can have constructor in struct. You can have another class as a reference type member variable.

 

In the given example code, we have a struct called CData and it has got two data members. One is the integer and another one is an array of Shape class. It has got a constructor method which will take the number of Shape objects as one argument.

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

 

namespace CSharpExample

{

    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()

        {

            CData data = new CData(2);

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

            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

Shape

Triangle: 10 20 30

Now Drawing Objects

Drawing Shape

Drawing Triangle