Sobes.tech
Junior — Middle

What is the main difference between defining a class and a structure in programming?

sobes.tech AI

Answer from AI

The main difference between a class and a struct in C# is that a class is a reference type, while a struct is a value type. This affects how they are stored in memory and passed to methods:

  • Classes are stored on the heap, and variables contain a reference to the object.
  • Structs are stored on the stack (if they are local) and are copied when passed.

Because of this, structs are usually used for small, immutable data, while classes are used for more complex objects with behavior and inheritance.

Example:

struct Point
{
    public int X;
    public int Y;
}

class Person
{
    public string Name;
}