Anonymous methods
Date posted: 12/01/2014
You haven't filled in compulsory values.
The email is not correct
This time we are going to look into some interesting c# elements. That will be anonymous methods. Anonymous methods can help creating pieces of code organized as a method would but instead placing it right in the spot where you would call that method.
Anonymous methods
This article is where we talked about delegates. To sum things up we said that a delegate can be regarded as a pointer to a method. In other words we create a delegate, we pick a method which we assign to that delegate and from that moment on, using that delegate will be like using the method.
Could we make one more step and assign the delegate to the content of a method without the need for that method to exist? .Net 2.0 says we can. Anonymous types allow us to do so. What is an anonymous type? It is a type that needs not be declared in order to be used.
For example
var character = new { Name = "Ryuk", Race = "Shinigami" };
the character variable can be considered as having type equal to a class with parameters Name and Race.
Similarly, using an anonymous method is the same as using the commands that could have been placed within a method; however the method has never been declared.
To get to grips with what an anonymous method we'll do some web application trip. Supposing we create a simple HTML file and insert the following code.
<div>Click Me </div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div").click(function (event) {
alert("Wow! You just clicked a div.");
});
});
</script>
People familiar with jQuery will instantly realize that this code will create a simple div. When we click it we will get an alert message pointing that indeed, we clicked the div. If however you have never noticed how this thing works, focus on the following
$("div").click(function (event) {
alert("Wow! You just clicked a div.");
});
JavaScript does not a call an existing function. On the contrary it creates a function containing our alert command on the fly. The same thing applies to .NET.
Creating a delegate using an anonymous method is quite simple. The syntax can be seen below
Delegate d = delegate(arguments) { code };
The code part can contain whatever you wish, much like any other method. However the arguments part must match the delegate's arguments.
This a simple (and pointless) example where the anonymous method returns the input string. You may notice that the delegate and the anonymous method get the same arguments.
delegate string stringDelegate(string str);
//Anonymous method will return the input string
stringDelegate anonymousMethodDelegate = delegate(string outputText) { return outputText; };
string str = anonymousMethodDelegate("This is a string method.");
Anonymous methods can use more complex types as well. For example the following method will get a list of integers and return a list of strings.
delegate List<string> ListDelegate(List<int> intList);
//Anonymous method will return a list of strings
ListDelegate anonymousMethodDelegate = delegate(List<int> intList) {
List<string> stringList = new List<string>();
foreach(int i in intList)
stringList.Add(i.ToString());
return stringList;
};
List<string> strList = anonymousMethodDelegate(new List<int>(){1,2,3});
We also see that an anonymous method apart from complex types may contain complex code. However you should keep in mind that creating too complex anonymous methods, when we can avoid it, is not suggested as it may create hard to read code.
Now, if you are using .Net 4.5 or higher editions that may yet appear there's one more thing for you. The Func keyword allows you to create an anonymous method without an existing delegate
Look at the following example:
int GetMaxIntValue()
{
//This can't be used in .Net 4.0 or previous editions
//Gets the maximum value out of an integer list
Func<List<int>, int> anonymousMethod = delegate(List<int> intList) {
int maxValue = -1;
foreach (int i in intList)
if (i > maxValue)
maxValue = i;
return maxValue;
};
return anonymousMethod(new List<int>(){1,2,3});
}
The result will be 3.
Using Func<string, bool> anonymousMethod
we create the anonymous method anonymousMethod which gets a string argument and returns a bool value. Keep in mind that using the Func we need to use a return type. Returning void is not accepted.
Also keep in mind that anonymous methods on contrast to actual methods, can use local variables. We can rewrite the example like this
int GetMaxIntValueGreaterThanLocalInteger()
{
int minValue = 5;
//This can't be used in .Net 4 or previous editions
//Gets the maximum value out of an integer list which is greater than 5
Func<List<int>, int> anonymousMethod = delegate(List<int> intList) {
{
int maxValue = -1;
foreach (int i in intList)
if ((i > minValue) && (i > maxValue))
maxValue = i;
return maxValue;
};
return anonymousMethod(new List<int>() { 1, 2, 3 });
}
This time the result is -1.
That way we can avoid using global variables and adding extra arguments.
Here's a final example so we can compare using named to anonymous methods. Here is what we created last time using delegates
delegate void myDelegate(string str);
protected void Page_Load(object sender, EventArgs e)
{
//Attach WriteSthMethod while creating the writeSthDelegateObject delegate
myDelegate writeSthDelegateObject = new myDelegate(WriteSthMethod);
writeSthDelegateObject("Hello, I am a delegate");
}
void WriteSthMethod(string outputText)
{
OutputLit.Text += outputText;
}
and the output would be
Hello, I am a delegate
Using anonymous method
delegate void myDelegate(string str);
protected void Page_Load(object sender, EventArgs e)
{
//Let's use an anonymous method instead
myDelegate anonymousMethodDelegate = delegate(string outputText) { OutputLit.Text += outputText; };
anonymousMethodDelegate("Anonymous method used");
}
returning Anonymous method used much simpler.
Should I use anonymous methods?
Anonymous methods can help minimizing your source code. You can avoid adding extra methods and at the same time keep some straightforward direction in your code. Being a separate method, even though anonymous it may be, using anonymous methods you can still split your source code in parts (the way methods would do). Furthermore anonymous methods allow you to use local instead of creating new global variables.
However if you intend to use the same anonymous method more than once, creating an anonymous method is pointless. Not only do you use the same lines of code over and over, but you are also making things harder for future maintenance. You should just have to go the traditional way.
Of course what has been said doesn't mean that whenever you would create a method that would be called once, you should replace it with an anonymous one. Always try to create nice organized source code and use anonymous methods where you feel they would fit nicely.
Anonymous methods have evolved into lambda expressions since .NET 3.0. This will be the object of the next article.
Summary
Anonymous methods can be regarded as statements or commands that represent a method. However this method does not exist and it is created on the fly. An anonymous method can be used either as part of an existing delegate body or not, depending in the .NET version you are using. Anonymous methods can be used to make your code better if used properly, however if you do not pay attention things may end up in a different way.
Back to BlogPreviousNext