Answer the question
In order to leave comments, you need to log in
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!");
}
}
class Dog
{
void Say()
{
Console.WriteLine("Gav gav!");
}
}
Answer the question
In order to leave comments, you need to log in
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.
You can't store a cat, a dog, and other talking robots in one variable.
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.
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();
}
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);
}
// Можно использовать и для string[], и для List<string>, и даже для того, о чём мы ещё не знаем!
static void PrintAll(IEnumerable<string> collection) {
foreach(var e in collection) {
Console.WriteLine(e);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question