S
S
splunk2016-02-25 02:59:46
.NET
splunk, 2016-02-25 02:59:46

C#. Where can an explicit implementation of an interface be useful?

I read how to do it, but did not understand where and why to use

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
V Sh., 2016-02-25
@JuniorNoobie

Well, suppose you have two interfaces (IDollar and IEuro) that describe a method with the same name (getPrice). If you happen to have a class (Car) that will implement these interfaces, then for correct operation, namely, to return the price in dollars and euros, you must explicitly implement both interface methods in the class and call it like this:
(IEuro) car.getPrice() - price in euros
(IDollar)car.getPrice() - price in dollars

M
Michael, 2016-02-25
@Sing303

It briefly describes why interfaces are needed
sergeyteplyakov.blogspot.ru/2014/12/what-are-inter...

A
Alexey Pavlov, 2016-02-25
@lexxpavlov

I sometimes make a class both a regular method and an explicitly implemented one with the same name, for convenience.
For example, sometimes you need a comparer as an object with a method, and sometimes you don't need an object, and then you can call a static method.

public class NaturalComparer : IComparer<string>
{
  [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
  private static extern int StrCmpLogicalW(string psz1, string psz2);

  public static int Compare(string x, string y)
  {
    return StrCmpLogicalW(x, y);
  }

  int IComparer<string>.Compare(string x, string y)
  {
    return StrCmpLogicalW(x, y);
  }
}

public class TestApp
{
  public static void Main()
  {
    // Используем явную реализацию
    var arr = new [] { "a5", "a1", "a10", "a3", "a7" };
    Array.Sort(arr); // a1, a10, a3, a5, a7
    Array.Sort(arr, new NaturalComparer()); // a1, a3, a5, a7, a10

    // Используем статический метод
    var list = new List<string> { "a5", "a1", "a10", "a3", "a7" };
    const string max = "a4";
    var minElements1 = list.Where(s => s.CompareTo(max) < 0).ToList(); // a1, a10, a3
    var minElements2 = list.Where(s => NaturalComparer.Compare(s, max) < 0).ToList(); // a1, a3
  }
}

V
Valery Abakumov, 2016-03-03
@Valeriy1991

Good afternoon! Interfaces (like abstract classes) allow (architecturally speaking) you to develop loosely coupled applications. This, in turn, leads to the fact that: 1) it becomes easier to make changes to the code; 2) the application does not depend on specific implementations, but depends on abstractions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question