C# Anonymous methods Interview Question

Collection of typically Interview Questions on anonymous methods for interview preparation. you can also read more about anonymous methods. Alternatively, you can also test your knowledge by an online free quiz for anonymous methods.

Interview Question: What is Anonymous method?

Answer: Anonymous methods were introduced into C# 2 as a way of creating delegate instances without having to write a separate method. They can capture local variables within the enclosing method, making them a form of closure.

An anonymous method looks something like:

delegate (int x) { return x * 5; }

Interview Question: Anonymous method vs Named method?

Answer: A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to print message:

void MyMethod1()
{
  Console.WriteLine("In Method1");
}

Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don’t specify the name of the method.

For example,

(delegate) => { Console.WriteLine("Inside Mymethod");}

Interview Question: Why we cannot assign anonymous method which return int value to int variable?

int X= delegate(){return 25;};

Answer: Because delegate is not an integer, so we cannot simple assign delegate to int you have to define a delegate which return int and then you can assign that value to integer variable
Something like below

delegate int IntDelegate();
...
IntDelegate del=delegate(){return 25;};
int X=del();

Alternatively, If you use .Net 3.5 or newer you can use the built in Func instead of using a custom (Func also have generic types if you need arguments like Func which tages a string and return an int):

Func<int> X = delegate() { return 255; };

Interview Question: How to return value with anonymous method?

Answer: anonymous method return type is declare or define by assigned delegate,

for example:

public delegate int AdditionDelegate(int x, int y);
…
AdditionDelegate additionDelegate =
delegate (int a, int b)
{
    return a + b + addToAddition;
};

Return type of the above anonymous method is int as defined by delegate.


Interview Question: How to make inline functions in C#?

Answer: There are several syntax’s available.

Anonymous methods were added in C# 2.0:

Func<int, int, int> add = delegate(int x, int y)
{
    return x + y;
};
Action<int> print = delegate(int x)
{
    Console.WriteLine(x);
}
Action<int> helloWorld = delegate // parameters can be elided if ignored
{
    Console.WriteLine("Hello world!");
}

Lambdas are new in C# 3.0 and come in two flavours.

Expression lambdas:

Func<int, int, int> add = (int x, int y) => x + y; // or...
Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
Statement lambdas:

Action<int> print = (int x) => { Console.WriteLine(x); };
Action<int> print = x => { Console.WriteLine(x); }; // inferred types
Func<int, int, int> add = (x, y) => { return x + y; };
Local functions have been introduced with C# 7.0:

int add(int x, int y) => x + y;
void print(int x) { Console.WriteLine(x); }

Interview Question: Can an anonymous method in C# call itself?

Answer: Programmatically yes, anonymous method can call itself below is the syntax:

myDelegate build = null;
build = delegate (Object bj)
{
    var letters = string.Empty;
    if (someCondition)
        return build(some_obj);
    else string.Empty;
};

But I would recommend avoiding anonymous delegates. Just create a method and have it call itself recursively.

Anonymous methods are meant to be anonymous – you shouldn’t be calling them by name (non-anonymously).


Interview Question: What’s is difference between anonymous methods and lambda expression?

Answer: In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list, and this means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read “x goes to x times x.” This expression can be assigned to a delegate type.

  • Lambda expressions can be converted to delegates or expression trees (with some restrictions); anonymous methods can only be converted to delegates
  • Lambda expressions allow type inference on parameters:
  • Lambda expressions allow the body to be truncated to just an expression (to return a value) or single statement (in other cases) without braces.
  • Lambda expressions allow the parameter list to be shortened to just the parameter name when the type can be inferred and when there’s only a single parameter
  • Anonymous methods allow the parameter list to be omitted entirely when it’s not used within the body and it doesn’t lead to ambiguity

you can also read more about anonymous methods. Alternatively, you can also test your knowledge by an online free quiz for anonymous methods.

Leave a Reply

Your email address will not be published. Required fields are marked *