Structures in Csharp.net
for programmers

Structures are defined in exactly the same way as classes

(Replacing the keyword class with struct)

However the instances of structures will be treated as value types.

They are suitable for light weight objects like points, rectangles, colors, etc.

Structures cannot have default constructors.

We can create instances of structures without using new keyword, if we do not want to call a constructor.

We can create instances of structures with new keyword if we want to use a constructor.

 

using System;

namespace Structure_Example

{

    class Program

    {

        static void Main(string[] args)

        {

            Rectangle rec1;

            rec1.lenght = 3;

            rec1.width = 2;

 

            Rectangle rec2;

            rec2.lenght = 5;

            rec2.width = 6;

 

            Rectangle rec3 = new Rectangle(2, 4);

            float area1 = rec1.GetArea();

            float area2 = rec3.GetArea();

            Console.WriteLine("{0},{1}", area1, area2);

            Console.Read();

        }

    }

}

 

struct Rectangle

{

    public float width;

    public float lenght;

 

    public Rectangle(float l, float w)

    {

        width = w;

        lenght = l;

    }

    public float GetArea()

    {

        return width * lenght;

    }

}

 

Output will be:

6,8