Func’ ing hell

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

func.png

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

func2.png

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.

func3.png

And running this produces the following result

func4.png

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;};

Advertisements

2 thoughts on “Func’ ing hell

  1. Uwe says:

    Just a side node: Your feed URLs on the front page have that “feed://” prefix. At least my Google Reader does not understand.

    Possibly this is an error?

  2. Karl Shifflett says:

    Sacha,

    Very nice!! I need to get into VS2008 now that Mole v4 is out and about. Your teaching will go a long way towards getting me up to speed.

    So very sorry I missed you in NY. I was sleeping when you and Josh called. Mole had caught up to me!

    I’m hoping to come to the UK this summer and was thinking about stopping in Italy and Malta too.

    Cheers Mate! Best to you,

    Karl

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: