Reputation: 17186
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; }
}
Upvotes: 2
Views: 85
Reputation: 71573
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.
Upvotes: 2
Reputation: 9101
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; }
Upvotes: 5