Search code examples
c#interfacepropertiesinitialization

Is it possible to set an init-only explicit-implemented property?


Let's say we have a class, which must have only one parameterless constructor. The class also define a init-only setter property.

class MyClass
{
    public int MyProp { get; init; }
}

Since C# 9, we can set that property only at construction time:

MyClass c = new()
{
    MyProp = 123,
};

So far, so good.

Now, let's suppose that the property is required by an interface, and we need to implement explicitly that interface:

interface IFoo
{
    int MyProp { get; init; }
}

class MyClass : IFoo
{
    private int _myProp;

    int IFoo.MyProp
    {
        get => _myProp;
        init => _myProp = value;
    }
}

However, that won't compile:

MyClass c = new()
{
    MyProp = 123,
};

Also, I have no idea about any possible syntax.

Is there any way to achieve this?


Solution

  • From the documentation:

    An explicit interface implementation doesn't have an access modifier since it isn't accessible as a member of the type it's defined in. Instead, it's only accessible when called through an instance of the interface.

    To make your instantiation possible, you therefore need to implement the property as a non-explicit-implementation of the interface as well:

    class MyClass : IFoo
    {
        private int _myProp;
    
        int IFoo.MyProp
        {
            get => MyProp;
            init => MyProp = value;
        }
    
        public int MyProp
        {
            get => _myProp;
            init => _myProp = value;
        }
    }
    

    Of course, if you don't want IFoo.MyProp to use the non-explicit implementation as a "backing property" you can change that.