This must have been answered already, but I can't find an answer:
Is there a quick and provided way of zeroing a struct
in C#, or do I have to provide someMagicalMethod
myself?
Just to be clear, I know the struct will be initialised to 0, I want to know if there's a quick way of resetting the values to 0.
I.e.,
struct ChocolateBar {
int length;
int girth;
}
static void Main(string[] args) {
ChocolateBar myLunch = new ChocolateBar();
myLunch.length = 100;
myLunch.girth = 10;
// Eating frenzy...
// ChocolateBar.someMagicalMethod(myLunch);
// myLunch.length = 0U;
// myLunch.girth = 0U;
}
The easiest solution is to write a method which does a reset of all the individual members. In C, we use memset(&struct_var, 0, sizeof(struct whatever)) when we know for sure that 0 or NULL is an acceptable initial value for all of its members. But in C++, it is tough to keep this assumption true always.
You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.
Structure members can be initialized using curly braces '{}'.
memset will set the structure to all-bits-zero whereas value initialization will initialize all members to the value zero. The C standard guarantees these to be the same only for integral types, not for floating-point values or pointers. Also, some APIs require that the structure really be set to all-bits-zero.
Just use:
myLunch = new ChocolateBar();
or
myLunch = default(ChocolateBar);
or
myLunch = default;
These are equivalent1, and will both end up assigning a new "all fields set to zero" value to myLunch
.
Also, ideally don't use mutable structs to start with - I typically prefer to create a struct which is immutable, but which has methods which return a new value with a particular field set differently, e.g.
ChocolateBar myLunch = new ChocolateBar().WithLength(100).WithGirth(10);
... and of course provide appropriate constructors as well:
ChocolateBar myLunch = new ChocolarBar(100, 10);
1 At least for structs declared in C#. Value types can have custom parameterless constructors in IL, but it's relatively hard to predict the circumstances in which the C# compiler will call that rather than just use the default "zero" value.
Just call the parameterless constructor in your code:
ChocolateBar chocolateBar = new ChocolateBar();
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