Avatar ·

When to use struct instead of class in C#: understanding value types and reference types

Hi everyone! I've been writing in C# for about a year, and I'm constantly troubled by the question: when should I use struct and when class? I seem to understand the difference — struct is a value type, and class is a reference type. But in practice, I often get lost.\n\nFor example, I have this code:\n\n```csharp\npublic class PointClass\n{\n public int X { get; set; }\n public int Y { get; set; }\n \n public PointClass(int x, int y) { X = x; Y = y; }\n}\n\npublic struct PointStruct\n{\n public int X { get; set; }\n public int Y { get; set; }\n \n public PointStruct(int x, int y) { X = x; Y = y; }\n}\n```\n\nBoth seem to do the same thing. But I've read that struct is faster for small objects because they are stored on the stack, while class is stored on the heap. On the other hand, I've heard that struct should not be used