Search code examples
c#interfaceprivate

C# public only for classes of the same interface


Can I make some properties public only to same interface classes and readonly to all other classes?


Solution

  • You can use explicit implementation, for example:

    interface IFoo {
        int Value { get; set; }
    }
    
    public class Foo : IFoo {
        public int Value { get; private set; }
    
        int IFoo.Value {
            get { return Value; }
            set { Value = value; }
        }
    }
    

    When accessed via Foo only the get will be accessible; when accessed via IFoo both getter and setter will be accessible.

    Any use?