What are the Difference between Structure and Class??
Abhishek Yadav
Select an image from your device to upload
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.