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 Actions with Action<T>

Action<T> is a generic type for a delegate to a function that returns void, and takes a single parameter of some type T. We used a generic type before: the List<T> (List-of-T) where T represents the type of the objects that can be added to the list. In this case, we have an Action-of-T where T represents the type of the parameter for the function.

So, instead of declaring our own delegate:

delegate void DocumentProcess( Document doc );

we could just use an Action<> like this:

Action<Document>

Warning

A quick warning: although these are functionally equivalent, you cannot use an Action<Document> polymorphically as a DocumentProcess—they are, of course, different classes under the covers.

We’re choosing between an implementation that uses a type we’re declaring ourselves, or one supplied by the framework. Although there are sometimes good reasons for going your own way, it is usually best to take advantage of library code if it is an exact match for your requirement.

So, we can delete our own delegate definition, and update our DocumentProcessor to use an Action<Document> instead, as shown in Example 5-12.

Example 5-12. Modifying the processor to use the built-in Action<T> delegate type

class DocumentProcessor
{
    private readonly List<Action<Document>> processes =
        new List<Action<Document>>();

    public List<Action<Document>> Processes
    {
        get
        {
            return processes;
        }
    }

    public void Process(Document doc)
    {
        foreach (Action<Document> process in Processes) { process(doc); ...

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