C
C#2y ago
Gladiator

❔ static fields for struct types

(1)
public static class StructA
{
public static readonly StructA ValueA = new (..) ;
}
public static class StructA
{
public static readonly StructA ValueA = new (..) ;
}
or as Utility class
public static class Utility
{
public static readonly StructA ValueA = new (..) ;
}
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;
}
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(..);
}
public static class Utility
{
// Initialize every time.
public static StructA ValueA => new(..);
}
and what is the benefit of implementation (3)
4 Replies
Gladiator
GladiatorOP2y ago
What about defensive copy for readonly structs?
mtreit
mtreit2y ago
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. In general, don't expose public fields. 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.
333fred
333fred2y ago
The benefit of 3, for simple struct creations, is that you're not taking up space for an unnecessary field
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server