How to Implement Two interfaces with Same Method Signature in C#

Опубликовано: 20 Август 2020
на канале: Brian Lagunas
4,587
181

In this video, I answer the question, "How to Implement Two interfaces with Same Method Signature in C#?".

It is very common to have a class that implement two interfaces which have the same method signature. Or maybe, you implement an interface that has the same method signature as a method on your class. Either way, the result is a conflict in the method implementations. By default, you can only have one unique method signature defined in a class. However, when working with interfaces you can use a special implementation of interfaces to get around that limitation.

Explicit implementation of interfaces allows you to provide unique implementations for for each interface method.

Explicit implementations of interfaces are actually used to solve two problems.
- Hide the implementation of an API from the public
- Resolve conflicting method signatures

Using an explicit interface implementation is as easy as changing the scope of the method to private, and appending the interface name to the method signature.

For example, consider this interface implementation

public interface IMyInterface
{
void DoSomething();
}

The class that implements the interface would look something like:

public class MyClass : IMyInterface
{
public void DoSomething() { ... }
}

To implement the interface explicitly use:

public class MyClass : IMyInterface
{
void IMyInterface.DoSomething() { ... }
}

Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
https://pluralsight.pxf.io/bE3rB

Sponsor Me:
https://github.com/sponsors/brianlagunas

Follow Me:
Twitter:   / brianlagunas  
Twitch:   / brianlagunas  
Blog: http://brianlagunas.com
GitHub: https://github.com/brianlagunas


Смотрите видео How to Implement Two interfaces with Same Method Signature in C# онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Brian Lagunas 20 Август 2020, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 4,58 раз и оно понравилось 18 людям.