Stefanos Kargas
Stefanos Kargas

Reputation: 11093

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?

Upvotes: 1

Views: 88

Answers (2)

pescolino
pescolino

Reputation: 3133

An interface is just something like a contract for classes. It doesn't change the accessibility level.

If a member of a class is public it is public to all classes that can access the class. The only restrictions you can have is the use of internal or protected. internal makes the member public to classes which are defined within the same assembly and protected makes it public to classes derived from the class.

Instead of the interface you can create an abstract base class and make the members protected:

public interface IFoo
{
    int Value { get; set; }
}

public abstract class FooBase : IFoo
{
    public abstract int Value { get; set; }

    protected void ProtectedMethod()
    {
    }
}

public class Foo : FooBase
{
    public int Value { get; set; }
}

However you can not define a member that is accessible by classes that implement a specific interface. There is no access modifier like public-to-IFoo-otherwise-private.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

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?

Upvotes: 6

Related Questions