Language/C#
[ChatGPT-4] C# struct vs class
VirtualDever
2024. 6. 5. 09:29
Certainly! Let’s explore the differences between classes and structs in C#:
- Type Category:
- Class: A class is a reference type. Instances of classes are allocated on the heap, and they are managed by the garbage collector.
- Struct: A struct is a value type. Instances of structs are allocated either on the stack or inline within containing types. They are deallocated when the stack unwinds or when their containing type gets deallocated1.
- Memory Allocation:
- Class: Allocated on the heap.
- Struct: Allocated on the stack or inline in containing types (based on compiler optimizations). Value type allocations and deallocations are generally cheaper than reference type allocations and deallocations1.
- Inheritance and Polymorphism:
- Class: Supports inheritance and polymorphism.
- Struct: Does not support inheritance and cannot be inherited from another struct or class. It also cannot be a base class2.
- Default Constructor and Destructor:
- Class: Can have default constructors and destructors.
- Struct: Cannot have default constructors or destructors2.
- Access Modifiers:
- Class: Members are private by default.
- Struct: All members are public by default3.
In summary, choose a class when you need inheritance, polymorphism, or more complex behavior. Use a struct when you want a lightweight value type with better performance and no inheritance requirements. Keep in mind that excessive boxing and unboxing can impact performance when working with structs4. 🚀