Search code examples
c#mutableautomatic-properties

Auto-properties with mutable objects


I'm trying to make properties for mutable objects. Is this a problem with Auto-properties? For example, the following code would allow for unwanted manipulation of the mutable object. How would I avoid this?

public class Mutable{
    public int Value { get; set; }
}

public class ClassWithMutable{
    public Mutable Object { get; }

    public ClassWithMutable(){
        this.mutable = new Mutable();
        this.mutable.Value = 0;
    }
}

public class Demo{
    public static void Main(String[] args){
        ClassWithMutable test = new ClassWithMutable();
        Mutable o = test.Object;
        o.Value = 1;
    }
}

Solution

  • You could use an interface that only exposes the get of the properties, and a private class that implements it.

    public interface IImmutable {
        int Value { get; }
    }
    
    public class ClassWithImmutable{
    
        private Mutable _object;        
        public IImmutable Object { get { return _object; } }
    
        public ClassWithImmutable(){
            this._object = new Mutable();
            this._object.Value = 0;
        }
    
        private class Mutable : IImmutable {
            public int Value { get; set; }
        }
    
    }
    
    public class Demo{
        public static void Main(String[] args){
            ClassWithImmutable test = new ClassWithImmutable();
            IImmutable o = test.Object;
            o.Value = 1;    // fails
        }
    }