C#: Func<> instead of methods? [duplicate] - c#

This question already has answers here:
Func Delegate vs Function
(6 answers)
Closed 9 years ago.
This is a curiosity questions for you all in the know:
Is there any harm/downside to using a Func instead of a method? Simple example:
private static Func<int, int, DBContext, List<T>> Foo =
(i1, i2, dbc) =>
(i1 != 0) ? dbc.Bar(i2) : new List<T> { /*some default values ...*/ };
Vs
private static List<T> Foo(int i1, int i2, DBContext dbc)
{
return i1 != 0 ? dbc.Bar(i2) : new List<T> { /*some default values ...*/ };
}

I see severale downsides:
performance impact (delegate vs method) - small but it's there
no parameternames (hurts readability on calls)
the definition itself is less readable
no overload possible (thanks to xanatos)
as you gain nothing I would only to so in a local and small context and prefer the static method

Performance is not as much of an argument as it would seem originally, the cost of invoking a delegate and a method that is dispatched through the v_table (virtual instance methods) are comparable. In this case, for a static Method it is likely there is a small performance gain for not using the delegate.
The "trick" you discovered here is a fairly common technique to achieve functional decomposition without resorting to object-oriented programming techniques (e.g. the Strategy Pattern). You replace a method call with a call to a delegate. Another nice aspect of this trick is that the syntax for invocation is the same.
However, I would be extremely careful applying this technique. What I do usually use it for is to avoid Interfaces with a single method, that do not have more than one or two parameters (else I would consider using a Parameter Object or using an interface).
C# is a multi-paradigm language, and using each paradigm has its place. Functional paradigms (such as using Funcs instead of compile-time known methods) have their place, as do object oriented paradigms. In your case, there is no benefit over using a Func<>, you should use a traditional method for clarity instead.

In the first case (with Func), you're not writing a method, but a variable Foo that you initialize with a specific delegate. You have one level of indirection that you can use to change what Foo points to. To simplify your example:
public static class Test {
public static Func<int, int, int> Foo =
(i1, i2) =>
i1 + i2;
public static int Foo2(int i1, int i2)
{
return i1 + i2;
}
}
let's test:
int a = Test.Foo(2,3);
int b = Test.Foo2(2,3);
Console.WriteLine("{0}, {1}",a,b); // 5, 5, all seems good, they're both sums
//... but wait... now you can do this:
Test.Foo = (x,y) => x * y; //reassigning Foo
int c = Test.Foo(2,3);
Console.WriteLine("{0}",c); // 6
so, if you are usign this level of indirection, the Func approach makes sense. But if you're not using it, you have introduced one level of indirection too many, with impact on performance, on how well your code communicates its intent and on the correctness of your program (since your method can now be switched for another that does something different at runtime)

ideally you wouldnt wanna create a Func if there is just going to be one definition of it always.. you are unnecessarily increasing the complexity and readability of the code and thus affecting the maintainability..
if you have strong reasons to use it like you create Func dynamically based on certain conditions then using Func<> is justified..
Also take a look at Action. here is a blog that I read to explain when to use what: http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/

From the "learning book" perspective it should be the same, but
small performance impact, because lambdas/delegates are little-bit slower than methods
parameters have generic names (e.g. arg1, arg2)
Intellisense is generally not able to provide documentation tooltips
Methods defined as lambda fields cannot introduce new generic parameters
readability impact

Apart from the readablity downgrade I don't think there's any other harm. Not sure about how the code compiles, but on the first version you are just defining the function using a delegate. I suppose you could also do the following:
private static List<T> Foo(int i1, int i2, DBContext dbc)
{
i1 != 0 ? return dbc.Bar(i2) : return new List<T> { /*some default values ...*/ };
}
private static Func<int, int, DBContext, List<T>> Foo2 = Foo;

Related

What are delegates for? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the advantages of delegates?
I have created a sample application. I am really finding it difficult to understand why to use delegates because without delegates we can achieve everything .
class Program
{
public delegate double Integrand(double x);
static double MyFunc1(double x) { return x + 10; }
static double MyFunc2(double x) { return x + 20; }
public static double Gauss3DelMethod(Integrand f)
{
double a = f(1);
return a;
}
public static double Gauss3SimpleMethod(double x)
{
double a = x;
return a;
}
static void Main(string[] args)
{
//with delegates
double res = Gauss3DelMethod(MyFunc1);
double res1 = Gauss3DelMethod(MyFunc2);
//without delegates
double res2 = Gauss3SimpleMethod(MyFunc1(1));
double res3 = Gauss3SimpleMethod(MyFunc2(1));
int i = 0;
}
}
So, why should I use delegates?
In your particular example, maybe it's not important. (It's not clear what it's trying to achieve.)
But suppose you wanted to make the method execute the same MyFunc1 or MyFunc2 for several different inputs. For example, suppose you were implementing the Newton-Raphson method, to operate over a general function. In that situation, you couldn't call the function once and pass that into the method - you want to pass the actual function into the method, so that the method can call it with whatever inputs it needs.
A similar example is sorting. For example, using LINQ you can write something like:
var sorted = people.OrderBy(x => x.Age).ToList();
There we're passing a function to project each source element to the ordering key. We don't have to execute that function ourselves - OrderBy will do it for us (lazily).
Of course, all of this can be done with single-method interfaces too - delegates and single-method interfaces have a lot in common. However, delegates have the following benefits over single-method interfaces:
Delegates are multi-cast - they can be combined/removed, usually for the sake of events
You can execute them asynchronously with BeginInvoke/EndInvoke
You can build them with anonymous methods and lambda expressions
You can represent logic as data via expression trees using lambda expresions; these can then be compiled into delegates
You can build a delegate from any method with the appropriate signature - so for example a single class can have multiple methods "implementing" the same delegate type, whereas you can't implement an interface multiple times in one class
Likewise delegate implementation methods can be private, whereas interface methods have to be public (or somewhat-public via explicit interface implementation)
All of these could have been addressed differently using single-method interfaces, of course, but delegates are a handy alternative.
In conclusion: delegates are very useful. Just because you've written some trivial code which doesn't particularly require them doesn't mean they're not useful. I would strongly suggest you look into LINQ, event handlers and the TPL, all of which use delegates heavily.
Delegates are a useful way to pass around functions.
Func and Action are also delegates. Without them you couldn't use almost every LINQ method and, beginning from C# 3.0, you can use Lambda Expressions to create them faster.
Imagine for example you have an enumerable of integers:
var numbers = Enumerable.Range(0, 100);
By using delegates you can create higher-order functions (http://en.wikipedia.org/wiki/Higher-order_function) that can help you to filter, for example, the numbers above in several ways. Where is one of the cases.
You may want to select just odd numbers:
var odd = numbers.Where(a => a % 2 == 0);
Or even ones:
var even = numbers.Where(a => a % 2 != 0);
Without them you would have to create a method for each filter (e.g. WhereOdd or WhereEven)

Are there already built in functional C#/.NET constructs like these? g(h()), or

public static Func<V> To<T, V>(this Func<T> g, Func<T, V> h)
{
return () => h(g());
}
public static Func<T> ToIdentity<T>(this T t)
{
return () => t;
}
I sometimes use these and others when delaying evaluation. Are these already in the .net library?
Edit:
Here is an example usage:
public static string SuffixColumn(this string v, string suffix, int columns)
{
return
v.ToIdentity()
.ToScrubbedHtml()
.ToFormat(() => "{0} " + suffix.ToLower().PadLeft(columns, ' '))
.ToErrorText(v, suffix, columns)();
}
ToErrorText checks 'v' as legitimate (non-error code, non-null, etc), if good it runs the chained in Func, if bad it produces fail-safe text result. If v, suffix, or columns are not good then ToFormat will never be called. (Hence the delayed/non-evaluated usage).
ToFormat is nearly the composition of the provided Func and string.Format. ToIdentity is used to lift v to a Func and then everything in the chain is based on some Func of T.
Let me see if I understand: you are using lambdas to capture values in a "wrapper" object -- a Func<T> -- and then build a workflow of lazily-evaluated functions around the wrapped object, yes?
Though building it out of functions works, I would personally be inclined to build the monad out of some custom type; it seems too easy to conflate functions that act on the monadic type or its "underlying" type with instances of the monad itself. You are basically building the identity monad using functions; I'd be more inclined to simply create a class or interface with a name that reflects the purpose to which you are putting the identity monad.
You might also consider renaming your methods. Your "To" is traditionally called "Bind" and your "ToIdentity" is traditionally called "Unit".
That is, a monad pattern for a monad type M<T> usually has the methods:
public static M<V> Bind<U, V>(this M<U> m, Func<U, M<V>> k)
and
public static M<T> Unit<T>(this T value)
The bind allows you to implement composition of functions on monads that are analogous to functions that compose on the "underlying" types of the monads.
For a gentle introduction to the marvels of monads in C#, see my erstwhile coworker Wes Dyer's great article on the subject:
http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx
To answer your actual question:
Are these already in the .net library?
Those exact functions are not in the framework. But functions very much like those exist in the framework. For example, SelectMany on IEnumerable<T> is analogous to your To method; it implements the monadic bind operation on sequences. new Nullable<int>(123) is analogous to your "ToIdentity" method; it implements the monadic unit operation for the "maybe monad". And so on.
The CLR type system is insufficiently rich to express the monad pattern in general; for that you need a "higher" type system, like that of Haskell. You'll have to build each specific monad yourself. However, it looks like you are well on your way.
Some more thoughts on using monads in C#-like languages:
Monads in C# -- why Bind implementations require passed function to return a monad?
Monad in plain English? (For the OOP programmer with no FP background)
Why there is no something like IMonad<T> in upcoming .NET 4.0
Help a C# developer understand: What is a monad?
You can use Lazy to lazy-load values.
Lazy<int> lazy = new Lazy<int>(() => delayEvaluatingMe());
int delayed = lazy.Value;

Creating two delegate instances to the same anonymous method are not equal

Consider the following example code:
static void Main(string[] args)
{
bool same = CreateDelegate(1) == CreateDelegate(1);
}
private static Action CreateDelegate(int x)
{
return delegate { int z = x; };
}
You would imagine that the two delegate instances would compare to be equal, just as they would when using the good old named method approach (new Action(MyMethod)). They do not compare to be equal because the .NET Framework provides a hidden closure instance per delegate instance. Since those two delegate instances each have their Target properties set to their individual hidden instance, they do not compare. One possible solution is for the generated IL for an anonymous method to store the current instance (this pointer) in the target of the delegate. This will allow the delegates to compare correctly, and also helps from a debugger standpoint since you will see your class being the target, instead of a hidden class.
You can read more about this issue in the bug I submitted to Microsoft. The bug report also gives an example of why we are using this functionality, and why we feel it should be changed. If you feel this to be an issue as well, please help support it by providing rating and validation.
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=489518
Can you see any possible reason why the functionality should not be changed? Do you feel this was the best course of action to get the issue resolved, or do you recommend that I should take a different route?
I'm not so inclined to think this is a "bug". It appears moreover that you're assuming some behaviour in the CLR that simply does not exist.
The important thing to understand here is that you are returning a new anonymous method (and initialising a new closure class) each time you call the CreateDelegate method. It seems that you are experting the delegate keyword to use some sort of pool for anonymous methods internally. The CLR certainly does not do this. A delegate to the anonymous method (as with a lambda expression) is created in memory each time you call the method, and since the equality operator does of course compare references in this situation, it is the expected result to return false.
Although your suggested behaviour may have some benefits in certain contexts, it would probably be quite complicated to implement, and would more likely lead to unpredictable scenarios. I think the current behaviour of generating a new anonymous method and delegate on each call is the right one, and I suspect this is the feedback you will get on Microsoft Connect as well.
If you are quite insistent on having the behaviour you described in your question, there is always the option of memoizing your CreateDelegate function, which would insure that the same delegate is returned each time for the same parameters. Indeed, because this is so easy to implement, it is probably one of the several reasons why Microsoft did not consider implementing it in the CLR.
EDIT: Old answer left for historical value below the line...
The CLR would have to work out the cases in which the hidden classes could be considered equal, taking into account anything that could be done with the captured variables.
In this particular case, the captured variable (x) isn't changed either within the delegate or in the capturing context - but I'd rather the language didn't require this sort of complexity of analysis. The more complicated the language is, the harder it is to understand. It would have to distinguish between this case and the one below, where the captured variable's value is changed on each invocation - there, it makes a great deal of difference which delegate you call; they are in no way equal.
I think it's entirely sensible that this already-complex situation (closures are frequently misunderstood) doesn't try to be too "clever" and work out potential equality.
IMO, you should definitely take a different route. These are conceptually independent instances of Action. Faking it by coercing the delegate targets is a horrible hack IMO.
The problem is that you're capturing the value of x in a generated class. The two x variables are independent, so they're unequal delegates. Here's an example demonstrating the independence:
using System;
class Test
{
static void Main(string[] args)
{
Action first = CreateDelegate(1);
Action second = CreateDelegate(1);
first();
first();
first();
first();
second();
second();
}
private static Action CreateDelegate(int x)
{
return delegate
{
Console.WriteLine(x);
x++;
};
}
}
Output:
1
2
3
4
1
2
EDIT: To look at it another way, your original program was the equivalent of:
using System;
class Test
{
static void Main(string[] args)
{
bool same = CreateDelegate(1) == CreateDelegate(1);
}
private static Action CreateDelegate(int x)
{
return new NestedClass(x).ActionMethod;
}
private class Nested
{
private int x;
internal Nested(int x)
{
this.x = x;
}
internal ActionMethod()
{
int z = x;
}
}
}
As you can tell, two separate instances of Nested will be created, and they will be the targets for the two delegates. They are unequal, so the delegates are unequal too.
I don't know about the C# specific details of this problem but I worked on the VB.Net equivalent feature which has the same behavior.
The bottom line is this behavior is "By Design" for the following reasons
The first is that in this scenario a closure is unavoidable. You have used a piece of local data within an anonymous method and hence a closure is necessary to capture the state. Every call to this method must create a new closure for a number of reasons. Therefore each delegate will point to an instance method on that closure.
Under the hood a anonymous method / expression is represented by a System.MulticastDelegate derived instance in code. If you look at the Equals method of this class you will notice 2 important details
It is sealed so there is no way for a derived delegate to change the equals behavior
Part of the Equals method does a reference comparison on the objects
This makes it impossible for 2 lambda expressions which are attached to different closures to compare as equals.
I can't think of a situation where I've ever needed to do that. If I need to compare delegates I always use named delegates, otherwise something like this would be possible:
MyObject.MyEvent += delegate { return x + y; };
MyObject.MyEvent -= delegate { return x + y; };
This example isn't great for demonstrating the issue, but I would imagine that there could be a situation where allowing this could break existing code that was designed with the expectation that this is not allowed.
I'm sure there are internal implementation details that also make this a bad idea, but I don't know exactly how anonymous methods are implemented internally.
This behaviour makes sense because otherwise anonymous methods would get mixed up (if they had the same name, given the same body).
You could change your code to this:
static void Main(){
bool same = CreateDelegate(1) == CreateDelegate(1);
}
static Action<int> action = (x) => { int z = x; };
private static Action<int> CreateDelegate(int x){
return action;
}
Or, preferably, since that's a bad way to use it (plus you were comparing the result, and Action doesn't have a return value ... use Func<...> if you want to return a value):
static void Main(){
var action1 = action;
var action2 = action;
bool same = action1 == action2; // TRUE, of course
}
static Action<int> action = (x) => { int z = x; };

