0

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;
    }
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
nostro
  • 13
  • 3

2 Answers2

3

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
    }
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
1

I'm trying to understand the intent of your question rather than your question, and I'm coming up a little short. However, I think I came up with something.

You can "mask" your mutable object under a read-only interface.

public class ClassWithMutable
{
    public IImumutable Mutable { get { return _mutable; } }
    private Mutable _mutable;
    public ClassWithMutable()
    {
        _mutable = new Mutable()
        {
            Value = 1
        };
    }
}
public interface IImumutable
{
    int Value { get; }
}
public class Mutable : IImumutable
{
    public int Value { get; set; }
}

As long as your ClassWithMutable instance exposes the Mutable instance as an Immutable then the consumer can't easily change it. (I emphasize easily, because there's pretty much always a way that you can change it. It just depends on how hard you want to work.)

Cameron
  • 2,574
  • 22
  • 37