c# struct weird behavior

Viewed 57

Found some weird behevior with c# struct and using statement. Not sure why this is happening. Sample struct:

public struct Thing : IDisposable {
    private bool _dispose;

    public void Dispose() {
        _dispose = true;
    }
    public bool GetDispose() {
        return _dispose;
    }
    public void SetDispose(bool dispose) {
        _dispose = dispose;
    }
}

And usage of this struct:

        var thing = new Thing();
        using (thing) {
            Console.WriteLine(thing.GetDispose());
        }
        Console.WriteLine(thing.GetDispose());

I expect here to see the following output:

False
True

Because Dispose() method is called at the end of using scope. But I get:

False
False

If I change struct to class, or use struct and add thing.SetDispose(true); inside using scope, I get expected output

False
True

My question is why do I get False False with a struct? I checked with debugger, Dispose() is called every time at the end of using scope.

1 Answers

The structs are value types, so in this piece of code, the original struct will be copied to a new one inside using statement.

Your code at the end will be translated to:

var thing = new Thing();                     //thing._dispose == false
using (Thing thing2 = thing) {               //thing2.dispose == false   
     Console.WriteLine(thing2.GetDispose()); //thing2.dispose == false
}                                            //thing2.dispose == true
                                             //BUT thing1.dispose == false
Console.WriteLine(thing.GetDispose());

You can read more here: https://ericlippert.com/2011/03/14/to-box-or-not-to-box/

Related