Setter for property not defined in interface

If my interface has a getter-only signature like:

public interface IInterface 
{
   object Id{get;}
}

      

This way the interface only dictates the public getter for Id in any implemented class now that I have the class:

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

      

the compiler is complaining about the installer because the installer is not defined in the interface. However, I did not dictate anything in the interface contract for the setter; why does interface insist on customizer on derived classes?

+2


source to share


2 answers


You just need to make the 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;}
    }
}

      

+11


source


When developing .net, Microsoft decided to create three non-interchangeable property types: read-only, write-only, and read-write. In C #, if you declare a read-write property with the same name as one or more interface properties to be implemented, the compiler can automatically create not only the read-write property that the programmer actually specified, but also read-only and / or write properties just to suit the interfaces. For example, if the IReadableFoo interface implements the Foo read-only property, IWritableFoo implements the Foo write property, and IReadWriteFoo inherits IReadableFoo and IWritablefoo and implements the "new" read-write property Foo, and the ReadWriteFoo class implements IReadWriteFoo and declares the public read-write propertythe compiler will have ReadWriteFoo generate interface implementations of the read-only property IReadableFoo.Foo, the write-only property IWritableFoo.Foo, and the write-write property IReadWriteFoo.Foo.



+1


source







All Articles