2

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?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Troskyvs
  • 7,537
  • 7
  • 47
  • 115

1 Answers1

8

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;
René Vogt
  • 43,056
  • 14
  • 77
  • 99