Junior — Middle
In what cases is it preferable to use structured data types instead of classes?
sobes.tech AI
Answer from AI
Structured data types (struct) in C# are preferred when:
- Lightweight objects are needed that are created and destroyed frequently.
- Objects have a small size and do not require inheritance.
- To avoid overhead associated with memory management related to classes (which are reference types).
Struct is a value type stored on the stack, which can improve performance when working with small data.
Example of using struct:
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
If inheritance, polymorphism, or a long-lived object is required, it is better to use classes.