0% found this document useful (0 votes)
140 views11 pages

C# 04 - Delegates Lambdas and Events

Delegates allow methods to be passed around and invoked later. Lambda expressions provide a concise syntax to define anonymous methods inline without declaring a name. Events provide a publisher-subscriber mechanism where classes can publish events to signal occurrences, and other classes can subscribe to events to be notified when they occur.

Uploaded by

Ateik Alzehla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views11 pages

C# 04 - Delegates Lambdas and Events

Delegates allow methods to be passed around and invoked later. Lambda expressions provide a concise syntax to define anonymous methods inline without declaring a name. Events provide a publisher-subscriber mechanism where classes can publish events to signal occurrences, and other classes can subscribe to events to be notified when they occur.

Uploaded by

Ateik Alzehla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11

C# 7 and .Net Core 2.

2
Delegates, Lambdas, and Events

Ateik Alzehla
Content

Delegates
Lambda expressions
Closures
Events
Delegates

 Delegates are the .NET variant of addresses to methods


 When you want to pass methods around to other methods?
 Declaring Delegates. delegate void MyDelegate(int x);

 Using Delegates
 Declaring a variable and instantiate it, same as class;
 Pass method as parameter to the delegate constructor;
 We can declare variable and assign a method to it without new keyword.
MyDelegate x= new MyDelegate(methodname);
 You can use the delegate variable
MyDelegate() or MyDelegate.Invoke()
Action<T> and Func<T> Delegates

They are delegates.

Instead of defining a new delegate type with every parameter and return type

The generic Action<T> delegate is meant to reference a method with void
return.
up to 16 different parameter types
The Action class without the generic parameter for void method()

The Func<T> delegates can be used in a similar manner.
But with a return parameter.
The return parameter is the last one
Multicast Delegates:

Delegates can call many methods in separate.
private delegate string GetAString();
string str = "Hello";
GetAString del = str.ToString;
del(); private delegate string GetAString();
del = ReadLine; string str = "Hello";
del(); GetAString del = str.ToString;
del += ReadLine;
del();

Call more than one method in one shot
If the methods has return we get only the result of the last one;
If one failed, the rest will not be invoked.
Multicast delegates recognize the operators + and +=
Action<double> operation1 = method1;
Action<double> operation2 = method2;
Action<double> operations = operation1 + operation2;
Anonymous Methods

is a block of code that is used as the parameter for the delegate.
The delegate Func<string, string>
 

class Program {
takes a single string parameter and static void Main()
returns a string. anonDel is a variable {
of this delegate type. Instead of string mid = ", middle part,";
assigning the name of a method to Func<string, string> anonDel = delegate (string param)
this variable, a simple block of code {
is used, prefixed by the delegate param += mid;
keyword, followed by a string param += " and this was added to the string.";
parameter. return param;
};
Console.WriteLine(anonDel("Start of string"));
}
}


We really don’t need this syntax anymore because lambda expression
Lambda Expressions:

Assign a lambda expression to a delegate type: implement code inline
class Program {
static void Main()
{
string mid = ", middle part,";
Func<string, string> anonDel = param =>
{
param += mid;
param += " and this was added to the string.";
return param;
};
Console.WriteLine(anonDel("Start of string"));
}
}


Closure: is accessing variables outside the block of the lambda expression
Lambda Expressions- Parameters:

Several ways to define parameters
If there’s only one parameter, just the name of the parameter is enough
Func<string, string> oneParam = s => $"change uppercase{s.ToUpper()}";
Console.WriteLine(oneParam("test"));

If a delegate uses more than one parameter, you can combine the parameter names inside brackets

Func<double, double, double> twoParams = (x, y) => x * y;


Console.WriteLine(twoParams(3, 2));

You can add the parameter types to the variable names inside the brackets

Single statement or multiple statements=> the using of {} or return;


Events:

Events are based on delegates and offer a publish/subscribe mechanism to
delegates. public event EventHandler<myEventArgs> SomethingHeppend;


Event Publisher: public class CarInfoEventArgs : EventArgs {
public CarInfoEventArgs(string car) => Car = car;
public string Car { get; }
}
public class CarDealer {
public event EventHandler<CarInfoEventArgs> NewCarInfo;
public void NewCar(string car) {
Console.WriteLine($"CarDealer, new car {car}");
NewCarInfo?.Invoke(this, new CarInfoEventArgs(car));
}
}
Events (Continued): public class Consumer
{
private string _name;

Event Listener: public Consumer(string name) => _name = name;
public void NewCarIsHere(object sender, CarInfoEventArgs e)
{
Console.WriteLine($"{_name}: car {e.Car} is new");
}
}

class Program {
static void Main() {
Now the event publisher

var dealer = new CarDealer();
var valtteri = new Consumer("Valtteri");
dealer.NewCarInfo += valtteri.NewCarIsHere;
and subscriber need to connect. dealer.NewCar("Williams");
var max = new Consumer("Max");
dealer.NewCarInfo += max.NewCarIsHere;
dealer.NewCar("Mercedes");
dealer.NewCarInfo -= valtteri.NewCarIsHere;
dealer.NewCar("Ferrari");
}
}
Any questions?

You might also like