SlideShare a Scribd company logo
1 of 4
Download to read offline
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

Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical AnalyzerArchana Gopinath
 
Fun with lambda expressions
Fun with lambda expressionsFun with lambda expressions
Fun with lambda expressionsMike Melusky
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerVineet Kumar Saini
 
A simple approach of lexical analyzers
A simple approach of lexical analyzersA simple approach of lexical analyzers
A simple approach of lexical analyzersArchana Gopinath
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Syed Farjad Zia Zaidi
 
20130329 introduction to linq
20130329 introduction to linq20130329 introduction to linq
20130329 introduction to linqLearningTech
 
Lexical analyzer generator lex
Lexical analyzer generator lexLexical analyzer generator lex
Lexical analyzer generator lexAnusuya123
 
Lecture 7 Templates, Friend Classes
Lecture 7 Templates, Friend ClassesLecture 7 Templates, Friend Classes
Lecture 7 Templates, Friend Classesbunnykhan
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationAkhil Kaushik
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of CSuchit Patel
 

What's hot (20)

Ch6
Ch6Ch6
Ch6
 
Pcd question bank
Pcd question bank Pcd question bank
Pcd question bank
 
Basics1
Basics1Basics1
Basics1
 
Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical Analyzer
 
Fun with lambda expressions
Fun with lambda expressionsFun with lambda expressions
Fun with lambda expressions
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
Lexical Analyzers and Parsers
Lexical Analyzers and ParsersLexical Analyzers and Parsers
Lexical Analyzers and Parsers
 
C programming notes
C programming notesC programming notes
C programming notes
 
JDK8 Lambda expressions demo
JDK8 Lambda expressions demoJDK8 Lambda expressions demo
JDK8 Lambda expressions demo
 
A simple approach of lexical analyzers
A simple approach of lexical analyzersA simple approach of lexical analyzers
A simple approach of lexical analyzers
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Lex
LexLex
Lex
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
 
20130329 introduction to linq
20130329 introduction to linq20130329 introduction to linq
20130329 introduction to linq
 
Lexical analyzer generator lex
Lexical analyzer generator lexLexical analyzer generator lex
Lexical analyzer generator lex
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Lecture 7 Templates, Friend Classes
Lecture 7 Templates, Friend ClassesLecture 7 Templates, Friend Classes
Lecture 7 Templates, Friend Classes
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 

Viewers also liked

dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...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...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 OverviewYammer Overview
Yammer Overviewmselepec
 
Comparing JVM Web Frameworks - Spring I/O 2012
Comparing JVM Web Frameworks - Spring I/O 2012Comparing JVM Web Frameworks - Spring I/O 2012
Comparing JVM Web Frameworks - Spring I/O 2012Matt Raible
 
Cloud Native Progressive Web Applications - Denver JUG 2016
Cloud Native Progressive Web Applications - Denver JUG 2016Cloud Native Progressive Web Applications - Denver JUG 2016
Cloud Native Progressive Web Applications - Denver JUG 2016Matt Raible
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 

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

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

C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTNguyen Patrick
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
C++ question and answers
C++ question and answersC++ question and answers
C++ question and answersAdenKheire
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.Questpond
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfSudhanshiBakre1
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignmentAhmad Kamal
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The LambdaTogakangaroo
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
C#-LINQ-and-Lambda-Expression
C#-LINQ-and-Lambda-ExpressionC#-LINQ-and-Lambda-Expression
C#-LINQ-and-Lambda-ExpressionSimplilearn
 

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 FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
C++ question and answers
C++ question and answersC++ question and answers
C++ question and answers
 
Introduction of C++ By Pawan Thakur
Introduction of C++ By Pawan ThakurIntroduction of C++ By Pawan Thakur
Introduction of C++ By Pawan Thakur
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
C material
C materialC material
C material
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
C-PROGRAM
C-PROGRAMC-PROGRAM
C-PROGRAM
 
C#-LINQ-and-Lambda-Expression
C#-LINQ-and-Lambda-ExpressionC#-LINQ-and-Lambda-Expression
C#-LINQ-and-Lambda-Expression
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

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