Sobes.tech
Junior — Middle

Can you explain the concept of duck typing and how it is applied in dynamic programming languages?

sobes.tech AI

Answer from AI

Duck typing is a concept in dynamic programming languages where the type of an object is determined not by its class or inheritance hierarchy, 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: if an object supports the required interface (methods), it can be used as the desired type.

In C#, this is not typical because the language is statically typed, but with the advent of the dynamic type (dynamic), duck typing can be applied:

void MakeItQuack(dynamic obj) {
    obj.Quack(); // Compilation will succeed, but an error will occur at runtime if the method does not exist
}

class Duck {
    public void Quack() { Console.WriteLine("Quack!"); }
}

MakeItQuack(new Duck());

Thus, duck typing allows writing more flexible code that does not depend on specific types, but only on the presence of the required methods.