65.9K
CodeProject is changing. Read more.
Home

The Power of the 'Action' Delegate

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.87/5 (15 votes)

Mar 4, 2008

CPOL

2 min read

viewsIcon

42743

downloadIcon

165

Overview and test library of how powerful the System.Action delegate can be

Introduction

For a few weeks now, I've been trying to think of a reasonable way to code a single function that would accept a delegate to any function, without having to write 23 or more overloads. And to make it look... clean and consistent across any function being passed. Zero boxing overhead is a must.

So obviously I must have found a way, otherwise I would still be pouring over the code (as well as my coke-a-cola). Simple, clean, and I even was able to write an asynchronous version of the function without any added complexity.

How It Works

First off - as you've probably realized from the title- this code cites the power of the Action delegate. So what about it? It is a delegate to a function without a return value or any parameters. And why does that make it special? Because you can basically cast any function to a standard System.Action delegate.

void Foo(Action method);

That looks sound but...

void Main()
{
    Foo(Blah);
}

void Blah(int index, int la) { }

... will generate an error. As you say, "Hey this guy said I could pass any method I wanted..." blah blah blah. Yes but you need to do what I call 'lambda casting' to it first.

void Main()
{
    Foo(() => Blah(0, 34));
}

void Blah(int index, int la) { }

As you can see, you take an empty lambda declaring statement '()' followed by the operator '=>' and then just call the function as you normally would.

When Foo is executed, it will call the function just like you specified. This method works wonders for a profiler (like the sample library) however I am not sure about any other uses.

A Final Thought

With 'lambda casting' comes a very small amount of overhead. Invisible to most applications. I wouldn't suggest this for a game though. Too many of these and things might get ugly.

About The Sample Library

The included sample library is merely a heavily-documented example of using 'lambda casting'. If for any reason you do not understand my inane documentation styles, please feel free to leave a comment asking questions or send me an e-mail at Blobmiester@gmail.com.

History

  • 4th March, 2008: Original article submitted