2

I started with this:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
    }
    string IFoo.X { get; set; }
}

It compiled as I was expecting. No surprise.

Then I go to this:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        X = "";
    }
    string IFoo.X { get; set; }
}

Now I get 'X is not available in the current context'.

Wasn't expecting that.

I end up with:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        X = "";
    }
    private string X;
    string IFoo.X { get; set; }
}

And I never would have thought of that.

Question: The above code in not meshing with my current understanding of thigns because I see two X's. On an intuitive level I can see the compiler doesn't need to get confused. Can someone put it in their words the rules of the language at play here?

Thanks in advance.

Update after answer: I could have casted to the interface as below:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        (IFoo(this)).X = "";
    }
    string IFoo.X { get; set; }
}

3 Answers 3

5

Because you've implemented your interface explicitly (by writing string IFoo.X instead of just string X), you can only access that interface property via the interface.

So you'd need to do

public void F()
{
    ((IFoo)this).X = "";
}

Or not declare the interface explicitly, i.e.

public string X { get; set; }
2
  • 1
    I've always felt it a bummer that '.' keeps it's high precedence in this particular case, it would be nice to just go (IFoo)this.X Oct 22, 2010 at 15:15
  • Yeah, or even have a separate operator like they do in C++ (which I seem to remember was ->, e.g. (IFoo)this->X) Oct 22, 2010 at 16:02
3

An explicit interface implementation is not a regular named member of the class, and cannot be accessed by name on the class type (unless you cast it to the interface)

See the spec.

2

Your explicit implementation of IFoo.X basically limits the use of IFoo.X to cases where the instance of C is treated as an IFoo. If you remove the explicit implementation, you'll get a property X that satisfies the IFoo interface, and can be used when treating the class as a C as well as an IFoo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.