Sobes.tech
Junior — Middle

Kas saaksite selgitada ühtseisva (part) tüübi põhimõtet ja kuidas seda programmeerimises rakendatakse?

sobes.tech AI

Vastus AI-lt

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 is a duck" reflects the essence: the type of the object is not important, but its behavior.

In C#, this is not an built-in mechanism like in dynamic languages, but it can be mimicked 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 the Quack method, otherwise a runtime error will occur.