tags:

views:

43

answers:

3

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  A: 

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.

SLaks
+5  A: 

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; }
Grant Crofton
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
Gabriel
Yeah, or even have a separate operator like they do in C++ (which I seem to remember was ->, e.g. `(IFoo)this->X`)
Grant Crofton
+2  A: 

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.

KeithS