Feature | Class | Record | Struct |
---|---|---|---|
Type | Reference Type | Reference Type (since C# 10, can be record struct ) | Value Type |
Memory Allocation | Typically allocated on the heap. | Typically allocated on the heap. | Typically allocated on the stack (or heap if used as part of a class or array) |
Default Constructor | Can have a parameterless constructor, and can be explicitly defined. | Implicit parameterless constructor is not allowed; parameters are required. | Parameterless constructor is provided by default and initializes all fields to default values. |
Inheritance | Supports inheritance (can inherit from other classes and be inherited). | Supports inheritance (can inherit from other records but not from classes). | Does not support inheritance (cannot inherit from or be inherited by other types). |
Equality | Uses reference equality by default, can override Equals and GetHashCode for value-based equality. | Uses value-based equality by default (based on all properties). Automatically implements Equals , GetHashCode , and ToString . | Uses value-based equality by default (based on all fields). Automatically implements Equals , GetHashCode , and ToString . |
Mutability | Mutable by default; properties can be changed after object creation. | Immutable by default; properties are readonly and set via constructor. | Immutable by default (properties are typically readonly and initialized in the constructor). |
Deconstruction | Not supported by default. | Supports deconstruction with tuple-like syntax. | Supports deconstruction with tuple-like syntax. |
Constructor | Can have multiple constructors with various parameters. | Primary constructor is defined with positional parameters; can also have additional constructors. | Constructor must initialize all fields; no parameterless constructor allowed unless provided by the compiler. |
Default Values | Fields initialized to default values if not explicitly set. | Properties are initialized via the constructor. | Fields are initialized to default values (e.g., 0 , null ). |
Use Cases | Used for complex objects with behavior and mutable state. | Ideal for immutable data models, DTOs, and scenarios where value-based equality is important. | Ideal for lightweight, immutable data structures where copying and stack allocation are beneficial. |
0 comments:
Post a Comment