Search code examples
c#propertiesexplicit-interface

Interface property fails when defining explicitly


I'm learning about interface properties and ran into something that I thought should work based on MSDN and book examples, but it doesn't. If I implement the interface property explicitly, it's not recognized when my class instance tries to access, but works fine if I do it implicitly(not sure if that's the correct terminology).

interface IMyInterface
  {
    string Name { get; set; }       
  }

class MyClass : IMyInterface
{
    private string name;

    string IMyInterface.Name  //works if not explicit: i.e., public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}


class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        myClass.Name = "blah";  // fails

    }
}

Solution

  • This is how it is supposed to work with explicit interface implementations:

    A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

    So if you re-write your code like this, it should no longer fail:

    static void Main(string[] args)
    {
        IMyInterface myClass = new MyClass();
        myClass.Name = "blah";  // no longer fails
    }