Search code examples
c#immutabilitymutable

Any way to make a mutable object derived from an immutable object in C#?


I'm interested in making an immutable class that has properties that cannot be modified, and a mutable class that derives from it. These objects would be simple data objects representing database records, so they would have only immutable values for the properties.

My goal is to have my data access layer create the mutable versions of the objects normally, by setting the properties based on the database values, but passing readonly versions of these objects back to the application. (I'm ok with the fact that the code could explicitly cast the immutable object back into a mutable one if the developer really wanted to.)

I can do this uglily (is that a word?), using methods for getters and setters and having a public new setter for the mutable class:

public class ImmutableClient {
    private int _clientId;
    public int getClientId() { return _clientId; }
    protected void setClientId(int clientId) { _clientId = clientId; }
}

public class Client : ImmutableClient {
    public new void setClientId(int clientId) { base.setClientId(clientId); }
}

I'd prefer to use auto-properties if possible - they're much nicer when debugging. Other than that, I don't really care how the code looks, since it's just going to all come from a code generator and never be looked at.

Any ideas?


Solution

  • I would use an interface. Have a read only interface that is returned to the client and a fully writeable class that implements it but is only used in the data access layer.

    interface IReadOnlyObject
    {
        int Property { get; }
    }
    
    class DALObject : IReadOnlyObject
    {
        public int Property { get; set; }
    }