Is there a quick way of zeroing a struct in C#?

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;
}
Jon Skeet
people
quotationmark

Just use:

myLunch = new ChocolateBar();

or

myLunch = default(ChocolateBar);

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.

people

See more on this question at Stackoverflow