Junior — Middle
What are the differences between a class and a structure in programming?
sobes.tech AI
Answer from AI
Main differences between class and struct in C#:
- Data type: Classes are reference types, structs are value types.
- Storage: Classes are stored on the heap, structs on the stack (unless they are part of a class).
- Inheritance: Classes support inheritance, structs do not.
- Constructors: Structs cannot have parameterless constructors, classes can.
- Passing: When passing a struct to a method, a copy is created; when passing a class, a reference is passed.
Example:
struct Point {
public int X, Y;
}
class Person {
public string Name;
}
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1; // copy
p2.X = 3;
// p1.X will remain 1
Person person1 = new Person { Name = "Ivan" };
Person person2 = person1; // reference
person2.Name = "Peter";
// person1.Name will also change to "Peter"
The choice between class and struct depends on the task and requirements for performance and semantics.