Search code examples
c#constructorinitializationexplicit-interface

Is there a way to initialize EII property within constructor?


Let's start with code from MS page:

interface ILeft
{
    int P { get;}
}
interface IRight
{
    int P();
}

class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get { return 0; } }
}

I would like to change Middle in such way, the EII property is once initialized, something like this:

class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get; }

    Middle()
    {
        ILeft.P = 0;    
    }
}

Above code does not compile, thus my question -- is there a syntax for doing this?

I am asking about syntax, because brute force way would be to declare private field and redirect ILeft.P getter to return data from it.


Solution

  • I think the only other possibility besides your suggested approach of using a backing field rather than an auto-property is to use the property initializer syntax, e.g.:

    int ILeft.P { get; } = 0;
    

    Of course with this you can't initialize based on, say, an argument passed to the constructor, so it provides only limited additional flexibility.

    (There is a proposal to add "primary constructors" to the C# language, which might make it possible to initialize a get-only explicitly implemented interface property based on a constructor argument, though as far as I know there's no timeline for its inclusion in the language so I wouldn't hold your breath...)