Ben said:
Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when and
why I would need to use it.
Can someone please shed some light on this subject?
Thanks a lot,
Ben
What you would actually return from the method would be a delegate.
Returning delegates from a method is not so common, but a delegate is a
type that can be used for the return value just like any other type.
Delegates are most commonly used by events, but they are also used in
other ways. The Array.Sort method for example has some overloads that
takes delegates, which is used to compare the items when they are sorted.
You can make a method that compares two strings in a special way:
public static int CompareIgnoreCase(string x, string y) {
return string.Compare(x, y, true);
}
Then you can use the name of the method to send a delegate to the Sort
method:
Array.Sort<string>(myStringArray, CompareIgnoreCase);
Or using an anonymous method:
Array.Sort<string>(myStringArray, delegate(string x, string y) { return
string.Compare(x, y, true); } );
Or even a lambda expression if you are using C# 3:
Array.Sort<string>(myStringArray, (x, y) => string.Compare(x, y, true));
To expand this in the direction of your original question, you could
have a method that returns different delegates depending on how you want
to sort:
public static Comparison<string> GetComparer(bool ignoreCase) {
if (ignoreCase) {
return delegate(string x, string y) {
return string.Compare(x, y, true);
};
} else {
return delegate(string x, string y) {
return string.Compare(x, y);
};
}
}
Calling the method would return a delegate, which you then can use in
the call to the Sort method:
Array.Sort<string>(myStringArray, GetComparer(true));
You can of course call the delegate directly also:
int result = GetComparer(true)("Peter", "Paul");
Or store it in a variable, and call it:
Comparison<string> comp = GetComparer(true);
int result = comp("Jack", "Jill");