SlideShare a Scribd company logo
A
Understanding Generic Anonymous Methods and Lambda Expressions in C#
Posted Date: 1. May 2014 Author: Anil Sharma
Categories: .Net Framework, LINQ, C Sharp
Keywords: Generic Anonymous Methods, Anonymous Methods, Lambda Expressions, Lambda Expressions in C#, Lambda
Expressions Tutorials
nonymous methods behave like regular methods except that they are unnamed. Anonymous Methods were introduced
as an alternative to defining delegates that did very simple tasks, where full-blown methods amounted to more than
just extra typing. Anonymous methods also evolved further into Lambda Expressions, which are even shorter methods.
What is Anonymous Methods?
An anonymous method is like a regular method but uses the delegate keyword, and doesn’t require a name, parameters, or
return type. Following code example shows a regular method (used as a delegate for the CancelKeyPress event, Ctrl+C in a
console application) and an anonymous delegate that performs the same role.
The regular method which is uses as delegate is named ConsoleCancelEventHandler. The second statement that begins with
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program
{
static void Main(string[] args)
{
// ctrl+c
Console.CancelKeyPress += new ConsoleCancelEventHandler
(Console_CancelKeyPress);
// anonymous cancel delegate
Console.CancelKeyPress +=
delegate
{
Console.WriteLine(“Anonymous Cancel pressed”);
};
Console.ReadLine();
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine(“Cancel pressed”);
}
}
http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an...
1 of 4 8/18/2014 10:22 AM
the Console.CancelKeyPress += delegate demonstrates an anonymous method (delegate) that is equivalent to the longer
form of the method. The point of notice is that because the parameters in the delegate aren’t used, they are omitted from the
anonymous delegate. You have the option of using the parameter types and names if they are needed in the delegate.
Understanding Anonymous Generic Methods:
Delegates are really just methods as they are mostly used as event handlers. Generic methods are those that have
parameterized types. (You can think about replaceable data types.) Therefore, anonymous generic delegates are anonymous
methods that are associated with replaceable parameterized types. A very useful type is Func<t>. This generic delegate is
defined in the System namespace and can be assigned to delegates and anonymous delegates with varying return types and
parameters, which makes it a very flexible and useful.
Let’s take an example to understand that how we can use Anonymous Generic methods, following are simple example for
Anonymous Generic Methods
For all intents and purposes, Factorial is a nested function. above code used Func<long,long>, where the first long parameter
represents the return type and the second is the parameter. Notice that the listing also used a named parameter for the
anonymous delegate.
Understanding Lambda Expressions in C#
A Lambda Expression is a concise delegate. The left side (of the =>) represents the arguments to the function and the right
side is the function body. In below listed example, the Lambda Expression is assigned to the delegate FunctionPointer, but
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Program
{
static void Main(string[] args)
{
System.Func<long, long> Factorial =
delegate(long n)
{
if(n==1) return 1;
long result=1;
for(int i=2; i<=n; i++)
result *= i;
return result;
};
Console.WriteLine(Factorial(6));
Console.ReadLine();
}
}
http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an...
2 of 4 8/18/2014 10:22 AM
.NET 3.5 defines anonymous delegates like Action<t> and Func<t>, which can be used instead of the more formal, longer
delegate statement. This means that you don’t have to define the delegate statement in below example.
Following is an example shows the revision of above example, replacing the delegate statement with the generic Action<t>
delegate type.
Lambda Expressions we can define automatic properties. The basic idea behind automatic properties is that many times,
programmers define properties that are just wrappers for fields and nothing else happens. If there are no additional behaviors,
automatic properties allow the compiler to add the field, getter, and setter.
Summary: Anonymous Methods and Lambda Expressions are very powerful and useful in c#. There are predefined Generic
Delegates Func<t>, Predicate<t> and Action<t>, are very useful for programmers. We will understand these into a separate
article. Anonymous Methods and Lambda Expressions are widely used with Linq. You can begin exploring how Lambda
Expressions support LINQ queries by seeing how Lambda Expressions are used in extension methods such as Select<t>,
Where<t>, or OrderBy<t>.
Keen to here from you...!
1
2
3
4
5
6
7
8
9
10
11
class Program
{
delegate void FunctionPointer(string str);
static void Main(string[] args)
{
FunctionPointer fp =
s => Console.WriteLine(s);
fp("Dot Net Stuff!");
Console.ReadLine();
}
}
1
2
3
4
5
6
7
8
9
10
class Program
{
static void Main(string[] args)
{
System.Action<string> fp =
s => Console.WriteLine(s);
fp("Dot Net Stuff!");
Console.ReadLine();
}
}
http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an...
3 of 4 8/18/2014 10:22 AM
If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from
you. Please MakeUseOf Contact and i will be more than happy to help.
About the author
Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and
loves to work with Microsoft .Net. He's usually writes articles about .Net related
technologies and here to shares his experiences, personal notes, Tutorials,
Examples, Problems & Solutions, Code Snippets, Reference Manual and
Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL
Server, jQuery, Visual Studio and much more...!!!
Connect with the author: • Google • Linkedin
http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an...
4 of 4 8/18/2014 10:22 AM

