Sunday, May 26, 2013

What is a Struct?

Structs can be used to define custom types, which are build using a combination of the primitive types like int, string etc. For example we can define an Employee Struct which can hold details of the employee id, name, address etc in individual types like int, string etc.

Structs are value types while classes are reference types, which means that every instance of the Struct is completely independent and have their own set of values. If a struct instance A is assigned to struct instance B then both A & B have their own memory and have an independent set of value, hence any change to instance A will not affect instance B.

The below example defines a simple Struct which contains an integer id and a string name representing an employee details.

    struct SEmployee
    {
        public int id;
        public string Name;
    }

An instance of a Struct can be made similar to a class instance, by using the new keyword as follows.

    SEmployee objStruct1 = new SEmployee();
    objStruct1.id = 1;
    objStruct1.Name = "Name1";

Instances of structs can also be created without using the new keyword as follows, this will also work.

    SEmployee objStruct1;
    objStruct1.id = 1;
    objStruct1.Name = "Name1";

Stucts can also be declared using constructors, but unlike classes Structs cannot have empty constructors without parameters, if a constructor is declared on a struct then it should get the values of all the members of the struct and initialize their values. The struct which we defined above will have a constructor as follows.

    struct SEmployee
    {
        public int id;
        public string Name;
        //
        public SEmployee(int nid, string sName)
        {
            id = nid;
            Name = sName;
        }

    }

Search Flipkart Products:
Flipkart.com

No comments: