User FAQs
1) What is a Delegate ?
A delegate represents a reference to a method that has a particular signature (parameter list and return type).
Delegates give you a way of calling a method at run-time.
When you instantiate a delegate you can associate its instance with any method with a matching signature.
Delegates are used to pass methods as arguments to other methods.
public delegate int MyDelegate(int x);
Examples include: type safe functions, pointers, callbacks.
2) Delegates with Named Methods
When you instantiate a delegate by using a named method, the method is passed as the parameter.
delegate int MyDelegate(int x);
void DoSomething(int a)
{ return a * a; }
MyDelegate del = DoSomething;
3) Delegates with Anonymous Methods
Introduced in C# 2.0 (.NET 2.0).
An anonymous method provides a way of passing a block of code as an argument instead of creating an explicit named method.
delegate int MyDelegate (int x);
MyDelegate del = delegate (int a)
{ return a * a; }
4) What is a Lambda Expression ?
Introduced in C# 3.0 (.NET 3.5).
A lambda expression is a more concise way of writing an anonymous function.
You specify the input parameters (if any) on the left of the lambda operator => and the statement block (or expression) on the right.
delegate int MyDelegate (int x);
MyDelegate del = a => a * a;
These are often used to create delegates for use in LINQ queries.
5) What is the difference between a Delegate and an Event ?
An event is something that can be added or removed from an object.
When you add or create an event you are storing a delegate reference which can then be called at run-time.
6) What is an Event ?
An event is an indication that a state is about to change or that a state has changed.
An event handler is a method that is invoked using a delegate.
button.click += delegate(System.Object o, _
System.EventArgs e)
{ MessageBox.Show("pressed"); };
7) What is a Multicast Delegate ?
A Delegate object holds a reference to a single method.
It is possible for a delegate object to hold references to multiple methods.
These delegates are called multicast or combinable delegates.
8) What is a Generic Delegate ?
There are three different types of generic delegate.
System.Action - can include 0 to 16 input parameters, no return type
??
System.Func - can include 0 to 16 input parameters and one return type
System.Func<string, string> MyDelegate = MyMethod;
public static string MyMethod(string inputstring)
{ return ""; }
System.Predicate - can verify a certain criteria and return a boolean value
9) Can you describe some situations when you would use Delegates ?
Callback Mechanism -
Asynchronous Processing -
Multi-Casting -
Abstract and Encapsulate Methods -
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext