Can you explain the principle of duck typing and how it is applied in programming?
sobes.tech AI
Answer from AI
Duck typing is a programming concept where the type of an object is determined not by its class or inheritance, but by the presence of certain methods and properties.
The phrase "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck" reflects the essence: what matters is not the type of the object, but its behavior.
In C#, this is not a built-in mechanism like in dynamic languages, but it can be simulated through interfaces or dynamic typing (dynamic). For example, if an object implements the necessary methods, it can be used without strict type checking.
Example with dynamic:
void MakeItQuack(dynamic duck) {
duck.Quack();
}
class Duck {
public void Quack() {
Console.WriteLine("Quack!");
}
}
MakeItQuack(new Duck());
Here, it is important that the passed object has a Quack method, otherwise a runtime error will occur.