SlideShare a Scribd company logo
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!

More Related Content

What's hot

Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
Muthukumaran Subramanian
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdf
kumari36
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
Delegetes in c#
Delegetes in c#Delegetes in c#
Delegetes in c#
Mahbub Hasan
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul
 
QSpiders - Jdk Jvm Jre and Jit
QSpiders - Jdk Jvm Jre and JitQSpiders - Jdk Jvm Jre and Jit
QSpiders - Jdk Jvm Jre and Jit
Qspiders - Software Testing Training Institute
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
ParvizMirzayev2
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Madishetty Prathibha
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
jyoti_lakhani
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Call by value and call by reference in java
Call by value and call by reference in javaCall by value and call by reference in java
Call by value and call by reference in java
sunilchute1
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49myrajendra
 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#
yogita kachve
 
Java logging
Java loggingJava logging
Java logging
Jumping Bean
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaAbhilash Nair
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 

What's hot (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdf
 
Java Beans
Java BeansJava Beans
Java Beans
 
Java swing
Java swingJava swing
Java swing
 
Delegetes in c#
Delegetes in c#Delegetes in c#
Delegetes in c#
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
QSpiders - Jdk Jvm Jre and Jit
QSpiders - Jdk Jvm Jre and JitQSpiders - Jdk Jvm Jre and Jit
QSpiders - Jdk Jvm Jre and Jit
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Call by value and call by reference in java
Call by value and call by reference in javaCall by value and call by reference in java
Call by value and call by reference in java
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#
 
Java logging
Java loggingJava logging
Java logging
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Viewers also liked

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
Filip 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
 
Async/Await
Async/AwaitAsync/Await
Async/Await
Jeff Hart
 
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
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
C sharp
C sharpC sharp
C sharp
sanjay joshi
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
shubhra chauhan
 

Viewers also liked (9)

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# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
C sharp
C sharpC sharp
C sharp
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

Similar to 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
 
Akka
AkkaAkka
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
DEVCON
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj
 
Lesson11
Lesson11Lesson11
Lesson11
Alex Honcharuk
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
Michael Haberman
 
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 181
Mahmoud Samir Fayed
 
Software Craftsmanship - 2
Software Craftsmanship - 2Software Craftsmanship - 2
Software Craftsmanship - 2
Uri Lavi
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
Duong Thanh
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and events
Prem Kumar Badri
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Management
pritamkumar
 
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 Strings
Mohammad 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 Development
Frank Bergmann
 

Similar to 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
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 

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"));

Editor's Notes

  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)