Search code examples
c#interfaceexplicit-interface

Why do I need to cast 'this' to interface type in a C# explicit implementation?


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?)

Solution

  • Since this within the context of an explicit interface implementation can only possibly be of type Profile

    This is not true. You are implementing Profile.Alias inside the ConcreteProfile class. In this context, this refers to the ConcreteProfile instance and can be used to access any member of the ConcreteProfile instance.

    For example, the ConcreteProfile class can contain another Name property that is not Profile.Name. In this case this.Name would refer to that property.

    Since you want to access Profile.Name, you have to cast this to Profile.