0

In some locations of my program I need access to the concrete implementation of an object (Test) and in other locations I only need a read-only interface (ITest). This is to prevent an user from assuming that all properties are set and modifiable

For example if the user calls TestFactory.Search the returned collection will prevent them from modifying the property A and using CollectionB (it is not set inside the function). I would like to be able to use object initializers and keep the properties names the same. I have the following solution:

public interface IReadOnly
{
    int Id{ get; }
    string Name{ get; }
}

public class ClassA : IReadOnly
{
    int Id{ get; internal set; }
    string Name{ get; set; }
}

public interface ITest
{
    int Id{ get; }
    IReadOnly A { get; }
}

public class Test : ITest
{
    private ClassA classA = new ClassA();

    int Id{ get; internal set; }
    IReadOnly ITest.A{ get{ return classA; } }
    public ClassA A
    { 
        get
        { 
            return classA;
        }  
        set
        {
             classA = value;
        }
    }

    public IEnumerable<string> CollectionB {get;set;}
}

public static class TestFactory
{
    IEnumerable<ITest> Search(){ /**/ }
    Test Read(){ /**/ };
}

Is there a better way to solve this problem and is the abusing the concept of explicit interface implementation?

1
  • Let Test class implement IReadOnly as well and then just use test as IReadOnly o test Commented Oct 18, 2011 at 16:00

2 Answers 2

1

I would have your Test class implement both interfaces, IReadOnly and ITest. When you want to restrict setter access, cast to IReadOnly, otherwise, use ITest or the concrete Test.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe create an abstract class instead and then subclass the full access and read only behavior?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.