Yet another question about struct & class
So, here I am, having this code
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
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
Okay, so am I safe using only classes and completely omitting structs? At least that what I read a couple of times.
For the most part, yes
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?Yes using classes by default should be fine.
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.