O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generic Delegates for Functions

The .NET Framework exposes a generic class called Func<T, TResult>, which you can read as “Func-of T and TResult.”

As with Predicate<T> and Action<T> the first type parameter determines the type of the first parameter of the function referenced by the delegate.

Unlike Predicate<T> or Action<T> we also get to specify the type of the return value, using the last type parameter: TResult.

Note

Just like Action<T>, there is a whole family of Func<> types which take one, two, three, and more parameters. Before .NET 4, Func<> went up to four parameters, but now goes all the way up to 16.

So we could replace our custom delegate type with a Func<>. We can delete the delegate declaration:

delegate string LogTextProvider(Document doc);

and update the property:

    public Func<Document,string> LogTextProvider
    {
        get;
        set;
    }

We can build and run without any changes to our client code because the new property declaration still expects a delegate for a function with the same signature. And we still get a bit of log text:

Processing document 1
The processing will not succeed.
Some text for the log...

Processing document 2
Document traduit.
Some text for the log...
Spellchecked document.
Some text for the log...
Repaginated document.
Some text for the log...
Highlighting 'millennium'
Some text for the log...

OK, let’s go back and have a look at that log function. As we noted earlier, it isn’t very useful right now. We can improve it by logging the name of the file we have processed ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required