Thursday 19 July 2012

STRUCTURES


A structure is an enhanced version of the primitive data types we have used in previous lessons. Like a class, a structure is created from one variable of a primitive type or by combining various variables of primitive types.


To create a structure, you use the same formula as for a class but with the struct keyword. Here is an example of a structure:

struct Integer
{
}

Like a class, a structure can have fields. They are listed in the body of the structure. Here is an example:

struct Integer
{
    private int val;
}

A structure can also have properties. Here is an example:

struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }
}

A structure can also have methods. Here is an example:

struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }

    public int Read()
    {
        return int.Parse(Console.ReadLine());
}
 
    

 Differences between Class and Structure

·       Classes are Reference types and Structures are Values types.

·       Classes will support an Inheritance whereas Structures won’t.

·       Classes can have explicitly parameterless constructors whereas structures can’t.

·       Member variable initialization is possible in class whereas in Structures, it is not.

·       It is not possible to declare destructor in structure but in class it is possible.

·       Process of converting structure type into object type is called boxing and process of converting object type into structure type is called unboxing.

No comments:

Post a Comment