SlideShare une entreprise Scribd logo
1  sur  28
Evolution of C# delegates

Marko Barić
Senior software engineer @ Siemens CVC
marko.baric@siemens.com
Agenda
• Basic delegates
•

•
•
•
•
•
•

Delegate types, delegate instances

Combining multiple delegates
Method group conversions
Covariance and contravariance
Inline delegate actions
Captured variables (closures)
Lambda expressions
What is a delegate?
•
•
•
•

Provide a level of indirection
Sort of "sigle method interface"
Delegates inhert from System.Delegate
To create and use delegates:
•
•
•
•

The delegate type needs to be declared
The code to be executed must be contained in a
method
A delegate instance must be created
The delegate instance must be invoked
Declaring delegate types

delegate void StringProcessor(string input);
keyword

return
type

delegate type name

arguments
Creating delegate instances
class MyClass
{
public void SomeMethod(string input)
public static void SomeMethodStatic(string input)
}

StringProcessor p1 = new StringProcessor(myClassInstance.SomeMethod);

delegate instance
variable

delegate
type

action to invoke on
MyClass instance

StringProcessor p2 = new StringProcessor(MyClass.SomeMethod);

static action to
invoke on MyClass
Invoking delegates
StringProcessor p1 = new StringProcessor(myClassInstance.SomeMethod);
p1.Invoke("Some string");
// ...or shorter version
p1("Some string");

p1("Some string");

p1.Invoke("Some string")

SomeMethod("Some string")

• Delegates can be treated like any other type

• They have methods, multiple instance can be created...
Example
delegate void StringProcessor(string input);
class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
public void SayTheMessage(string message)
{
Console.WriteLine("{0} says: {1}", name, message);
}
public static void SayTheMessageStatic(string message)
{
Console.WriteLine(message);
}
}
static void Main(string[] args)
{
Person john = new Person("John");
Person tom = new Person("Tom");

// Result:
"John says: Hello!"
"Tom says: Hello!"
"Just saying something..."

StringProcessor johnsVoice = new StringProcessor(john.SayTheMessage);
StringProcessor tomsVoice = new StringProcessor(tom.SayTheMessage);
StringProcessor someonesVoice = new StringProcessor(Person.SayTheMessageStatic);

johnsVoice("Hello!");
tomsVoice.Invoke("Hello!");
someonesVoice("Just saying something...");
}
Combining the delegates
• All delegates inherit methods from
System.Delegate:
•
•

Delegate.Combine()
Delegate.Remove()

• Every delegate has an invocation list - a
list of actions to invoke
• "+", "+=", "-", "-="
• When delegate is invoked, all actions in
the invocation list are invoked in the
order they were added
Example of combining delegates
Person john = new Person("John");
Person tom = new Person("Tom");
Person mike = new Person("Mike");
StringProcessor johnsVoice = new StringProcessor(john.SayTheMessage);
StringProcessor tomsVoice = new StringProcessor(tom.SayTheMessage);
StringProcessor mikesVoice = new StringProcessor(mike.SayTheMessage);
StringProcessor twoCombined = johnsVoice + tomsVoice;
StringProcessor allCombined = twoCombined + mikesVoice;
allCombined += new StringProcessor(john.SayTheMessage);
allCombined("What's up!");
// Result:
"John says: What's up!"
"Tom says: What's up!"
"Mike says: What's up!"
"John says: What's up!"
Method group converions
//Delegate type
delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e);
//Target action
void LogKeyEvent(object sender, KeyPressEventArgs e)
{ /* do something */ }
void LogKeyEvent(int x)
{ /* do something */ }

button.KeyPress += new KeyPressEventHandler(LogKeyEvent);

button.KeyPress += LogKeyEvent;

Method group is converted to
compatible delegate type
Contravariance of delegates
Click
-----> void EventHandler(object sender, EventArgs e)
KeyPress -----> void KeyPressEventHandler(object sender, KeyPressEventArgs e)
MouseClick ---> void MouseClickEventHandler(object sender, MouseEventArgs e)
Button button = new Button();
button.Text = "Click me";
button.Click += LogPlainEvent;
button.KeyPress += LogPlainEvent;
button.MouseClick += LogPlainEvent;

