mgroves

Bring in the noise, bring in the Func (and Action)

Action and Func are kinda like pointers to methods. I've been using these a lot in a little pet project of mine, and I just wanted to share how awesome they are. They can be passed around, put into a collection, and invoked multiple times. Action (and Action<T> and Action<T1,T2>, Action<T1,T2,T3>) can 'point' to a method that doesn't return anything (i.e. a 'void' method). Like so:

    public class Class1
{
public void SomeMethod()
{
// do stuff
}

public void Example()
{
Action a = SomeMethod;
a.Invoke();
}
}

It's a silly example, but "a.Invoke();" is the same as just using "SomeMethod();" Similarly, if SomeMethod had a parameter (or two or three), then you could do this:

    public class Class1
{
public void SomeMethod(int a, string b)
{
// do stuff
}

public void Example()
{
Action<int,string> a = SomeMethod;
a.Invoke(1,"stuff");
}
}

So far, so awesome. Func is the same thing, except it 'points' to a method that can return something. Behold:

    public class Class1
{
public double SomeMethod(int a, string b)
{
// do stuff
return 0.0;
}

public void Example()
{
Func<int,string,double> f = SomeMethod;
double d = f.Invoke(5, "stuff");
}
}

Note that the 'result' type goes in the last slot in the Func: Func<param1,param2,result>. That seems backwards to me, but oh well. Now mix in some lambas for anonymous action:

        public void Example()
{
Action a = () => {
// do stuff
};
a.Invoke();
}

Now you create anonymous methods, stick them in a list, or a stack, or something, and go through and invoke them (or not invoke them) as you like.

These are contrived examples that aren't very useful. What I'm using them for is returning a collection of private methods, depending on various conditions. The user can then pick which one(s) to use from that list. The ones the user picks get placed into a stack and then invoked in LIFO order (this is part of a game).

Anyway, I think Action and Func are really cool parts of C#.

1 Response to Bring in the noise, bring in the Func (and Action) Article comments Feed

1

Craig Stuntz of http://blogs.teamb.com/craigstuntz/

I think it's clearer to just write:

a();

...instead of:

a.Invoke();

They do the same thing.

Posted at January 28, 2010 on 10:49am

Write a response

Play nice. Be constructive. Allowed HTML tags are: <a>, <strong>, <em> and <blockquote>

« Project Euler 5, 6, … I'm playing with Win… »