Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null / Empty value for a struct in .Net 1.x

Tags:

c#

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?

like image 624
Borja Avatar asked Oct 25 '25 06:10

Borja


2 Answers

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?

like image 108
Jon Skeet Avatar answered Oct 27 '25 19:10

Jon Skeet


The common idiom in .net framework is to have a static readonly field named "Empty" like Size.Empty.

like image 38
codymanix Avatar answered Oct 27 '25 19:10

codymanix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!