I need use an empty value for an struct.
I don't know which is the best option to do it. I was thinking on use an static readonly field on the struct for it, but I'm not sure if it's the best option to do it or not. Maybe a method on a common class, that returns the empty, is a better option.
I'm using the struct for performance reasons, so change it to a class is not an option. And I don't sure if I use the static field, the size of each struct instance will be increased.
Any ideas?
Are there any values for the struct which would naturally be invalid? In particular, you can always write:
MyStruct x = new MyStruct();
which will end up with all the bits being 0. If that's not a valid state for your struct for some reason (e.g. you've got an integer value which is always set to non-zero in the constructor) then that's great - use that as your "empty" value. You can create a static field with that value if you want:
public static readonly MyStruct Empty = new MyStruct();
Note that adding a static field will not add any overhead to instances of your struct.
If every possible bit pattern in your struct is already a valid value, however, you'll need a different approach - either adding an extra field to your struct, or adding an extra field to any pieces of code which use your struct and may need to represent a "missing" value.
You say that using a class isn't an option "for performance reasons" - is this because you've performed rigorous benchmarking of the difference in your situation?
The common idiom in .net framework is to have a static readonly field named "Empty" like Size.Empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With