U
U
Uncle Bogdan2020-12-08 16:46:57
OOP
Uncle Bogdan, 2020-12-08 16:46:57

Why do we need an interface if we can create functions?

What's the real difference? (Applies to abstract classes as well)
Like you write:
with an interface:

class Dog : IAnimal
    {
        void IAnimal.Say()
        {
            Console.WriteLine("Gav gav!");
        }
    }


Without interface:
class Dog
    {
        void Say()
        {
            Console.WriteLine("Gav gav!");
        }
    }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
DevMan, 2020-12-08
@motkot

An interface guarantees that the methods described in it are implemented in the class.
smoke the topic of interfaces in general, and the OOP tag on the toaster in particular - this question has been asked 100 times already.

F
freeExec, 2020-12-08
@freeExec

You can't store a cat, a dog, and other talking robots in one variable.

D
Denis Zagaevsky, 2020-12-08
@zagayevskiy

An interface is a tool for abstraction. There is no abstraction in your example, moreover, it is bad simply because no one builds an animal-cat/dog hierarchy. This is meaningless, and very quickly you will be buried in a fish, which, as it were, is also an animal, but say is not applicable to it.
Make the interface ISpeakeable - that is, able to speak. Make a method that accepts this interface, and you will understand why it is good.

V
Vasily Bannikov, 2020-12-08
@vabka

As far as animals are concerned.
With interfaces, you can do this:

interface ISpeaking {
  public void Speak();
}

public class Dog: ISpeaking {
  public void Speak() => Console.WriteLine("Гав!");
}

public class Cat: ISpeaking {
  public void Speak() => Console.WriteLine("Мяу!");
}

public static void Main() {
 ISpeaking[] speakers = new ISpeaking[] {new Cat(), new Dog()};
 foreach(ISpeaking speaker in speakers)
   speaker.Speak();
}

A more applicable example is the IEnumerable interface.
IEnumerable implement different collections: arrays, List, HashSet, Dictionary.
With IEnumerable, you can iterate through all the elements of a collection. This allows you to get rid of code duplication:
Without interfaces:
static void PrintAll(string[] array) {
  foreach(var e in array)
    Console.WriteLine(e);
}

static void PrintAll(List<string> list) {
  foreach(var e in list) { // Дублирование!
    Console.WriteLine(e);
}

With interface:
// Можно использовать и для string[], и для List<string>, и даже для того, о чём мы ещё не знаем!
static void PrintAll(IEnumerable<string> collection) {
  foreach(var e in collection) {
    Console.WriteLine(e);
  }
}

Interfaces are one way to achieve polymorphism.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question