Difference Between Struct and Classes in C#

The main difference between class and Struct

Class – Reference type .

Which means only a reference to a location is stored.

Struct – Value type.

Which means the value is stored.

Now lets create a class and struct a simple one that looks like.

// A class song

class Song
{
public string name;

}

// A struct songs

struct Songs

{
public string name;
}

// A console Application to demonstrate
class Program
{
static void Main(string[] args)
{
// reference type  – Two classes are created s , s1 
Song s = new Song();
Song s1 = new Song();

// A value is assigned to s 


s.name = “All Rise”;

// s –> s1 which means the reference to the value at a memory location is assigned to s1 


s1 = s;
Console.WriteLine(“Initial Value”);
Console.WriteLine(“from s1 :” + s1.name);
Console.WriteLine(“from s :” + s.name);

Console.WriteLine(“change to s1”);

//Any change to s1 is reflected to s also 


s1.name = “Beautiful”;
Console.WriteLine(“from s1 :”+s1.name);
Console.WriteLine(“from s :” + s.name);
Console.ReadLine();

// value type
Songs s3 = new Songs();
Songs s4 = new Songs();
s3.name = “All Rise”;
s4 = s3;
Console.WriteLine(“Initial Value”);
Console.WriteLine(“from s1 :” + s4.name);
Console.WriteLine(“from s :” + s3.name);

 

// Same thing is done in a struct but the values in s3 and s4will be different 

 

Console.WriteLine(“change to s1”);
s4.name = “Beautiful”;
Console.WriteLine(“from s1 :” + s4.name);
Console.WriteLine(“from s :” + s3.name);
Console.ReadLine();
}
}

Output

Initial Value
from s1 :All Rise
from s :All Rise
change to s1
from s1 :Beautiful
from s :Beautiful

Initial Value
from s1 :All Rise
from s :All Rise
change to s1
from s1 :Beautiful
from s :All Rise

Hope you got the Difference. Ideally you can use a struct in case the size of the object is small. And you have a case as mentioned above.

How ever there are some things you need to know before using a struct .

– cannot have explicit parameterless constructor where as a class can.
-cannot have destructors.
-can’t inherit from another class.

 

Hope You got the Difference 🙂 .

 

 

Advertisements