Ads Top

Lambda in C#

Lambda. The syntax for delegate functions can be complex. Lambda expressions provide a simple and terse way of specifying functions. They use the => syntax to separate formal parameters and the method body.

Lambda: Syntax
Tip:Lambda expressions are used throughout C# programs. Common methods receive them as arguments.
Tip 2:Whenever you see a method that receives a Predicate, Action, Func or Comparison, a lambda can be passed.

Example . Next, we build upon the delegate concept. We declare a delegate type UppercaseDelegate. It receives a string, and returns a string. We create instances of this delegate Type in the Main method.

Program that uses delegate type: C#

using System;

class Program
{
    delegate string UppercaseDelegate(string input);

    static string UppercaseFirst(string input)
    {
        char[] buffer = input.ToCharArray();
        buffer[0] = char.ToUpper(buffer[0]);
        return new string(buffer);
    }

    static string UppercaseLast(string input)
    {
        char[] buffer = input.ToCharArray();
        buffer[buffer.Length - 1] = char.ToUpper(buffer[buffer.Length - 1]);
        return new string(buffer);
    }

    static string UppercaseAll(string input)
    {
        return input.ToUpper();
    }

    static void WriteOutput(string input, UppercaseDelegate del)
    {
        Console.WriteLine("Your string before: {0}", input);
        Console.WriteLine("Your string after: {0}", del(input));
    }

    static void Main()
    {
        // Wrap the methods inside delegate instances and pass to the method.
        WriteOutput("perls", new UppercaseDelegate(UppercaseFirst));
        WriteOutput("perls", new UppercaseDelegate(UppercaseLast));
        WriteOutput("perls", new UppercaseDelegate(UppercaseAll));
    }
}

Output

Your string before: perls
Your string after: Perls
Your string before: perls
Your string after: perlS
Your string before: perls
Your string after: PERLS

No comments:

Powered by Blogger.