Get me outta here!

Monday, August 19, 2024

Class/Record/Struct

 

FeatureClassRecordStruct
TypeReference TypeReference Type (since C# 10, can be record struct)Value Type
Memory AllocationTypically 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 ConstructorCan 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.
InheritanceSupports 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).
EqualityUses 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.
MutabilityMutable 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).
DeconstructionNot supported by default.Supports deconstruction with tuple-like syntax.Supports deconstruction with tuple-like syntax.
ConstructorCan 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 ValuesFields 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 CasesUsed 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