I've recently been playing around with the delegate Func<T, TResult> and creating methods that return different instances Func<T, TResult> containing lambda but what I have struggled to come up with is any good real world ideas of why one might want to return (or even create such an instance).
There is an example on MSDN where they do the following...
Func<string, string> convertMethod = UppercaseString;
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
And although it looks pretty and is an interesting concept I fail to see what advantages such code provides.
So could someone here please provide any real world examples where they have had to use Func<T, TResult> and in general why one might want to use this delegate?
If what you're asking, really, is why we have delegates in general:
If you've ever consumed an event, you've used a delegate
If you've ever used LINQ, you've used a delegate (technically, with an IQueryable provider you've used an expression, but for LINQ-to-Objects you've used a delegate)
Delegates provide a way of injecting your own behavior into another object. The most common usage is with events. An object exposes an event and you provide a function (anonymous or not) that gets called when that event fires.
If you're asking why we have the Func<T, TResult> (and similar) delegate, then there are two main reasons:
People were having to declare their own simple delegate types when they needed a particular delegate in their code. While the Action<> and Func<> delegates can't cover all cases, they are simple to provide and cover many of the cases where custom delegates were needed.
More importantly, the Func<T, TResult> delegate is used extensively in LINQ-to-Objects to define predicates. More specifically, Func<T, bool>. This allows you to define a predicate that takes a strongly-typed member of an IEnumerable<T> and returns a boolean by using either a lambda or ordinary function, then pass that predicate to LINQ-to-Objects.
You would use it a lot in LINQ. So, for example, to double all the numbers in a list:
myList.Select(x => x * 2);
That's a Func<TIn, TOut>. It's quite useful when creating concise code. A real-world example is in one of the many tower-defence games I made, I calculated the closest enemy to the tower using one line:
enemies.Select(x => tower.Location.DistanceTo(x.Location)).OrderBy(x => x).FirstOrDefault();
I think a great example is lazy initialization.
var value = new Lazy<int>(() => ExpensiveOperation()); // Takes Func<T>
The canonical example of a need for a function pointer is for a comparison function to pass to a sort routine. In order to have different sort keys, you create a lambda for the comparison function, and pass that to the sort function.
Or for a simple real-world example:
IEnumerable<Person> FindByLastName(string lastName)
{
return Customers.Where(cust => cust.LastName == lastName);
}
In this example, cust => cust.LastName == lastName is not just a lambda, but it creates a closure by capturing the lastName parameter. In othe words, it creates a function, which will be different every time FindByLastName is called.
The Func<T> delegate (and other overloads) give you new ways for writing abstractions in C#. To demonstrate some of the options, here are a couple of C# langauge constructs that could be written using delegates instead:
Thread.Lock(obj, () => {
// Safely access 'obj' here
});
Enumerable.ForEach(collection, element => {
// Process 'element'
});
Exceptions.Try(() => {
// Try block
}).With((IOException e) => {
// Handle IO exceptions
});
These are quite primitive, so it is good to have a language construct for them. However, it demonstrates that Func and lambda expressions add quite a lot of expressive power. It makes it possible to write new constructs such as parallel loop (using .NET 4.0):
Parallel.ForEach(collection, element => {
// Process 'element'
});
First of all, Func<T> is not a class, it's a delegate.
Basically, you can use it whenever you need a method argument or a property of delegate type if you don't want to declare your own delegate for that.
One great use of Funct<T>, besides the fact that it is embedded in many frameworks such as LINQ, Mocking Tools, and Dependency Injection containers is to use it to create a delegate based factory.
Recently, I wanted the external program calling my method to be able to modify the way it behaves.
My method in itself simply converts a file from XLS to XML. But it was necessary to allow the calling code to specify if needed an arbitrary number of transformations which should apply to each xls cell before being writing as a xml tag. For example : convert the "," decimal separator to ".", suppress the thousand separator, and so on (the transformations were all string replacements).
Then the caller code just had to add an arbitrary number of entries in a dictionary where the key is the pattern and the value is the replacement string for this pattern. My method loops over the dictionary and creates a new Func<string,string> for each entry. Then for each cell the Func<string,string> are applied in sequence.
Related
I have created a little LINQ extension method that allows me to use a value for very small code without going through the hassle of declaring a local variable.
public static TReturn Do<TInput, TReturn>(this TInput input, Func<TInput, TReturn> func)
=> func(input);
I use it to inline slightly more expensive expressions that I only use in one place, such as:
var ImportantValue = MyDatabase.First(e => e.Id == 28131).Do(e =>
{
Console.WriteLine(e.Name);
MyOtherDatabase.Add(new Foo(e.FooParameter));
return e.ImportantValue;
});
This is useful as duplicating the MyDatabase.First(e => e.Id == 28131) statement would be a performance hit, and creating a local for it would just clutter up the scope needlessly, as it is only ever used in that one spot.
Furthermore this allows for using expression bodies in places where you usually would have to use a block statement, only to have it be two lines long.
However, I am not sure that the name Do is very descriptive or useful, and I can't think of any better names for this. As I am using this in more and more code, I would like to give it a proper, descriptive name.
A better name than Do is possibly Apply. But this extension method will be callable for all types of the .NET Framework, so it will clutter the intellisense list of everything. Being on the top of the list would be extra irritating, so I would be inclined to name it with something starting from X, Y or Z, to move it to the bottom. Personally I would prefer not to have an extension method like this at all.
I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps
I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps
I've read that it is usually bad practice to extend System.Object, which I do agree with.
I am curious, however, if the following would be considered a useful extension method, or is it still bad practice?
It is similar to extending System.Object but not exactly,
public static R InvokeFunc<T, R>(this T input, Func<T, R> func)
{
return func.Invoke(input);
}
This essentially allows any object to invoke any function that takes that object as a parameter and returns R, whether that function belongs to the object or not. I think this could facilitate some interesting 'inversion of control', but not sure about it overall.
Thoughts?
Well there are really two points here:
1) Whether it is a good idea to create an extension method with this T so it will be applied to all types?
2) Whether the particular extension method described is useful?
For the 1st question the answer is sometimes but depends on the context. You can have an extension method apply to all classes just like linq does ensuring that you pick an appropriate namespace. I would think creating this type of extension method within the System namespace a bad idea but if it were more targeted then perhaps it would be useful.
For the 2nd since the invoke is immediate then the choice of syntax is as follows
int res = other.InvokeFunc<Other, int>(Callback);
var res2 = (new Func<Other, int>(Callback))(other);
var res3 = Callback(other);
Looking at that then a simple call to the method passing the instance in is more natural and typical, however if your extension method becomes more elaborate then I go back to my first point on that it depends on the context (which could help with encapsulation).
All this does is that it gives you the ability to refer to a method as a parameter which is in fact what delegates already allow you in C#.
I don't see it being more useful (in case of IoC) than a delegate of type Func<T,R> in your case. It's just another way of invoking it.
UPDATE
As mentioned in the comments, I think this method only helps you in creating delegates more efficiently. But either way, you do not use the created delegate any further since you invoke it immediately. So an extension method like this would make more sense to me:
public static Func<R> InvokeFunc<T, R>(this T input, Func<T, R> func)
{
return () => func(input);
}
I discovered something very strange that I'm hoping to better understand.
var all = new List<int[]>{
new int[]{1,2,3},
new int[]{4,5,6},
new int[]{7,8,9}
};
all.ForEach(n => n.ForEach(i => Console.WriteLine(i)));
which can be rewritten as:
...
all.ForEach(n => n.ForEach(Console.WriteLine));
How is it possible to leave out the lambda expression parameter (i=>) and still have the current item passed to console.WriteLine?
Thanks for any insight.
-Keith
List<T>.ForEach is looking for an Action<T>. When you write
n.ForEach(Console.WriteLine);
what you have here is one of the members of the method group Console.WriteLine playing the role of an Action<T>. The compiler will look for the best overload of Console.WriteLine that eats instances of int. In fact, it will use the overload Console.WriteLine(int). It will then use this overload to play the role of an Action<int>.
For details on how this is done, see ยง6.6 of the specification (Method group conversions).
However, when you write
n.ForEach(i => Console.WriteLine(i));
we actually have a very different Action<int> In the first case, the Action<int> was Console.WriteLine(int). Here, the Action<int> is equivalent to you having written
public static void DoSomething(int i) {
Console.WriteLine(i);
}
and then
n.ForEach(DoSomething);
(Of course, the compiler has to go through the same method group process as described above to figure out what is meant by DoSomething).
The point is that in the first case the Action<int> is Console.WriteLine(int). However, in the second case the Action<int> is a middle man (the lambda expression) that itself will call Console.WriteLine(int).
This is less confusing if you consider what is really happening.
You are passing a method to a delegate argument. Most of the time, we think of delegates in the context of events, but they can be parameters to methods as well. It doesn't seem odd when a method is added to an event without arguments, it just is unusual looking when executed in this context.
Before lambdas, you had to do this all the time, and it was such a pain that one would never consider using a library that looked like LINQ. With Lambdas, this is easier to do, but you can always do the old way as well.