More Related Content

What's hot (20)

DOC
Pcd question bank
Sumathi Gnanasekaran
 
PPT
Basics1
phanleson
 
PPTX
Language for specifying lexical Analyzer
Archana Gopinath
 
PPTX
Fun with lambda expressions
Mike Melusky
 
PDF
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
PPT
Lexical Analyzers and Parsers
Heshan Suriyaarachchi
 
PDF
C programming notes
Prof. Dr. K. Adisesha
 
PPTX
JDK8 Lambda expressions demo
MouryaKumar Reddy Rajala
 
PPTX
A simple approach of lexical analyzers
Archana Gopinath
 
PPT
C++ Programming Course
Dennis Chang
 
PPTX
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
PPT
20130329 introduction to linq
LearningTech
 
PPTX
Lexical analyzer generator lex
Anusuya123
 
PPTX
C++ ppt
parpan34
 
PPT
Lecture 7 Templates, Friend Classes
bunnykhan
 
PPT
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
PPT
C++ for beginners
Salahaddin University-Erbil
 
PPTX
Cpu-fundamental of C
Suchit Patel
 
Pcd question bank
Sumathi Gnanasekaran
 
Basics1
phanleson
 
Language for specifying lexical Analyzer
Archana Gopinath
 
Fun with lambda expressions
Mike Melusky
 
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
Lexical Analyzers and Parsers
Heshan Suriyaarachchi
 
C programming notes
Prof. Dr. K. Adisesha
 
JDK8 Lambda expressions demo
MouryaKumar Reddy Rajala
 
A simple approach of lexical analyzers
Archana Gopinath
 
C++ Programming Course
Dennis Chang
 
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
20130329 introduction to linq
LearningTech
 
Lexical analyzer generator lex
Anusuya123
 
C++ ppt
parpan34
 
Lecture 7 Templates, Friend Classes
bunnykhan
 
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
C++ for beginners
Salahaddin University-Erbil
 
Cpu-fundamental of C
Suchit Patel
 

Viewers also liked (7)

PDF
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
Anil Sharma
 
PDF
tutorials-visual-studio_visual-studio-2015-preview-comes-with-emulator-for-an...
Anil Sharma
 
PPTX
Yammer Overview
mselepec
 
PDF
Comparing JVM Web Frameworks - Spring I/O 2012
Matt Raible
 
PDF
Cloud Native Progressive Web Applications - Denver JUG 2016
Matt Raible
 
PPTX
ASP.NET MVC Performance
rudib
 
PPTX
Indian patent act
Soumya Athira
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
Anil Sharma
 
tutorials-visual-studio_visual-studio-2015-preview-comes-with-emulator-for-an...
Anil Sharma
 
Yammer Overview
mselepec
 
Comparing JVM Web Frameworks - Spring I/O 2012
Matt Raible
 
Cloud Native Progressive Web Applications - Denver JUG 2016
Matt Raible
 
ASP.NET MVC Performance
rudib
 
Indian patent act
Soumya Athira
 
Ad

Similar to tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressions-in-c-sharp (20)

PPTX
Lamdha.pptx
ControlUrgentSecurit
 
PDF
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
PDF
Review of c_sharp2_features_part_ii
Nico Ludwig
 
PPTX
C# Delegates
Raghuveer Guthikonda
 
PDF
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 
PPTX
Evolution of C# delegates
mbaric
 
PDF
Intake 38 5 1
Mahmoud Ouf
 
DOCX
Mastering C# Lambda Expressions: A Complete Guide
LetsUpdateSkills
 
PPTX
C#.net Evolution part 1
Vahid Farahmandian
 
PDF
Delegate
rsvermacdac
 
PPTX
Essential language features
baabtra.com - No. 1 supplier of quality freshers
 
PPT
Of Lambdas and LINQ
BlackRabbitCoder
 
PPTX
Lambdas and Extension using VS2010
vgrondin
 
PPTX
Linq and lambda
John Walsh
 
PDF
Linq & lambda overview C#.net
Dhairya Joshi
 
PPTX
09 advanced c#
eleksdev
 
PPTX
Delegetes in c#
Mahbub Hasan
 
PPTX
Unit2_1.pptx Introduction to C# Language features
Priyanka Jadhav
 
PPTX
Unit 1:DOT NET Framework CLR(Common Language Runtime )
Priyanka Jadhav
 
ODP
Can't Dance The Lambda
Togakangaroo
 
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
Review of c_sharp2_features_part_ii
Nico Ludwig
 
C# Delegates
Raghuveer Guthikonda
 
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 
Evolution of C# delegates
mbaric
 
Intake 38 5 1
Mahmoud Ouf
 
Mastering C# Lambda Expressions: A Complete Guide
LetsUpdateSkills
 
C#.net Evolution part 1
Vahid Farahmandian
 
Delegate
rsvermacdac
 
Of Lambdas and LINQ
BlackRabbitCoder
 
Lambdas and Extension using VS2010
vgrondin
 
Linq and lambda
John Walsh
 
Linq & lambda overview C#.net
Dhairya Joshi
 
