Delegates in C#
-Delegates are just function pointers, That is, they hold references to functions.
A Delegate is a class. When you create an instance of it, you pass in the function name (as a parameter for the delegate's constructor) to which this delegate will refer.
Use a delegate when
- An eventing design pattern is used.
- Easy composition is desired.
- It is desirable to encapsulate a static method.
Every delegate has a signature. For example:
Delegate int SomeDelegate(string s, bool b);
is a delegate declaration. When I say this delegate has a signature, I mean that it returns an int type and takes two parameters of type string and bool.
Consider the following function:
private int SomeFunction(string str, bool bln){...}
You can pass this function to SomeDelegate's constructor, because of their similar signatures.
SomeDelegate sd = new SomeDelegate(SomeFunction);
Now, sd refers to SomeFunction, in other words, SomeFunction is registered to sd. If you call sd, SomeFunction will be invoked. Keep in mind what I mean by registered functions. Later, we will refer to registered functions.
sd("somestring", true);
No comments:
Post a Comment
Comments Welcome