TechBubbles Microsoft Technology BLOG

Lambda Expressions in C# 3.0

Lambda expressions is one of the features introduced in the C# 3.0. Lambda expressions help you to ease the burden of writing verbose Anonymous Methods.

I will explain the where to use the Anonymous methods first then we see the example on lambda expressions

Anonymous Methods

Anonymous Methods is the feature in C# 2.0. The idea behind writing the anonymous methods is to write methods inline to the code with out declaring a formal named method. Normally they used for small methods that don’t require any reuse.

Example:

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(IsKalyan);

   }

   public static bool IsKalyan(string name)

  {

      return name.Equals(“Kalyan”);

  }

}

You can declare a anonymous method as follows

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(delegate (string name )

                                            {

                                                return name.Equals(“Kalyan”);

                                             }   );

   }

}

Advantage: It saves some typing and puts the method closer to where it is being used which helps with maintenance

Lambda Expressions

Lambda Expressions makes the thing even more easier by allowing you to write avoid anonymous method and statement block.

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find( name => name.Equals(“Kalyan”));

}

We can also effectively use the Lambda Expressions with LINQ and i will explain the feature in forth coming articles.

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

Add Comment

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud