Wednesday, March 14, 2012

Difference between Struct and Class in c# (Struct Vs Class)

There is a FAQ I get from people: What is the difference between Struct and Class as we can design an object using both?

Class is a Reference type and struct is a Value type. This means Class instance refers the address of another instance assigned to it but a Struct instance copies the values of assigned object.

In other words if we create 2 class instances A and B, and assign B to A then any changes made to B will reflect in A also. But in Struct, A will hold a copy of values of B and any changes to B will be independent.

Example (ASP.NET/C#):

public class Class1
    {
        public string TestValue { get; set; }
        public Class1() { }
    }

protected void Page_Load(object sender, EventArgs e)
    {
        Class1 A = new Class1(); //Create an instance of a class Class1

        A.TestValue = "1";

        Response.Write("A.TestValue: " + A.TestValue);
        Response.Write("<br />");

        //Assign B to A

        Class1 B = A; //Create another instance of the same class Class1

        B.TestValue = "2";

        Response.Write("B.TestValue: " + B.TestValue);
        Response.Write("<br />");
        Response.Write("A.TestValue: " + A.TestValue);
    }

No comments:

Post a Comment

Share your comments