Search code examples
c#.netidisposableusing

Struct and IDisposable


I wonder why does it not compile?

public static void Main(string[] args)
{
    using (MyStruct sss = new MyStruct())
    {

        sss.s = "fsdfd";// Cannot modify members of 'sss' because it is a 'using variable' 

        //sss.Set(12);    //but it's ok
    }
}

public struct MyStruct : IDisposable
{
    public int n;
    public string s;

    public void Set(int n)
    {
        this.n = n;
    }
    public void Dispose()
    {
        Console.WriteLine("dispose");
    }
}

UPDATE: But it works perfect. Why?

public static void Main(string[] args)
        {

            using (MyClass sss = new MyClass())
            {
                sss.Field = "fsdfd"; 
            }


        }

public class MyClass:IDisposable {

    public string Property1 { get; set; }
    public string Field;
    public void Method1 (){}

    public void Dispose()
    {
        Console.WriteLine("dispose class");
    }
 }

Solution

  • The class and struct scenarios are actually the same but you see different effects.

    When you change the class example to :

    using (MyClass sss = new MyClass())
    {
        sss = null;          // the same error
        sss.Field = "fsdfd"; // ok
    }
    

    You will get the same error on the first assignment.

    The explanation is: You cannot change (mutate) the using-variable. But for a class that applies to the reference, not to the instance.

    And the lesson is: Don't use structs. And especially don't use mutable structs.