Search code examples
c#inheritanceinterfaceencapsulation

How to hide set method of an implemented property from an interface in C#?


Greetings everyone...

If I have the following interface:

interface IMyInterface
{
    int property { get; set; }
}

And the following implementation:

class MyClass : IMyInterface
{
// anything
}

How can I hide the set method of property from the instances of MyClass... In other words, I don't want the set method of property to be public, is that possible?

It would be easy to do with abstract class:

abstract class IMyInterface
{
    int property { get; protected set; }
}

Then I could only set the property within the class that implements the abstract class above...


Solution

  • If you use the following interface the set method will be unavailable when classes are manipulated via the interface:

    interface IMyInterface
    { 
       int property { get; }
    }
    

    You could then implement the class like this:

    class MyClass : IMyInterface
    {
      int property { get; protected set; }
    }