- 출처 : ChatGPT 3.5
In C#, both structs and classes are used to define custom types, but they have some important differences in terms of their behavior and usage:
Classes:
- Reference Types: Classes are reference types, meaning when you create an instance of a class, you're actually creating a reference to the object in memory.
- Heap Allocation: Objects of a class are allocated memory on the heap. This means that they have dynamic memory allocation and deallocation, and their lifetimes are managed by the garbage collector.
- Inheritance: Classes support inheritance, allowing you to create hierarchies of related types.
- Mutable: Class instances are mutable by default, meaning you can change their state after creation.
- Pass by Reference: When you pass an instance of a class to a method, you're passing it by reference. This means changes made to the object inside the method affect the original object.
Example:
class MyClass
{
public int MyProperty { get; set; }
}
Structs:
- Value Types: Structs are value types, meaning when you create an instance of a struct, you're working directly with the data itself, not a reference to it.
- Stack Allocation: Struct instances are typically allocated on the stack. They have a fixed size determined by their members.
- No Inheritance: Structs do not support inheritance. They cannot be used as a base for other structs or classes.
- Immutable: Structs are immutable by default. Once created, their state cannot be changed.
- Pass by Value: When you pass an instance of a struct to a method, you're passing it by value. This means changes made to the struct inside the method do not affect the original struct.
Example:
struct MyStruct
{
public int MyField;
}
Choosing Between Structs and Classes:
- Use structs:
- When you need lightweight objects.
- When the object logically represents a single value, like a Point or a DateTime.
- When you want value semantics, or if you need to pass the object by value frequently.
Use classes:
- For complex objects that require inheritance or are intended to be used as base classes.
- When you need reference semantics, or if you need to share the object across multiple parts of your code without making copies.
Understanding these differences is crucial for designing efficient and effective solutions in C#.
'Language > C#' 카테고리의 다른 글
책 [C# 교과서] 인터페이스 주요 문장 (0) | 2024.04.13 |
---|---|
책 [C# 교과서] 목차 별 익숙한 정도를 상부터 하까지 (0) | 2024.04.13 |
Jetbrains Rider 새로운 UI Beta 버전 (0) | 2023.02.12 |
C# null 조건 연산자 (null conditional operator) (0) | 2023.02.11 |
책 [이것이 C#이다] Action 대리자 샘플코드 (0) | 2022.11.08 |