Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit implementation of an interface using an automatic property

Is there any way to implement an interface explicitly using an automatic property? For instance, consider this code:

namespace AutoProperties
{
    interface IMyInterface
    {
        bool MyBoolOnlyGet { get; }
    }

    class MyClass : IMyInterface
    {
        static void Main(){}

        public bool MyBoolOnlyGet { get; private set; } // line 1
        //bool IMyInterface.MyBoolOnlyGet { get; private set; } // line 2
    }
}

This code compiles. However, if you replace line 1 with line 2 it does not compile.

(It's not that I need to get line 2 working - I'm just curious.)

like image 348
user181813 Avatar asked Oct 11 '10 09:10

user181813


People also ask

What is implicit interface implementation?

An implicit interface implementation is where you have a method with the same signature of the interface. An explicit interface implementation is where you explicitly declare which interface the method belongs to.

Which of the following is used for correct implementation of an interface in C# net?

Which statement correctly defines Interfaces in C#.NET? Explanation: Leaving all options only option 'a' is correct as interfaces can be inherited i.e inheritance can be performed in csharp . net.

Can we use property in interface C#?

In C#, an interface can be defined using the interface keyword. An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties.

Can we declare property in interface?

No, we can't declare variables, constructors, properties, and methods in the interface. no,interface cannot contains fields.


1 Answers

Indeed, that particular arrangement (explicit implementation of a get-only interface property by an automatically implemented property) isn't supported by the language. So either do it manually (with a field), or write a private auto-implemented prop, and proxy to it. But to be honest, by the time you've done that you might as well have used a field...

private bool MyBool { get;set;}
bool IMyInterface.MyBoolOnlyGet { get {return MyBool;} }

or:

private bool myBool;
bool IMyInterface.MyBoolOnlyGet { get {return myBool;} }
like image 140
Marc Gravell Avatar answered Sep 23 '22 00:09

Marc Gravell