Structures in .NET

In simple terms, Structure is a composite datatype. Structures are value in type in .NET.

syntax :

Struct <Strcuture_Name>
{
    int i;
}

In a structure we cannot initialize the variables in a structure, variables can only be initialized thru functions or objects.

    struct Structure
    {
        //Structure cannot have PARAMETER-LESS construtors
        //public Structure()
        //{ }

        // DEFAULT is PRIVATE
        int j; //Field must be fully assigned before control leaves the constructor	

        //Structs cannot contain explicit parameterless constructors

        //Struct are assumpted to be lightweight. According to it,
        //all struct have compiler-defined default constructor(with
        //no parameters), that assigns all values to zero value(0 to
        //int,null to ref,e.t.c.). This constuctor is more
        //effective, than putting zero one-one at other constructor.
        //Use Static constructor if you want to initialize some thing before hand.

        //public Structure() { }

        public Structure(int i)
        {
            j = i; //As structure require us to assign a value to field in constructor
        }

        public string s_method1()
        {
            return "struct1";
        }

        public override string ToString()
        {
            return string.Format("value of i is {0}", j.ToString());
        }
    }

    struct Structure1
    {
        Structure s; //can not have  = new Structure(1); statement here as we cannot define the feilds here (either in function or constructors else they will take the default value.
        string s_method2()
        {
            s = new Structure(1);
            return s.s_method1();
        }

    }

By default all the structure are sealed, as they are already sealed. Objects of strcuture are always created on stack as they are value types.

There is no option of declaring a default parameter less constructure in case of structures as compiler defined this constructor by default.
We cannot have a destructor for strcutures

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*