Typely
GitHub
  • Overview
    • πŸ‘Welcome!
  • Validations
    • πŸ“Common
    • πŸ”’Number
    • βš–οΈComparable
    • ✏️String
  • Customize errors
    • 🌎Localization
    • πŸ”Sensitive data
  • General
    • 🧩Class VS Struct
    • πŸ–ΌοΈSupported frameworks
    • πŸš€Benchmarks
    • ⚠️Limitations
  • Design decisions
    • πŸ”„Conversions
    • ℹ️Use of interfaces
    • πŸ€Έβ€β™‚οΈUnderlying type comparison
    • πŸ’‚Validations
Powered by GitBook
On this page
Edit on GitHub
  1. General

Class VS Struct

PreviousSensitive dataNextSupported frameworks

Last updated 2 years ago

Theses are the two main constructs to create de type. A class witch is a reference type, will be allocated on the heap and garbage-collected whereas a struct, a value type, will be allocated on the stack or inlined in the containing type then deallocated when their containing type gets deallocated or simply by moving the stackpointer back to the previous function. Therefore memory management of value types will generally be less expensive.

C# 9.0 introduced record types to the language and provides an easy way to declare reference types with equality based on immutable values. C# 10 came with record structs to declare value types witch have the same benefits of traditional records. Under the hood, records generates struct or class with an implementation of IEquatable and operators ==, !=.

So because record is just syntactic sugar, Typely won't use it but offers the same functionality of creating a value type or a reference type like so:

// By default, generated types will be like their underlying value.
builder.OfDecimal().For("Cost");
builder.OfString().For("Description").AsStruct(); // Makes a struct.
builder.OfDecimal().For("Rating").AsClass(); // Makes a reference type.
🧩
Choosing Between Class and Struct - Framework Design Guidelinesdocsmsft
Logo
What's new in C# 9.0 - C# Guidedocsmsft
Logo
What's new in C# 10 - C# Guidedocsmsft
Logo