Presentation is loading. Please wait.

Presentation is loading. Please wait.

IT College 2016, Andres käver

Similar presentations


Presentation on theme: "IT College 2016, Andres käver"— Presentation transcript:

1 IT College 2016, Andres käver http://enos.itcollege.ee/~akaver/csharp
C# - DELEGATES IT College 2016, Andres käver

2 C# - Delegates A delegate is a type that defines a method signature, and can provide a reference to any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods.

3 C# - Delegates Basic usage
public delegate void SampleDelegate(string str); class SampleClassDelegate { // Method that matches the SampleDelegate signature. public static void SampleMethod(string message) // Add code here. } // Method that instantiates the delegate. void SampleDelegate() SampleDelegate sd = SampleMethod; sd("Sample string");

4 C# - Delegates Declare delegate signature (new type)
delegate returntype DelegateMethod(arguments….) Declare delegate variable, assign suitable method to it DelegateMethod methodCall = SomeSuitableMehtod; Use methodCall in your code methodCall(parameters…)

5 C# - Func<…>, Action<…>
Func<parameterTypes0..32,TResult> To simplify code, don’t declare explicit new delegate – use Func Func<bool> methodCall = someMethodNoArguments; Func<int,bool> methodCall = someMehtodWithIntParameter; When method returns void, use Action<parameterTypes0..32>

6 C# - Delegates, Anonymous methods
You can use anonymous method with delegates Func<bool> methodCall = delegate() { return someMethod(); }; Func<int, bool> methodCall = delegate(int x) { return someMethod(x); };

7 C# - delegates, lambda expression
You can assign lambda expression to Func Func<bool> methodCall = () => SomeMehtod(); Func<int, bool> methodCall = (x) => SomeMethod(x);

8

9

10

11

12

13


Download ppt "IT College 2016, Andres käver"

Similar presentations


Ads by Google