tags:

views:

87

answers:

1

If my interface has the signature only for getter such as:

public interface IInterface 
{
   object Id{get;}
}

So the interface only dictates a public getter for Id on any implemented class now when i have the class :

public class Simple : IInterface
{
  object Id
  {
    get{return something;} 
    set{ do something else;}
  }
}

the compiler complains about the setter as the setter is not defined in the interface. However I didnt dictate anything on the interface contract for a setter; why does the interface insist on the setter on the derived classes ?

+9  A: 

You just need to make Id public. For example, this compiles fine:

public interface IInterface
{
    object Id { get; }
}
public class Simple : IInterface
{
    private int something;
    public object Id
    {
        get { return something; }
        set{ something = (int)value;}
    }
}
Reed Copsey
When i declare the Id as explicit declaration I cant use public , do you know why?
VolkanUzun
Yes. Explicit declarations are different - they are inherently public but ONLY when used as the interface itself (interfaces are always public). However, an explicit implementation will not allow the setter, since the interface (which is what you'd be using) will only have a getter on the property.
Reed Copsey
but then again, why does the interface care about the setter? I see that the way interface interprets the code is: there is only a getter so it should be readonly; but cant you also interpret is as: i only care that there should be a getter; that is the contract; i dont care about the setter
VolkanUzun
It doesn't care - but if you define it explicitly, you're defining the access "for use only as an IInterface", which IInterface "explicitly" does NOT have a setter. It makes no sense to have a setter there, so the compiler complains.
Reed Copsey