Sobes.tech
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: struct is stored on the stack (if a local variable) or inline in an object, class is stored on the heap, and the variable contains a reference.
  • Passing: when passing, struct is copied, when passing class, the reference is copied.
  • Inheritance: struct does not support inheritance (except for implementing interfaces), class supports inheritance.
  • Constructors: struct has 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.

What is a struct, and how does it differ from a… - sobes.tech