Middle+
What is a struct, and how does it differ from a class?
sobes.tech AI
Answer from AI
In C#, a struct is a value type, and a class is a reference type. Main differences:
- Storage:
structis stored on the stack (if a local variable) or inline in an object,classis stored on the heap, and the variable contains a reference. - Passing: when passing,
structis copied, when passingclass, the reference is copied. - Inheritance:
structdoes not support inheritance (except for implementing interfaces),classsupports inheritance. - Constructors:
structhas a restriction — no parameterless constructor, initialized by default.
Example:
struct Point {
public int X;
public int Y;
}
class Person {
public string Name;
}
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1; // copy
p2.X = 3; // p1.X remains 1
Person person1 = new Person { Name = "Alice" };
Person person2 = person1; // reference
person2.Name = "Bob"; // person1.Name will also change
struct is used for small, immutable data where performance and lack of garbage collection overhead are important.