How to implement Anonymous Methods in C#?


This article will demonstrate Anonymous Methods in C#. I hope it will be useful for all beginners of C#. In this article, list is used for Anonymous Methods implementation. If the value is found in the list then output will be displayed as "Value found in the list."

How to implement Anonymous Methods in C#?
Description -
C# 2.0 has introduced new feature as Anonymous Methods which is very useful and powerful. It allows us to define a code block where a delegate object is acceptable.
Coding overhead can be reduced in the instantiating delegates by eliminating the need to create a separate method.
Create a console application and put following code into it.

 
using System;
using System.Collections.Generic;
using System.Text;

namespace MySampleForAnonymousMethods
{
class Program
{
static void Main(string[] args)
{
List LstValues = new List();
LstValues.Add(12);
LstValues.Add(121);
LstValues.Add(122);
LstValues.Add(112);
LstValues.Add(312);
LstValues.Add(152);

int InputValueToFind = 12;

int result = LstValues.Find(delegate(int val) { return (val == InputValueToFind); });

if (result != 0)
Console.WriteLine("Value found in the list.");
}

}
}


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: