C
Join ServerC#
help
❔ static fields for struct types
GGladiator12/10/2022
(1)
or as Utility class
(2)
The first and second one are the same but I have seen some libs prefer to implement them like (2)
(3)
and what is the benefit of implementation (3)
public static class StructA
{
public static readonly StructA ValueA = new (..) ;
}
or as Utility class
public static class Utility
{
public static readonly StructA ValueA = new (..) ;
}
(2)
public static class Utility
{
private static readonly StructA _valueA = new (..) ;
public static StructA ValueA => _valueA;
}
The first and second one are the same but I have seen some libs prefer to implement them like (2)
(3)
public static class Utility
{
// Initialize every time.
public static StructA ValueA => new(..);
}
and what is the benefit of implementation (3)
GGladiator12/10/2022
What about defensive copy for readonly structs?
Mmtreit12/10/2022
The arrow syntax defines a property. It's almost always preferred to use properties instead of public fields so you can change your implementation later (for instance, add some input validation on set) without it being a breaking change to consumers of your class.
Mmtreit12/10/2022
In general, don't expose public fields.
Mmtreit12/10/2022
I'm not sure what you mean by defensive copy of readonly structs. Any read of a struct is generally going to make a copy.
OOrannis12/11/2022
The benefit of 3, for simple struct creations, is that you're not taking up space for an unnecessary field
AAccord12/12/2022
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.