Search code examples
c#interfacepropertiescompilationexplicit

How to set property of explicitly implemented interface?


I've this code snippet:

public interface Imy
{
    int X { get; set; }
}

public class MyImpl : Imy
{
    private int _x;
    int Imy.X
    {
        get => _x;
        set => _x = value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var o = new MyImpl();
        o.Imy.X = 3;//error
        o.X = 3;//error
    }
}

I just wish to assign value to X, but get 2 compilation errors. How to fix it?


Solution

  • When you implement the interface explicitly, you need to cast the variable to the interface:

    ((Imy)o).X = 3;
    

    o is of type MyImpl in your code. You need to cast it to Imy explicitly to use the interface properties.


    Alternativly, you could declare o as Imy:

    Imy o = new MyImpl();
    o.X = 3;