Search code examples
c#interfaceautomatic-properties

How can an auto-implemented property having different access levels be described by an interface?


This class property is what I'm trying to refactor into an interface.

public class Stuff : IStuff {
    public int Number {
        get;
        protected internal set;
    }
}

Visual Studio 2008 refactoring tools extract the following interface

// Visual Studio 2008's attempt is:
public interface IStuff {
    int Number { get; }
}

The C# compiler complains with the error:

'Stuff.Number.set' adds an accessor not found in interface member 'IStuff.DataOperations'

(This is one of the few circumstances I have run into where Visual Studio generates code that causes an improper compile situation.)

Is there a direct solution to extract this one property into an interface without making distinct set and get members/methods on the class?


Solution

  • I tested with the following:

    class bla : Ibla {
        public int Blargh { get; protected internal set; }
    }
    
    interface Ibla {
        int Blargh { get; }
    }
    

    and it works just fine. Did you implement the interface correctly?