Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any reason why an interface reference would be included before a method name on an implementing class? [duplicate]

Tags:

c#

.net

Is there any reason why an interface reference would be included before a method name on an implementing class? For example, let's say you have a ReportService : IReportService and a GetReport(int reportId) method. I was reviewing some code and another developer implemented the method like this in ReportService:

Report IReportService.GetReport(int reportId)
{
  //implementation
}

I've never seen a service implementation like this before. Does it serve any purpose?

like image 334
user7242966 Avatar asked Dec 30 '16 18:12

user7242966


1 Answers

This is called "explicit interface implementation". The reason for this may for example be a naming conflict.

Consider the interfaces IEnumerable and IEnumerable<T>. One declares a non-generic method

IEnumerator GetEnumerator();

and the other a generic one:

IEnumerator<T> GetEnumerator();

In C# it's not allowed to have two methods with the same name that only differ in there return type. So if you implement both interfaces, you need to declare one method explicit:

public class MyEnumerable<T> : IEnumerable, IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    { 
        ... // return an enumerator 
    }

    // Note: no access modifiers allowed for explicit declaration
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // call the generic method
    }
}

Explicitly implemented interface methods cannot be called on instance variables:

MyEnumerable<int> test = new MyEnumerable<int>();
var enumerator = test.GetEnumerator(); // will always call the generic method.

If you want to call the non-generic method, you'd need to cast test to IEnumerable:

((IEnumerable)test).GetEnumerator(); // calls the non-generic method

That also seems to be the reason why there are no access modifiers (like public or private) are allowed on explicit implementations: it's not visible on the type anyway.

like image 184
René Vogt Avatar answered Oct 27 '22 01:10

René Vogt