2

This is a surprise to me! When I was seeing a code of someone, I just noted this line (shortened version!)

interface IPrint
{
   void PrintDateTimeNow();
}

class DatePrint : IPrint
{
    void IPrint.PrintDateTimeNow()
    {
        throw new NotImplementedException();
    } 

    public PrintDateTimeNow()
    {
        throw new NotImplementedException();
    } 
}

I tried to invoke this method and the function "PrintDateTimeNow()" is being called.

        var obj = new DatePrint();
        obj.PrintDateTimeNow();

That means, what is the purpose of the method IPrint.PrintDateTimeNow() ?

How to invoke IPrint.PrintDateTimeNow() ?

Why does the compiler allow an another method with the same name ?

4 Answers4

3

IPrint.PrintDateTimeNow() is a so-called explicit interface definition, as opposed to an implicit interface definition. You will find an elaborate answer to your question at C# Interfaces. Implicit implementation versus Explicit implementation

// This will call the implicit implementation
var obj = new DatePrint(); // same as DatePrint obj = new DatePrint();
obj.PrintDateTimeNow();

// This will call the explicit implementation
IPrint obj = new DatePrint();
obj.PrintDateTimeNow();

If for some reason you wanted the two cases to behave differently, you'd need both the explicit and implicit definition. If they should behave the same, the explicit definition is redundant and can probably be dumped.

Personally, I'd never add them prematurely just in case thy might be necessary at some time in the future. I'd consider that to be a violation of the YAGNI principle.

Community
  • 1
  • 1
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
1

It is called explicit interface implementation... please read the MSDN on that specific topic!

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.

1

IPrint.PrintDateTimeNow()is an explicit interface implementation. You need to cast obj to IPrint in order to call IPrint.PrintDateTimeNow():

((IPrint)obj).PrintDateTimeNow();

This can be helpful if your class implements mutliple interfaces that declare the same members (or members with the same name)

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
1

The explicit implementation will only be called when you access obj like this:

IPrint obj = new DatePrint();
obj.PrintDateTimeNow();
Noich
  • 14,631
  • 15
  • 62
  • 90