Same action for 3 different delegates!

Form form = new Form();
form.Controls.Add(button);
Application.Run(form);
static void LogEvent(object sender, EventArgs e)
{
Console.WriteLine("An event occurred");
}
Covariance of delegates
delegate Stream MyDelegate();

Stream
static MemoryStream GenerateSampleData()
{
byte[] buffer = new byte[16];
return new MemoryStream(buffer);
}
MyDelegate d = GenerateSampleData();
Stream stream = d();
MemoryStream stream = d();

MemoryStream
Built-in delegate types in .NET
delegate void Action<T>(T arg);
delegate void Action<T1, T2>(T1 arg1, T2 arg2);
...
delegate TResult Func<T, TResult>(T arg);
delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
...
delegate bool Predicate<T>(T arg);
...
Inline delegate actions
• You don't need action method to exist you can create it inline
Action<int> printRoot = delegate(int number)
{
Console.WriteLine(Math.Sqrt(number));
};
printRoot(9);

Invoke it like other delegates

Func<string, int> getLength = delegate(string input)
{
return input.Length;
};
int length = getLength("Some string");
Ingnoring inline delegate
arguments
• When you won't use delegate arguments
you can loose them in definition
button.Click += delegate(object sender, EventArgs e) { ... };
Button button = new Button();
button.Text = "Click me";
button.Click += delegate { Console.WriteLine("Click"); };
button.KeyPress += delegate { Console.WriteLine("KeyPress"); };
button.MouseClick += delegate { Console.WriteLine("MouseClick"); };
Ingnoring inline delegate
arguments
• Beware of the compiler limitations:
// Thread class has several different constructors
public Thread(ThreadStart start)
public Thread(ParameterizedThreadStart start)
// There are 2 types of delegates involved
public delegate void ThreadStart()
public delegate void ParameterizedThreadStart(object obj)
new Thread(delegate() { Console.WriteLine("Something..."); } );
new Thread(delegate(object o) { Console.WriteLine("Something..."); } );
new Thread(delegate { Console.WriteLine("Something..."); } );
Captured variables (closures)
• Captured variables are outer variables
used (captured) in the scope of
anonymous method
void EnclosingMethod()
{
string outerVariable = "Default string";
Action<int> a = delegate()
{
string localVariable = outerVariable;
};
a();
}
Captured variables
delegate void MyDelegate();
string captured = "before x is created";
MyDelegate x = delegate
{
Console.WriteLine(captured);
captured = "changed by x";
};
captured = "before x is invoked";
x();
Console.WriteLine(captured);
captured = "before second invocation";
x();
// Result:
"before x is invoked"
"changed by x"
"before second invocation"

The captured variable is the same one
that the outer code uses!!!
Lifetime of captured variables
• A captured variable lives for at least as
long as any delegate instance referring to
it MethodInvoker CreateDelegateInstance()
public
{

int counter = 5;
MethodInvoker increment = delegate
{
Console.WriteLine(counter);
counter++;
};
increment();
return counter;
}
...
MethodInvoker x = CreateDelegateInstance();
x();
x();
Things can get tricky very fast
MethodInvoker[] invokers = new MethodInvoker[2];
int outsideVariable = 0;
for (int i=0; i<2; i++)
{
int insideVariable = 0;
invokers[i] = delegate
{
Console.WriteLine ("({0},{1})", outsideVariable, insideVariable);
outsideVariable++;
insideVariable++;
};
}
MethodInvoker first = invokers[0];
// Result:
MethodInvoker second = invokers[1];
(0,0)
first();
first();
first();
second();
second();

(1,1)
(2,2)
(3,0)
(4,1)
Lambda expressions
• They are evolution of anonymous
methods
• More readable and compact than other
delegate forms
• Many shortcuts and "syntatic sugar"
tricks allow most compat form of code
• Brings new operator "=>" (spelled as
"goes to")
Simple lambda expression
delegate TResult Func<T, TResult>(T input);
Func<string, int> returnLength;
returnLength = delegate (string text)
{
return text.Length;
};

(list of input arguments) =>

{ statements }

returnLength = (string text) => { return text.Length; };

input arguments

