C
C#9mo ago
SpReeD

Yet another question about struct & class

So, here I am, having this code
public readonly record struct MinifigureDto {
public required int Id { get; init; }
public required string Name { get; init; }
public required int ThemeId { get; init; }
public required uint Amount { get; init; }
}
public readonly record struct MinifigureDto {
public required int Id { get; init; }
public required string Name { get; init; }
public required int ThemeId { get; init; }
public required uint Amount { get; init; }
}
This object won't change during runtime, so, should I make it a struct or a class? What is the devil in the detail?
6 Replies
mtreit
mtreit9mo ago
In this case it probably doesn't matter. I would probably just use record and not record struct since the former is immutable by default. The general rule is to use structs if the size is 16 bytes or less. There is no hard and fast rule here. Struct avoids heap allocations if you don't need to box it, but you copy the entire thing when you pass it around (instead of copying just an 8 byte pointer if it's a class) Does this matter? Totally depends on your application and usage patterns
SpReeD
SpReeDOP9mo ago
Okay, so am I safe using only classes and completely omitting structs? At least that what I read a couple of times.
Angius
Angius9mo ago
For the most part, yes
SpReeD
SpReeDOP9mo ago
To draw a line here, saying, if something represents a single piece of data, be it a Vector or an int64 like in DateTime the usage of struct is efficient. Structuring the object shown in my example as struct would not fit, since it represents a record/row from a database. Considering this, would it be best-practice to use only classes and later, by refactoring, changing them to structs if they meet specific condition, just to get some extra ms out of it?
mtreit
mtreit9mo ago
Yes using classes by default should be fine.
canton7
canton79mo ago
Choosing Between Class and Struct - Framework Design Guidelines
Learn how to decide whether to design a type as a class, or to design a type as a struct. Understand how reference types and value types differ in .NET.
Want results from more Discord servers?
Add your server