When to use Anonymous delegates
When to use Anonymous delegates
Best needs: predicates / comparer
Hi
Ever wondered why anonymous delegates were created when we already had proper delegates?
In normal delegate, we write as follows
Public delegate MyDelegate (string s);
Public void MyFunction(string s) { Console.Write(s); }
Public static void main() {
MyDelegate del = new MyDelegate(MyFunction);
del("Nitin");
}
In Anonymous delegates, we write
Public static void main() {
MyDelegate del = delegate(string s) { Console.Write(s); }
del("Nitin");
}
Basically this is same as
String s = "Nitin"; // this happens in normal delegate
myFunction(s);
myFunction("Nitin"); // this happens in anonymous delegate
Now the difference
If we don't need to use the function outside of the delegate scope, we can safely use anonymous delegate and remove the explicit function. If we need the function directly also, then we need to declare the function and use either anonymous or normal delegate.
Comments
Post a Comment