Today I was looking at an article over at codeproject which used some lambda expression in conjunction with some of the inbuilt .NET delegates such as
Func<T,TResult> and
Func<TResult>
And this started me thinking, that all very well using these convenience delegates, but what if I want more parameters etc etc.
So I started to look into this a bit more. If we look at the object browser in VS2008 we can see that the following FUNC delegates exist
And if we look further at this in VS2008 by looking at one of these FUNC types, say FUNC<T,TResult> in VS2008 we can see the following
So Func<T,TResult> is just a short hand for a delegate declaration. Mmm. This means that we can create our own.
So lets have a look at that. Here is a screen shot of a simple console application where I’ve created my own delegate type.
And running this produces the following result
The important things to note here are as follows
- => is a lambda which is equivalent to an anonomous delegate being declared
- () => means that the lambda expression takes no input params
- (x) => means the lambda expression takes a parameter named x
- Func<bool> means the function takes 0 params but returns a bool. This maps on to the existing System.Func<TResult> type
- Func<int,bool> means the function takes an int param and returns a bool. This maps on to the existing System.Func<T,TResult> type
And we can create our own like
public delegate int SimpleReturn<T>(T input);
which we can use as follows
mySimpleReturn(20);
….
public static SimpleReturn<int> mySimpleReturn = (x) =>{
Console.WriteLine(“mySimpleReturn “ + x + ” * 2 “ + ” = “ + (x * 2).ToString());
return x * 2;};