Is modifying a value type from within a using statement undefined behavior?

后端 未结 4 984
予麋鹿
予麋鹿 2021-02-08 07:08

This one\'s really an offshoot of this question, but I think it deserves its own answer.

According to section 15.13 of the ECMA-334 (on the using statement,

4条回答
  •  [愿得一人]
    2021-02-08 07:50

    To sum it up

    struct Mutable : IDisposable
    {
        public int Field;
        public void SetField( int value ) { Field = value; }
        public void Dispose() { }
    }
    
    
    class Program
    
    {
        protected static readonly Mutable xxx = new Mutable();
    
        static void Main( string[] args )
        {
            //not allowed by compiler
            //xxx.Field = 10;
    
            xxx.SetField( 10 );
    
            //prints out 0 !!!! <--- I do think that this is pretty bad
            System.Console.Out.WriteLine( xxx.Field );
    
            using ( var m = new Mutable() )
            {
                // This results in a compiler error.
                //m.Field = 10;
                m.SetField( 10 );
    
                //This prints out 10 !!!
                System.Console.Out.WriteLine( m.Field );
            }
    
    
    
            System.Console.In.ReadLine();
        }
    

    So in contrast to what I wrote above, I would recommend to NOT use a function to modify a struct within a using block. This seems wo work, but may stop to work in the future.

    Mario

提交回复
热议问题