0
interface IThing
{
 int Property {get;}
 void Method();
}

class Thing : IThing
{
 int IThing.Property {get; } = 999;
 void IThing.Method() {Console.WriteLine($"Property = {Property}");}
}

This gives a compiler error "The name Property does not exist in the current context". Regardless if I refer to Property or IThing.Property or this.Property

Why does explicit interface implementation appear to 'shield' interface methods from each other? Is this a language feature or a syntax error on my part (I haven't used explicit interface implementations before and was testing it out to see).

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 1
    _"Why does explicit interface implementation appear to 'shield' interface methods from each other?"_ -- it doesn't. It just means that the object itself isn't considered to implement the members of the interface. Only a reference to the interface itself will expose those members. That is, after all, _exactly_ the whole point of using explicit interface implementations. See marked duplicate. – Peter Duniho Mar 24 '20 at 20:33
  • 2
    The whole point of an explicit interface implementation is that **it does not add the name of the method to the member set of the implementing type**. So you should not be surprised when *the name cannot be found*. – Eric Lippert Mar 24 '20 at 20:34
  • I would've expected the interface to know about its own members though. Anyway if that's the annwer, that's the answer :) – Mr. Boy Mar 24 '20 at 20:58
  • I don't understand what you mean by "the interface knows its own members". Are you expecting that the type of `this` is the type of the *interface*? If that were the case then the implementation could not call the members of the type containing the explicit method! – Eric Lippert Mar 25 '20 at 16:44
  • What I'm getting at here is that you seem to have some fundamentally wrong belief, and it would be great if we could figure out what that wrong belief is and replace it with a correct belief. Then you'd be more successful. – Eric Lippert Mar 25 '20 at 16:45

2 Answers2

6

You have to reference this as an instance of the interface. You can do that with casting.

Console.WriteLine($"Property = {((IThing)this).Property}");

See also Explicit Interface Implementation for more detail.

Igor
  • 60,821
  • 10
  • 100
  • 175
2

The reason you cannot access the property is because you have implemented the interface explicitly which means that you have to cast the class instance to the type of the interface. If you want to access the property without casting you have to implement the interface this way:

interface IThing
{
    int Property { get; }

    void Method();
}

class Thing : IThing
{
    public int Property { get; }

    public void Method() { Console.WriteLine($"Property = {Property}"); }
}
Iwan Uzunow
  • 21
  • 1
  • 3