Reputation: 371
I have an interface which has a property like this:
public interface IMyInterface
{
IGenericThing MyProperty { get; set; }
}
I implement that interface in a specific class that uses a generic type, but in that class, I want to use a specific implementation of IGenericThing, like this:
public abstract class MySpecificClass<T> : IMyInterface
where T : IGenericThing
{
IGenericThing IMyInterface.MyProperty
{
get { return myProperty; }
set
{
if (value is T)
{
MyProperty = (T)value;
}
}
}
protected T myProperty;
public T MyProperty
{
get { return myProperty; }
set
{
myProperty = value;
//...other setter stuff
}
}
}
This all works, which is awesome. It lets me access MyProperty when I have a reference to an object through IMyInterface, and access more specific information about MyProperty when I know it's an instance of MySpecificClass.
What I don't really understand is what this is called or what the compiler is doing to let this happen. I tried searching for this, but since I don't know what it's called, couldn't find anything.
Can anybody please explain what is going on here so that I can understand this better?
Upvotes: 0
Views: 25
Reputation: 68400
That's called explicit interface implementation
if a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
It's not exactly your case but here you have a classic usage for it
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
Upvotes: 1