statements
Shortening the lambdas
returnLength = (string text) => { return text.Length; }

If the statement is single expression,
you can loose the braces, return statement and semicolon
returnLength = (string text) => text.Length

Compiler can guess type of input arguments,
so you can loose it
returnLength = (text) => text.Length

If there is single input argument,
you can loose the parentheses
returnLength = text => text.Length
Let's recap
Func<string, int> returnLength = new Func<string, int>(GetLength);
returnLength(text);

Func<string, int> returnLength = GetLength;
returnLength(text);

returnLength = delegate (string text) { return text.Length; };

returnLength = (string text) => { return text.Length; };

returnLength = text => text.Length;
Real-life lamba example - Where
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
if (source == null || predicate == null)
{
throw new ArgumentNullExcpetion();
}
foreach (T item in source)
{
if (predicate(item))
{
yield return item;
}
}
}

// Usage:
var items = new List<string> { "John", "Tom", "Mike" };
var filteredItems = items.Where(i => i.StartsWith("J"));
Real-life lambdas in action
Q & A?
Thank you!

Contenu connexe

Tendances (20)

Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Generics C#
Generics C#Generics C#
Generics C#
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Constructor
ConstructorConstructor
Constructor
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Php forms
Php formsPhp forms
Php forms
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
class and objects
class and objectsclass and objects
class and objects
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Data and time
Data and timeData and time
Data and time
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

En vedette

Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneFilip Ekberg
 
Async in .NET
Async in .NETAsync in .NET
Async in .NETRTigger
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitSpiffy
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 

En vedette (7)

Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in Melbourne
 
Async in .NET
Async in .NETAsync in .NET
Async in .NET
 
CTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & AwaitCTU June 2011 - C# 5.0 - ASYNC & Await
CTU June 2011 - C# 5.0 - ASYNC & Await
 
Async/Await
Async/AwaitAsync/Await
Async/Await
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
C sharp
C sharpC sharp
C sharp
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

Similaire à Evolution of C# delegates

C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambaryoyomay93
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181Mahmoud Samir Fayed
 
Software Craftsmanship - 2
Software Craftsmanship - 2Software Craftsmanship - 2
Software Craftsmanship - 2Uri Lavi
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and eventsPrem Kumar Badri
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Managementpritamkumar
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
C++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and StringsC++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and StringsMohammad Shaker
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Rara Ariesta
 
Simulation Tool - Plugin Development
Simulation Tool - Plugin DevelopmentSimulation Tool - Plugin Development
Simulation Tool - Plugin DevelopmentFrank Bergmann
 

Similaire à Evolution of C# delegates (20)

C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Akka
AkkaAkka
Akka
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Lesson11
Lesson11Lesson11
Lesson11
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181
 
Software Craftsmanship - 2
Software Craftsmanship - 2Software Craftsmanship - 2
Software Craftsmanship - 2
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and events
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Management
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Java scriptfunction
Java scriptfunctionJava scriptfunction
Java scriptfunction
 
C++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and StringsC++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and Strings
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)
 
Dlr
DlrDlr
Dlr
 
Simulation Tool - Plugin Development
Simulation Tool - Plugin DevelopmentSimulation Tool - Plugin Development
Simulation Tool - Plugin Development
 

