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; }
}
Because you’ve implemented your interface explicitly (by writing
string IFoo.Xinstead of juststring X), you can only access that interface property via the interface.So you’d need to do
Or not declare the interface explicitly, i.e.