Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Delegates and Threads!

Tags:

c#

What exactly do I need delegates, and threads for?

like image 700
Kredns Avatar asked Nov 28 '22 12:11

Kredns


1 Answers

Delegates act as the logical (but safe) equivalent to function-pointers; they allow you to talk about an operation in an abstract way. The typical example of this is events, but I'm going to use a more "functional programming" example: searching in a list:

List<Person> people = ...
Person fred = people.Find( x => x.Name == "Fred");
Console.WriteLine(fred.Id);

The "lambda" here is essentially an instance of a delegate - a delegate of type Predicate<Person> - i.e. "given a person, is something true or false". Using delegates allows very flexible code - i.e. the List<T>.Find method can find all sorts of things based on the delegate that the caller passes in.

In this way, they act largely like a 1-method interface - but much more succinctly.

like image 164
Marc Gravell Avatar answered Dec 15 '22 03:12

Marc Gravell