Functors when should I use them whats their intended use [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I Just can't seem to wrap my head around them.
As I understand it's dynamically adding logic to a class. Are classes within the framework prepared for this?
Why should I just extend the class and add the functionality to it in the extension. I would be globally accessible and afaik much easier to maintain.
I've Read there are 4 functor types:
Comparer
Closure
Predicate
Transformer
We should probably Handle each one of them.
p.s. is there something like it in vb?
So I can state I think that lambda expressions are functors. This clears up things for me a bit :) (hehe)
Lambda expressions are functors?
Anonymous functions are functors?
But I asked this question because I ran into another type of fucntors namely these ones:
delegate void FunctorDelegate(int value);
class Addition {
FunctorDelegate _delegate;
public Addition AddDelegate(FunctorDelegate deleg) {
_delegate += deleg;
return this;
}
public int AddAllElements(IList< int> list) {
int runningTotal = 0;
foreach( int value in list) {
runningTotal += value;
_delegate(value);
}
return runningTotal;
}
}
And then calling it with this:
int runningTotal = new Addition()
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 1) {
runningOddTotal += value;
}
}))
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 0) {
runningEvenTotal += value;
}
}))
.AddAllElements(list);
So no fancy lambda style things.
Now I have this example but it isn't at all clear why this is a "good" solution.
Are delegates (functors) used as lambda expressions or anonymous methods "in most cases" just there as a shortcut for the programmer? There are as far as I can see only a few cases where they're actually the prefered choice for a problem.
I think you're confusing terms from different languages. You seem to be using "Functor" in the C++ or Java sense, e.g. see the wikipedia page. In C++, it's an object of a class that overloads the function-call operator, so it can be used as a function but with state.
This is logically the same thing as a delegate bound to an instance method in C# (or any .NET language).
There are three ways to write such a thing. First, you can write an ordinary method, and then assign the name of the method to a delegate variable.
void MyMethod() { Console.WriteLine("Hi!"); }
void Foo()
{
Action a = MyMethod;
a();
}
Second, you can use anonymous method syntax, introduced in C# 2.0:
void Foo()
{
Action a = delegate { Console.WriteLine("Hi!"); }
a();
}
Thirdly, you can use lambda syntax, introduced in C# 3.0:
void Foo()
{
Action a = () => Console.WriteLine("Hi!");
a();
}
The advantage of the last two is that the body of the method can read and write local variables in the containing method.
The advantage of lambda syntax over anon-methods are that it is more succinct and it does type inference on parameters.
Update: The advantage of anon-methods (delegate keyword) over lambdas is that you can omit the parameters altogether if you don't need them:
// correct way using lambda
button.Click += (sender, eventArgs) => MessageBox.Show("Clicked!");
// compile error - wrong number of arguments
button.Click += () => MessageBox.Show("Clicked!");
// anon method, omitting arguments, works fine
button.Click += delegate { MessageBox.Show("Clicked!"); };
I know of only one situation where this is worth knowing, which is when initializing an event so that you don't have to check for null before firing it:
event EventHandler Birthday = delegate { };
Avoids a lot of nonsense elsewhere.
Finally, you mention that there are four kinds of functor. In fact there are an infinity of possibly delegate types, although some authors may have their favourites and there obviously will be some common patterns. An Action or Command takes no parameters and returns void, and a predicate takes an instance of some type and returns true or false.
In C# 3.0, you can whip up a delegate with up to four parameters of any types you like:
Func<string, int, double> f; // takes a string and an in, returns a double
Re: Updated Question
You ask (I think) if there are many use cases for lambdas. There are more than can possibly be listed!
You most often see them in the middle of larger expressions that operate on sequences (lists computed on-the-fly). Suppose I have a list of people, and I want a list of people exactly forty years old:
var exactlyForty = people.Where(person => person.Age == 40);
The Where method is an extension method on the IEnumerable<T> interface, where T in this case is some kind of Person class.
This is known in .NET as "Linq to Objects", but known elsewhere as pure functional programming on sequences or streams or "lazy" lists (all different names for the same thing).
In .NET terms, I think what you are describing is the Delegate - and it exists in all of .NET, not just C#.
I'm not sure that a "closure" would a "type" in the same was as a comparer/predicate/transformer, since in C# terms a closure is simply an implementation detail but can be any of those three.
In .NET, delegates are used in two main ways:
as the eventing mechanism
to provide functional-style programming
The first is important, but it sounds like you are more interested in the second. In reality, they operate much like single-method interfaces... consider:
List<int> vals = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenVals = vals.FindAll(i => i % 2 == 0); // predicate
List<string> valsAsStrings = vals.ConvertAll(i => i.ToString()); // transformer
// sort descending
vals.Sort((x, y) => y.CompareTo(x)); // comparer
A closure is more where we bring additional scope from outside the delegate into the delegate:
int max = int.Parse(Console.ReadLine()); // perhaps 6
List<int> limited = vals.FindAll(i => i <= max);
here the max is captured into the delegate as a closure.
Re "Are classes within the framework prepaired for this?" - many are, and LINQ goes a long way to allowing this even wider. LINQ provides extension methods over (for example) all of IEnumerable<T> - meaning that collections without delegate-based access aquire them for free:
int[] data = { 1,2,3,4,5,6,7,8,9 };
var oddData = data.Where( i => i % 2 == 1 );
var descending = data.OrderBy(i => -i);
var asStrings = data.Select(i => i.ToString());
Here the Where and OrderBy methods are LINQ extension methods that take delegates.
Interesting with terminology; my spontaneous interpretation of the term "Functor" was that it referred to anonymous methods. So that will be my take on it.
These are some of my typical uses:
Comparisons (usually for sorting a list):
List<int> ints = new List<int>();
ints.AddRange(new int[] { 9, 5, 7, 4, 3, 5, 3 });
ints.Sort(new Comparison<int>(delegate(int x, int y)
{
return x.CompareTo(y);
}));
// yes I am aware the ints.Sort() would yield the same result, but hey, it's just
// a conceptual code sample ;o)
// and the shorter .NET 3.5 version:
ints.Sort((x, y) =>
{
return x.CompareTo(y);
});
I will use this approach for comparisons, rather than having it in its own method an using a delegate for that method, in the cases where this particular sort happens in one place only. If it is likely that I will want to use the same comparison somewhere else, it gets to live in its own, reusable method.
Another of my fairly common uses is in unit testing, when the test relies on some event being raised. I have found that to be essential when unit testing workflows in Workflow Foundation:
WorkflowRuntime runtime = WorkflowHost.Runtime;
WorkflowInstance instance = runtime.CreateWorkflow(typeof(CreateFile));
EventHandler<WorkflowEventArgs> WorkflowIdledHandler = delegate(object sender, WorkflowEventArgs e)
{
// get the ICreateFileService instance from the runtime
ISomeWorkflowService service = WorkflowHost.Runtime.GetService<ISomeWorkflowService>();
// set the desired file content
service.DoSomeWork(instance.InstanceId, inputData);
};
// attach event handler
runtime.WorkflowIdled += WorkflowIdledHandler;
instance.Start();
// perform the test, and then detach the event handler
runtime.WorkflowIdled -= WorkflowIdledHandler;
In this case it is simpler to have the event handler declared as anonymous methods since it uses the instance variable that is defined in the unit test method scope. Had I intstead opted to implelment the event handler as its own separate method I would also need to figure out a way for it to pick up instance, probably by introducing a class level member, which would not seem like a perfect design in a unit test class.
There are more cases where I find this in my code, but they usually have one or two things in common:
I have no interest in referencing that piece of code from anywhere else than in that particular place.
The method needs access to data that would be out of the scope for a regular method
The real answer is that a functor is a type of mathematical object, and is "reified" by different languages in different ways. For example, suppose that you have a "container" object that stores a bunch of other objects of the same type. (For example, a set or array) Then, if your language had a method that let you 'map' over the container, so that you could call a method on each object in the container, then the container would be a functor.
In other words, a functor is a container with a method that lets you pass a method to its contained things.
Every language has its own way of doing this, and they sometimes conflate the usage. For example, C++ uses function pointers to represent the "passing in" of a method, and calls the function pointer a "functor." Delegates are just a handle on methods that you can pass in. You are using the terminology "incorrectly", just like C++ does.
Haskell gets it right. You declare that a type implements the functor interface, and then you get the mapping method.
Functions (like lambdas) are functors too, but it can be kind of hard to think of a function as a "container". In short, a function is a "container" around a return value, constructed in such a way that the return value (possibly) depends on the function's arguments.
I'm sure you mean Lambda Expressions. Those are Small Functions you can write very quickly, and they have the characteristic "=>" Operator. These are a new Feature of C# 3.0.
This Example will be a classic Transformer; to use one we need a delegate to define the signature for the Lambda Function.
delegate int Transformer(int i);
Now Declare a Lambda with this delegate:
Transformer sqr = x => x * x;
We can use it like a normal function:
Console.WriteLine(sqr(3)); //9
These are used in LINQ Queries a lot, for example to Sort (Comparer), to Search through (Predicate).
The book "C# Pocket Reference" (apart from beign the best around in my opinion, has a very good part on Lambdas. (ISBN 978-0-596-51922-3 )

C# and variable number of parameters

I tried the following code:
class Program: ProgParent
{
public int Max(params int[] op)
{
return 0;
}
public int Max(int i, params int[] op)
{
return 1;
}
public int Max(int i, int j, params int[] op)
{
return 2;
}
public static void Main(string[] args)
{
System.Console.WriteLine((new Program()).Max(5, 6, 7, 8));
System.Console.ReadKey();
}
}
It executes, and uses the most specific function available. But the compiler gives no warning or error about this. Why?
The C# language spec says:
When performing overload resolution, a method with a parameter array
may be applicable either in its normal form [i.e. passing an array] or
its expanded form [i.e. passing a variable number of parameters]. The
expanded form of a method is available only if the normal form of the
method is not available and only if a method with the same signature
as the expanded form is not already declared in the same type"
In a (slightly simplified) nutshell: If overload resolution is ambiguous, the compiler chooses the non-params overload.
I guess the reasons for that decision (instead of making code like yours illegal) include:
If your method has the signature: void fn(params object[] p), you want to have some way to call the "normal form" (by passing an object[]). So the compiler has to handle ambiguous cases anyway.
Creating a temporary array is a lot more expensive than a method call, so you might want to create non-params overloads with 1,2,3 parameters that behave the same but are more efficient. (like e.g. String.Format)
Ignoring the build errors (which I'm putting down to typos) - what warning would you expect or want? It is finding a matching overload and using it...
Strictly speaking, I can call different overloads - by passing arrays, but yes, the usage isn't entirely clear.
Without the multiple overloads with params, this pattern is used quite heavily in things like string.Concat etc (which underpins + for strings under the bonnet).

Categories