C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 36

What are anonymous methods and lambda expressions in C#?

Answer:

Anonymous methods and lambda expressions in C# are both techniques used to define inline, unnamed methods. These features allow you to write concise and readable code, especially when dealing with delegates, LINQ queries, and event handling. They provide a way to create short-lived methods without the need for a formal method declaration.

Anonymous Methods

Anonymous methods provide a way to define an inline method without a name, using the delegate keyword. They were introduced in C# 2.0 and are often used in conjunction with delegates.

Syntax:

delegate (parameter_list)
{
    // Method body
};

Example:

using System;

public class Program
{
    public delegate void PrintDelegate(string message);

    public static void Main()
    {
        // Defining an anonymous method
        PrintDelegate print = delegate (string message)
        {
            Console.WriteLine(message);
        };

        // Using the anonymous method
        print("Hello, World!");
    }
}

Lambda Expressions

Lambda expressions are a more concise way to write anonymous methods, introduced in C# 3.0. They use the => syntax and are often used in LINQ queries and other functional programming scenarios.

Syntax:

(parameters) => expression;
(parameters) => { statements; };

Example:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public delegate void PrintDelegate(string message);

    public static void Main()
    {
        // Defining a lambda expression
        PrintDelegate print = (message) => Console.WriteLine(message);

        // Using the lambda expression
        print("Hello, World!");

        // Lambda expression in a LINQ query
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

Key Features of Lambda Expressions

  1. Concise Syntax:

    • Lambda expressions provide a shorter and more readable syntax compared to anonymous methods.
  2. Implicit Typing:

    • The types of the parameters in lambda expressions are often inferred by the compiler, reducing verbosity.
  3. Expression and Statement Lambdas:

    • Expression lambdas: Consist of a single expression and do not require curly braces.
    • Statement lambdas: Consist of one or more statements and require curly braces.

Expression Lambda:

(int x, int y) => x + y;

Statement Lambda:

(int x, int y) =>
{
    int result = x + y;
    return result;
};

Practical Uses

  1. Event Handling:
    • Lambda expressions and anonymous methods can be used to define event handlers inline.

Example:

using System;

public class Program
{
    public static void Main()
    {
        EventHandler handler = (sender, e) => Console.WriteLine("Event triggered!");
        var button = new Button();
        button.Click += handler;
        button.OnClick();
    }
}

public class Button
{
    public event EventHandler Click;

    public void OnClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}
  1. LINQ Queries:
    • Lambda expressions are extensively used in LINQ queries for filtering, sorting, and projecting data.

Example:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David" };
        var filteredNames = names.Where(name => name.StartsWith("C")).ToList();

        foreach (var name in filteredNames)
        {
            Console.WriteLine(name);
        }
    }
}
  1. Delegate Initialization:
    • Both anonymous methods and lambda expressions can be used to initialize delegates.

Example:

using System;

public class Program
{
    public delegate int MathOperation(int x, int y);

    public static void Main()
    {
        MathOperation add = (x, y) => x + y;
        MathOperation multiply = delegate (int x, int y)
        {
            return x * y;
        };

        Console.WriteLine($"Add: {add(3, 4)}");
        Console.WriteLine($"Multiply: {multiply(3, 4)}");
    }
}

Differences Between Anonymous Methods and Lambda Expressions

  • Syntax:

    • Anonymous methods use the delegate keyword and curly braces.
    • Lambda expressions use the => operator with optional curly braces for statement lambdas.
  • Type Inference:

    • Lambda expressions often benefit from type inference, making the code more concise.
    • Anonymous methods require explicit parameter types.
  • Features:

    • Lambda expressions can be converted to expression trees, enabling scenarios like LINQ to SQL.
    • Anonymous methods cannot be converted to expression trees.

Summary

Anonymous methods and lambda expressions in C# provide flexible and concise ways to define inline methods, making the code more readable and maintainable. While anonymous methods use the delegate keyword, lambda expressions offer a shorter syntax with the => operator. Both are widely used in event handling, LINQ queries, and delegate initialization, enhancing the expressiveness and power of C# programming.

Recent job openings