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

Viewed 6112

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;
}
6 Answers

You can modify your struct in this way:

struct ChocolateBar {
    int length;
    int girth;
    public void Clear()
    {
        this = new ChocolateBar();
    }
}

and use it in your code easily:

ChocolateBar cb = new ChocolateBar();
//some stuff here
cb.Clear();
Related