10:30 PM - Late, very late to think , think and think. You know what I am planning to eat something. Very recently, my office work had kept me busy full day. So.....
Finally, I decide on to get some "Jamie Oliver" - The easiest sexiest salad in the world. I had two choices:
- Either, I can create this receipe in my dinning room, where I can bring all the ingredients required to prepare this. Though, the chances may be me forgotting to bring some ingredients in the dinning room.
- Or, I can go to kitchen and prepare this receipe there. So, that I need not to bring specific ingredients to dinning room and will save myself from shuffling between dinning room and kitchen. This may save my time too. :)
I decided to go with the second approach and believe me I was quite at ease preparing the salad there. In kitchen, I need not to worry about finding every ingredient in the first place..now.. I can get each on-demand.
Can I think something of this sort:
- Which provides me the freedom and ease to cook any functionality ?
- Breaking the signature barrier of a function pointer (delegate1)
- Decorating2 my existing functionality with extra functionality.
- or, help me grab some biscuits/chips while I am preparing "Jamie Oliver" :)
Before we go into understanding the details, let me give a walkthrough over delegates:
1 Delegate: Originally, people call it function pointer. But for me delegate is a [placeholder] for a specific method signature.
- Let's create a simple method.
- Create a simple delegate for the same "simple function".
- Consume the delegate.
public int AddMethod(int a, int b)
{
return a + b;
}
delegate int Add(int a, int b);
public void TryDelegates()
{
//C# 1.x way of calling method - Named Methods
Add addOld = AddMethod;
//Output will be 45
Console.WriteLine(addOld(20, 25));
}
Till here, we have created a delegate and consumed the same, successfully. Now, how do we get some chips/biscuits in the middle of the method, that too without interfering the AddMethod()?
We can always go ahead and create a different method which will contain the biscuits/chips to act as some pre/post processing. Something like below:
//Modified AddMethod which will decorate the existing AddMethod
//with extra processing instructions
public int ModifiedAddMethod(int a, int b, int affectMe, Add addDelegate)
{
return addDelegate(a, b) + affectMe;
}
Here is how our consume method looks like:
public void TryDelegates()
{
//C# 1.x way of calling method - Named Methods
Add addOld = AddMethod;
//Output will be 45
Console.WriteLine(addOld(20, 25));
int affectMe = 10;
//Call the decorated method
Console.WriteLine(ModifiedAddMethod(20, 25, affectMe, addOld));
}
You can easily figure out, this looks like too much for us to do - that too just for a very simple method enhancement. One of the drawback of this method is to - pass whatever variable we need to process it in ModifiedAddMethod() , along with the delegate. Here is what C# 2.0 has for you, "Anonymous Methods - reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method" (as per MSDN).
What the heck is "Anonymous Method"?
For me, this is a mechanism which we can use to provide "CODE BLOCK" for direct execution and save ourself from mapping the expected delegate.
To understand this better, in our scenario creating a seperate method just for accomodating a "simple functionality change", we can write the ModifiedAddMethod() inline in the TryDelegates(). Here is how our code looks:
public void TryDelegates()
{
int affectMe = 10;
//C# 2.0 way of calling method - Anonymous Method
Add addNew = delegate(int a, int b)
{
return a + b + affectMe;
};
Console.WriteLine(addNew(20, 25));
}
As one benefit can be clearly seen that we have reduced lines of code + code has gained more readability + No hassles of passing variables.
Hey look, this quite matches to the natural style of my cooking. :) Voila, the we can program now using our natural instincts. This looks like a good time to introduce "Closures", to my readers.
What is a closure?
Is a block of code that can be passed as an argument to a function call. A cool feature borrowed from the world of functional programming language (Lisp, etc.) . To know more about closures, you would like to meet this gentleman - "Fowler"
Conclusion
In today's story, I introduced you to "Anonymous Methods" a.k.a. inline methods - inline delegate's implementation (again a method). Scenarios for using this would be, when we need to add some pre/post/additional processing for calling delegates, this specially applies to when we go for breaking limits with "System Delegates - delegates provided by .NET Framework".
My next story will target using an "Anonymous Method" to exploit one of the .NET Framework provided delegates. Please leave your comments, because they help me writing what you are looking for.
UPDATE:
One of my readers, "RAJEEV" had a tough time understanding why we would like to chain 2 delegates using anonymous method / delegate.
Reason #1 Anonymous Delegate exists specially to be used in conjunction of various Framework Delegates i.e. Predicate Delegate, Convertor Delegate, Action Delegate, etc.
Reason #2 Whenever, you require to access local method's variables without altering the specific delegate we can use Anonymous Method and then execute that specific delegate.

3 comments:
public void TryDelegates()
{
int affectMe = 10;
//C# 2.0 way of calling method - Anonymous Method
Add addNew = delegate(int a, int b)
{
return a + b + affectMe;
};
Console.WriteLine(addNew(20, 25));
}
Why would i be intersted in rewriting the whole logic of function inside the anonymous method would it not make more sense to internally call the delegate within the the method and process it.
So here's what i was trying to explain earlier
static void Main(string[] args)
{
int affectMe = 10;
Add dlg = delegate(int a, int b)
{
Add innerDlg = AddMethod;
return innerDlg.Invoke(a, b) + affectMe;
};
Console.Write(dlg.Invoke(12, 23));
}
Though i am not aware of any side effect when we are tryin to chain the 2 delegates like this. Any comments ?
I have edited the post to clarify your thoughts.
Let me know, if that answers your question
Post a Comment