09 advanced c#
eleksdev
 
Delegetes in c#
Mahbub Hasan
 
Unit2_1.pptx Introduction to C# Language features
Priyanka Jadhav
 
Unit 1:DOT NET Framework CLR(Common Language Runtime )
Priyanka Jadhav
 
Can't Dance The Lambda
Togakangaroo
 
Ad

Recently uploaded (20)

PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressions-in-c-sharp

  • 1. A Understanding Generic Anonymous Methods and Lambda Expressions in C# Posted Date: 1. May 2014 Author: Anil Sharma Categories: .Net Framework, LINQ, C Sharp Keywords: Generic Anonymous Methods, Anonymous Methods, Lambda Expressions, Lambda Expressions in C#, Lambda Expressions Tutorials nonymous methods behave like regular methods except that they are unnamed. Anonymous Methods were introduced as an alternative to defining delegates that did very simple tasks, where full-blown methods amounted to more than just extra typing. Anonymous methods also evolved further into Lambda Expressions, which are even shorter methods. What is Anonymous Methods? An anonymous method is like a regular method but uses the delegate keyword, and doesn’t require a name, parameters, or return type. Following code example shows a regular method (used as a delegate for the CancelKeyPress event, Ctrl+C in a console application) and an anonymous delegate that performs the same role. The regular method which is uses as delegate is named ConsoleCancelEventHandler. The second statement that begins with 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Program { static void Main(string[] args) { // ctrl+c Console.CancelKeyPress += new ConsoleCancelEventHandler (Console_CancelKeyPress); // anonymous cancel delegate Console.CancelKeyPress += delegate { Console.WriteLine(“Anonymous Cancel pressed”); }; Console.ReadLine(); } static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { Console.WriteLine(“Cancel pressed”); } } http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an... 1 of 4 8/18/2014 10:22 AM
  • 2. the Console.CancelKeyPress += delegate demonstrates an anonymous method (delegate) that is equivalent to the longer form of the method. The point of notice is that because the parameters in the delegate aren’t used, they are omitted from the anonymous delegate. You have the option of using the parameter types and names if they are needed in the delegate. Understanding Anonymous Generic Methods: Delegates are really just methods as they are mostly used as event handlers. Generic methods are those that have parameterized types. (You can think about replaceable data types.) Therefore, anonymous generic delegates are anonymous methods that are associated with replaceable parameterized types. A very useful type is Func<t>. This generic delegate is defined in the System namespace and can be assigned to delegates and anonymous delegates with varying return types and parameters, which makes it a very flexible and useful. Let’s take an example to understand that how we can use Anonymous Generic methods, following are simple example for Anonymous Generic Methods For all intents and purposes, Factorial is a nested function. above code used Func<long,long>, where the first long parameter represents the return type and the second is the parameter. Notice that the listing also used a named parameter for the anonymous delegate. Understanding Lambda Expressions in C# A Lambda Expression is a concise delegate. The left side (of the =>) represents the arguments to the function and the right side is the function body. In below listed example, the Lambda Expression is assigned to the delegate FunctionPointer, but 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Program { static void Main(string[] args) { System.Func<long, long> Factorial = delegate(long n) { if(n==1) return 1; long result=1; for(int i=2; i<=n; i++) result *= i; return result; }; Console.WriteLine(Factorial(6)); Console.ReadLine(); } } http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an... 2 of 4 8/18/2014 10:22 AM
  • 3. .NET 3.5 defines anonymous delegates like Action<t> and Func<t>, which can be used instead of the more formal, longer delegate statement. This means that you don’t have to define the delegate statement in below example. Following is an example shows the revision of above example, replacing the delegate statement with the generic Action<t> delegate type. Lambda Expressions we can define automatic properties. The basic idea behind automatic properties is that many times, programmers define properties that are just wrappers for fields and nothing else happens. If there are no additional behaviors, automatic properties allow the compiler to add the field, getter, and setter. Summary: Anonymous Methods and Lambda Expressions are very powerful and useful in c#. There are predefined Generic Delegates Func<t>, Predicate<t> and Action<t>, are very useful for programmers. We will understand these into a separate article. Anonymous Methods and Lambda Expressions are widely used with Linq. You can begin exploring how Lambda Expressions support LINQ queries by seeing how Lambda Expressions are used in extension methods such as Select<t>, Where<t>, or OrderBy<t>. Keen to here from you...! 1 2 3 4 5 6 7 8 9 10 11 class Program { delegate void FunctionPointer(string str); static void Main(string[] args) { FunctionPointer fp = s => Console.WriteLine(s); fp("Dot Net Stuff!"); Console.ReadLine(); } } 1 2 3 4 5 6 7 8 9 10 class Program { static void Main(string[] args) { System.Action<string> fp = s => Console.WriteLine(s); fp("Dot Net Stuff!"); Console.ReadLine(); } } http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an... 3 of 4 8/18/2014 10:22 AM
  • 4. If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help. About the author Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!! Connect with the author: • Google • Linkedin http://www.dotnet-stuff.com/tutorials/c-sharp/understanding-generic-an... 4 of 4 8/18/2014 10:22 AM