Dernier

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Dernier (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Evolution of C# delegates

  • 1. Evolution of C# delegates Marko Barić Senior software engineer @ Siemens CVC marko.baric@siemens.com
  • 2. Agenda • Basic delegates • • • • • • • Delegate types, delegate instances Combining multiple delegates Method group conversions Covariance and contravariance Inline delegate actions Captured variables (closures) Lambda expressions
  • 3. What is a delegate? • • • • Provide a level of indirection Sort of "sigle method interface" Delegates inhert from System.Delegate To create and use delegates: • • • • The delegate type needs to be declared The code to be executed must be contained in a method A delegate instance must be created The delegate instance must be invoked
  • 4. Declaring delegate types delegate void StringProcessor(string input); keyword return type delegate type name arguments
  • 5. Creating delegate instances class MyClass { public void SomeMethod(string input) public static void SomeMethodStatic(string input) } StringProcessor p1 = new StringProcessor(myClassInstance.SomeMethod); delegate instance variable delegate type action to invoke on MyClass instance StringProcessor p2 = new StringProcessor(MyClass.SomeMethod); static action to invoke on MyClass
  • 6. Invoking delegates StringProcessor p1 = new StringProcessor(myClassInstance.SomeMethod); p1.Invoke("Some string"); // ...or shorter version p1("Some string"); p1("Some string"); p1.Invoke("Some string") SomeMethod("Some string") • Delegates can be treated like any other type • They have methods, multiple instance can be created...
  • 7. Example delegate void StringProcessor(string input); class Person { private string name; public Person(string name) { this.name = name; } public void SayTheMessage(string message) { Console.WriteLine("{0} says: {1}", name, message); } public static void SayTheMessageStatic(string message) { Console.WriteLine(message); } } static void Main(string[] args) { Person john = new Person("John"); Person tom = new Person("Tom"); // Result: "John says: Hello!" "Tom says: Hello!" "Just saying something..." StringProcessor johnsVoice = new StringProcessor(john.SayTheMessage); StringProcessor tomsVoice = new StringProcessor(tom.SayTheMessage); StringProcessor someonesVoice = new StringProcessor(Person.SayTheMessageStatic); johnsVoice("Hello!"); tomsVoice.Invoke("Hello!"); someonesVoice("Just saying something..."); }
  • 8. Combining the delegates • All delegates inherit methods from System.Delegate: • • Delegate.Combine() Delegate.Remove() • Every delegate has an invocation list - a list of actions to invoke • "+", "+=", "-", "-=" • When delegate is invoked, all actions in the invocation list are invoked in the order they were added
  • 9. Example of combining delegates Person john = new Person("John"); Person tom = new Person("Tom"); Person mike = new Person("Mike"); StringProcessor johnsVoice = new StringProcessor(john.SayTheMessage); StringProcessor tomsVoice = new StringProcessor(tom.SayTheMessage); StringProcessor mikesVoice = new StringProcessor(mike.SayTheMessage); StringProcessor twoCombined = johnsVoice + tomsVoice; StringProcessor allCombined = twoCombined + mikesVoice; allCombined += new StringProcessor(john.SayTheMessage); allCombined("What's up!"); // Result: "John says: What's up!" "Tom says: What's up!" "Mike says: What's up!" "John says: What's up!"
  • 10. Method group converions //Delegate type delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e); //Target action void LogKeyEvent(object sender, KeyPressEventArgs e) { /* do something */ } void LogKeyEvent(int x) { /* do something */ } button.KeyPress += new KeyPressEventHandler(LogKeyEvent); button.KeyPress += LogKeyEvent; Method group is converted to compatible delegate type
  • 11. Contravariance of delegates Click -----> void EventHandler(object sender, EventArgs e) KeyPress -----> void KeyPressEventHandler(object sender, KeyPressEventArgs e) MouseClick ---> void MouseClickEventHandler(object sender, MouseEventArgs e) Button button = new Button(); button.Text = "Click me"; button.Click += LogPlainEvent; button.KeyPress += LogPlainEvent; button.MouseClick += LogPlainEvent; Same action for 3 different delegates! Form form = new Form(); form.Controls.Add(button); Application.Run(form); static void LogEvent(object sender, EventArgs e) { Console.WriteLine("An event occurred"); }
  • 12. Covariance of delegates delegate Stream MyDelegate(); Stream static MemoryStream GenerateSampleData() { byte[] buffer = new byte[16]; return new MemoryStream(buffer); } MyDelegate d = GenerateSampleData(); Stream stream = d(); MemoryStream stream = d(); MemoryStream
  • 13. Built-in delegate types in .NET delegate void Action<T>(T arg); delegate void Action<T1, T2>(T1 arg1, T2 arg2); ... delegate TResult Func<T, TResult>(T arg); delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); ... delegate bool Predicate<T>(T arg); ...
  • 14. Inline delegate actions • You don't need action method to exist you can create it inline Action<int> printRoot = delegate(int number) { Console.WriteLine(Math.Sqrt(number)); }; printRoot(9); Invoke it like other delegates Func<string, int> getLength = delegate(string input) { return input.Length; }; int length = getLength("Some string");
  • 15. Ingnoring inline delegate arguments • When you won't use delegate arguments you can loose them in definition button.Click += delegate(object sender, EventArgs e) { ... }; Button button = new Button(); button.Text = "Click me"; button.Click += delegate { Console.WriteLine("Click"); }; button.KeyPress += delegate { Console.WriteLine("KeyPress"); }; button.MouseClick += delegate { Console.WriteLine("MouseClick"); };
  • 16. Ingnoring inline delegate arguments • Beware of the compiler limitations: // Thread class has several different constructors public Thread(ThreadStart start) public Thread(ParameterizedThreadStart start) // There are 2 types of delegates involved public delegate void ThreadStart() public delegate void ParameterizedThreadStart(object obj) new Thread(delegate() { Console.WriteLine("Something..."); } ); new Thread(delegate(object o) { Console.WriteLine("Something..."); } ); new Thread(delegate { Console.WriteLine("Something..."); } );
  • 17. Captured variables (closures) • Captured variables are outer variables used (captured) in the scope of anonymous method void EnclosingMethod() { string outerVariable = "Default string"; Action<int> a = delegate() { string localVariable = outerVariable; }; a(); }
  • 18. Captured variables delegate void MyDelegate(); string captured = "before x is created"; MyDelegate x = delegate { Console.WriteLine(captured); captured = "changed by x"; }; captured = "before x is invoked"; x(); Console.WriteLine(captured); captured = "before second invocation"; x(); // Result: "before x is invoked" "changed by x" "before second invocation" The captured variable is the same one that the outer code uses!!!
  • 19. Lifetime of captured variables • A captured variable lives for at least as long as any delegate instance referring to it MethodInvoker CreateDelegateInstance() public { int counter = 5; MethodInvoker increment = delegate { Console.WriteLine(counter); counter++; }; increment(); return counter; } ... MethodInvoker x = CreateDelegateInstance(); x(); x();
  • 20. Things can get tricky very fast MethodInvoker[] invokers = new MethodInvoker[2]; int outsideVariable = 0; for (int i=0; i<2; i++) { int insideVariable = 0; invokers[i] = delegate { Console.WriteLine ("({0},{1})", outsideVariable, insideVariable); outsideVariable++; insideVariable++; }; } MethodInvoker first = invokers[0]; // Result: MethodInvoker second = invokers[1]; (0,0) first(); first(); first(); second(); second(); (1,1) (2,2) (3,0) (4,1)
  • 21. Lambda expressions • They are evolution of anonymous methods • More readable and compact than other delegate forms • Many shortcuts and "syntatic sugar" tricks allow most compat form of code • Brings new operator "=>" (spelled as "goes to")
  • 22. Simple lambda expression delegate TResult Func<T, TResult>(T input); Func<string, int> returnLength; returnLength = delegate (string text) { return text.Length; }; (list of input arguments) => { statements } returnLength = (string text) => { return text.Length; }; input arguments statements
  • 23. Shortening the lambdas returnLength = (string text) => { return text.Length; } If the statement is single expression, you can loose the braces, return statement and semicolon returnLength = (string text) => text.Length Compiler can guess type of input arguments, so you can loose it returnLength = (text) => text.Length If there is single input argument, you can loose the parentheses returnLength = text => text.Length
  • 24. Let's recap Func<string, int> returnLength = new Func<string, int>(GetLength); returnLength(text); Func<string, int> returnLength = GetLength; returnLength(text); returnLength = delegate (string text) { return text.Length; }; returnLength = (string text) => { return text.Length; }; returnLength = text => text.Length;
  • 25. Real-life lamba example - Where public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { if (source == null || predicate == null) { throw new ArgumentNullExcpetion(); } foreach (T item in source) { if (predicate(item)) { yield return item; } } } // Usage: var items = new List<string> { "John", "Tom", "Mike" }; var filteredItems = items.Where(i => i.StartsWith("J"));

Notes de l'éditeur

  1. - Delegate instanca će onemogućiti da garbage collector očisti njen target dok kod je ona živa. Ovo može stvoriti neželjeni memory leak jer će long-lived objekt (u našem slučaju instanca delegata) držati na životu short-lived objekt (u našem slučaju target)