- Class are ref type and Struc are value type 2. Struc doesn’t support inheritance except interface. 3. Class use heap and Struc use Stacks 4 Class use concept of boxing and unboxing but Struc doesn’t use 5. members of struc are by default public where as in class members are private. 6. we can not create default constructor of struc
Interviews13 answers
What are the Difference between Structure and Class??
13 Answers
Struct vs Class
struct Location
{
public int x, y;
public Location(int x, int y)
{
this.x = x;
this.y = y;
}
}
Location a = new Location(20, 20);
Location b = a;
a.x = 100;
System.Console.WriteLine(b.x)
;
The output will be 20. Value of “b” is a copy of “a”, so “b” is unaffected by change of “a.x”. But in class, the output will be 100 because “a” and “b” will reference the same object.
To answer this question, we should have a good understanding of the differences.
1
Structs are value types, allocated either on the stack or inline in containing types.
Classes are reference types, allocated on the heap and garbage-collected.
2
Allocations and de-allocations of value types are in general cheaper than allocations and de-allocations of reference types.
Assignments of large reference types are cheaper than assignments of large value types.
3
In structs, each variable contains its own copy of the data (except in the case of the ref and out parameter variables), and an operation on one variable does not affect another variable.
In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable.










