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
Ad

Recommended

Fun with lambda expressions
Fun with lambda expressions
Mike Melusky
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Jaliya Udagedara
 
Lexical analyzer
Lexical analyzer
kiran acharya
 
Getting started with c++
Getting started with c++
K Durga Prasad
 
Lesson 02 python keywords and identifiers
Lesson 02 python keywords and identifiers
Nilimesh Halder
 
Lexical analysis-using-lex
Lexical analysis-using-lex
Dattatray Gandhmal
 
Pc module1
Pc module1
SANTOSH RATH
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
Anurag University Hyderabad
 
Ch6
Ch6
kinnarshah8888
 
Pcd question bank
Pcd question bank
Sumathi Gnanasekaran
 
Basics1
Basics1
phanleson
 
Language for specifying lexical Analyzer
Language for specifying lexical Analyzer
Archana Gopinath
 
Fun with lambda expressions
Fun with lambda expressions
Mike Melusky
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
Lexical Analyzers and Parsers
Lexical Analyzers and Parsers
Heshan Suriyaarachchi
 
C programming notes
C programming notes
Prof. Dr. K. Adisesha
 
JDK8 Lambda expressions demo
JDK8 Lambda expressions demo
MouryaKumar Reddy Rajala
 
A simple approach of lexical analyzers
A simple approach of lexical analyzers
Archana Gopinath
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Lex
Lex
BBDITM LUCKNOW
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
20130329 introduction to linq
20130329 introduction to linq
LearningTech
 
Lexical analyzer generator lex
Lexical analyzer generator lex
Anusuya123
 
C++ ppt
C++ ppt
parpan34
 
Lecture 7 Templates, Friend Classes
Lecture 7 Templates, Friend Classes
bunnykhan
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
C++ for beginners
C++ for beginners
Salahaddin University-Erbil
 
Cpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
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...
tutorials-visual-studio_visual-studio-2015-preview-comes-with-emulator-for-an...
Anil Sharma
 

More Related Content

What's hot (20)

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

Viewers also liked (7)

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

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

C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
techfreak
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
Prabu U
 
Mastering C# Lambda Expressions: A Complete Guide
Mastering C# Lambda Expressions: A Complete Guide
LetsUpdateSkills
 
Java 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
Java 8 features
Java 8 features
NexThoughts Technologies
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
Abed Bukhari
 
3-Python Python oho pytho hdiwefjhdsjhds
3-Python Python oho pytho hdiwefjhdsjhds
hardikbhagwaria83
 
C Programming - Basics of c -history of c
C Programming - Basics of c -history of c
DHIVYAB17
 
C++ question and answers
C++ question and answers
AdenKheire
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Introduction of C++ By Pawan Thakur
Introduction of C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
C material
C material
tarique472
 
C++ tutorial assignment - 23MTS5730.pptx
C++ tutorial assignment - 23MTS5730.pptx
sp1312004
 
Advance python programming
Advance python programming
Jagdish Chavan
 
Functions assignment
Functions assignment
Ahmad Kamal
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
techfreak
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
Prabu U
 
Mastering C# Lambda Expressions: A Complete Guide
Mastering C# Lambda Expressions: A Complete Guide
LetsUpdateSkills
 
Java 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
Abed Bukhari
 
3-Python Python oho pytho hdiwefjhdsjhds
3-Python Python oho pytho hdiwefjhdsjhds
hardikbhagwaria83
 
C Programming - Basics of c -history of c
C Programming - Basics of c -history of c
DHIVYAB17
 
C++ question and answers
C++ question and answers
AdenKheire
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
C++ tutorial assignment - 23MTS5730.pptx
C++ tutorial assignment - 23MTS5730.pptx
sp1312004
 
Advance python programming
Advance python programming
Jagdish Chavan
 
Functions assignment
Functions assignment
Ahmad Kamal
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
Ad

Recently uploaded (20)

EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 

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