Return an opaque object to the caller without violating type-safety

Posted by JS Bangs on Stack Overflow See other posts from Stack Overflow or by JS Bangs
Published on 2010-05-27T15:26:55Z Indexed on 2010/05/27 15:31 UTC
Read the original article Hit count: 150

Filed under:
|
|

I have a method which should return a snapshot of the current state, and another method which restores that state.

public class MachineModel
{
    public Snapshot CurrentSnapshot { get; }
    public void RestoreSnapshot (Snapshot saved) { /* etc */ };
}

The state Snapshot class should be completely opaque to the caller--no visible methods or properties--but its properties have to be visible within the MachineModel class. I could obviously do this by downcasting, i.e. have CurrentSnapshot return an object, and have RestoreSnapshot accept an object argument which it casts back to a Snapshot.

But forced casting like that makes me feel dirty. What's the best alternate design that allows me to be both type-safe and opaque?

© Stack Overflow or respective owner

Related posts about c#

Related posts about design