I have an interface:
public interface Profile
{
string Name { get; }
string Alias { get; set; }
}
All objects that implement Profile
have a Name
and an Alias
, but some restrict Alias
such that it's always the same as Name
. The ones that apply this restriction can implement Alias
like this:
string Profile.Alias
{
get
{
return ((Profile)this).Name;
}
set { }
}
Since this
within the context of an explicit interface implementation can only possibly be of type Profile
and we know it was accessed through the Profile
interface rather than that of the containing class or any other interface it implements, why is the cast required?
Using return this.Name;
for the getter implementation results in this error:
Type `ConcreteProfile' does not contain a definition for `Name' and no extension method `Name' of type `ConcreteProfile' could be found (are you missing a using directive or an assembly reference?)
Since this within the context of an explicit interface implementation can only possibly be of type Profile and we know it was accessed through the Profile interface rather than that of the containing class or any other interface it implements, why is the cast required?
Because it uses explicit interface implementation. That's simply part of what explicit interface implementation does - and part of how it achieves its aim of disambiguating calls that would otherwise be ambiguous. From the C# 5 specification, section 13.4.1:
It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.
...
Explicit interface member implementations serve two primary purposes:
- Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.
- Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.
See more on this question at Stackoverflow