Sobes.tech
Junior — Middle

Can you explain what an anonymous method is and how it is used in programming?

sobes.tech AI

Answer from AI

Anonymous method is a function (delegate) that has no name and is usually defined directly at the point of use. In programming, they are often used to pass code as a parameter, for example, in delegates or event handlers.

In C#, anonymous methods appeared before lambda expressions and have the following syntax:

delegate void Print(string message);

Print print = delegate(string msg) {
    Console.WriteLine(msg);
};

print("Hello");

Here, delegate(string msg) { ... } is an anonymous method without a name, which can be assigned to a delegate.

Anonymous methods are useful when you need to define a short function on the spot without creating a separate named method.