Saturday 7 May 2011

Structs in C#

Structs
 Structure is the collection of dissimilar data types. A struct is a simple user-defined type, a lightweight alternative to classes.  Structs are somewhat more efficient in their use of memory in arrays. The C# struct is a lightweight alternative to a class. It can do almost the same as a class, but it's less "expensive" to use a struct rather than a class.

class Program
{
    static void Main(string[] args)
    {
        Home home;

        Home = new Home("Blue");
        Console.WriteLine(Home.Describe());

        Home = new Home("Red");
        Console.WriteLine(Home.Describe());

        Console.ReadKey();
    }
}

struct Home
{
    private string color;

    public Home(string color)
    {
        this.color = color;
    }

    public string Describe()
    {
        return "This Home is " + Color;
    }

    public string Color
    {
        get { return color; }
        set { color = value; }
    }
}
     A struct is a value type and a class is a reference type.
    When a struct is created, the variable to which the struct is assigned holds the struct's actual data. and When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory.
    When the struct is assigned to a new variable, it is copied and When the object reference is assigned to a new variable.
    The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. the new variable refers to the original object.
     In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created.
     Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
When to Use Structures?

• If the instances are relatively small
• If the instance life-time is going to be very short
If you are going to embed the instance into some other instances

No comments:

Post a Comment