Skip to Content
All posts

Mastering Advanced C# Features

Lambda Expressions, Anonymous Types, Anonymous Methods, and Extension Methods

2 min read ·  — #csharp-interview#middle-specialist#lambda-expressions,#anonymous-types,#anonymous-methods,#extension-methods

Mastering Advanced C# Features

In the universe of C#, developers often traverse familiar landscapes, encountering constructs and paradigms they've seen countless times. But sometimes, veering off the beaten path can lead to richer, more efficient code. Today, we'll journey through four such features: lambda expressions, anonymous types, anonymous methods, and extension methods.

1. Lambda Expressions

Lambda expressions are anonymous functions succinctly defined using the => operator.

Syntax:

(parameters) => expression-or-statement-block

Examples:

  • Simple Arithmetic:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Outputs: 8
  • Predicate to Check for Even Numbers:
Predicate<int> isEven = num => num % 2 == 0;
Console.WriteLine(isEven(4)); // Outputs: True

2. Anonymous Types

They allow creation of unnamed object types, primarily for temporary storage of related data.

Syntax:

new { Property1 = value1, Property2 = value2, ... }

Examples:

  • Creating an Anonymous Type for a Car:
var car = new { Make = "Toyota", Model = "Camry" };
Console.WriteLine($"Car Model: {car.Model}");  // Outputs: Car Model: Camry
  • Combining Data from Different Sources:
string[] names = { "Alice", "Bob" };
int[] scores = { 85, 90 };
var combined = names.Zip(scores, (name, score) =>
               new { Name = name, Score = score });

3. Anonymous Methods

Anonymous methods are inline methods declared without a name, predominantly seen in legacy code.

Syntax:

delegate(parameters) { statement(s) }

Examples:

  • Anonymous Method as a Predicate:
List<int> numbers = new List<int> { 1, 2, 3, 4 };

int evenCount = numbers
                .FindAll(delegate(int num) { return num % 2 == 0; })
                .Count;

Console.WriteLine(evenCount); // Outputs: 2

4. Extension Methods

These allow developers to seamlessly add methods to existing types without altering them.

Syntax:

public static ReturnType MethodName(this ExtendedType name, otherParameters)
{
  // ...
}

Examples:

  • Checking for Even Numbers on Integers:
public static class IntExtensions
{
  public static bool IsEven(this int value)
  {
     return value % 2 == 0;
  }
}

Console.WriteLine(6.IsEven()); // Outputs: True
  • Reversing a String:
public static class StringExtensions
{
    public static string Reverse(this string str)
    {
        return new string(str.Reverse().ToArray());
    }
}

Console.WriteLine("hello".Reverse()); // Outputs: olleh

Conclusion

The realm of C# is vast and filled with tools waiting to be mastered. Lambda expressions, anonymous types, anonymous methods, and extension methods are among the jewels that can elevate your coding prowess. They encapsulate the essence of modern C# and empower developers to write clean, maintainable, and efficient code. Here's to uncovering more secrets of the language and pushing boundaries in software engineering!

References