tags:

views:

66

answers:

1

Is it possible to adapt a method like this function "F"

class C {
    public void F(int i);
}

to a delegate like Action<C,int>?

I have this vague recollection that Microsoft was working on supporting this kind of adaptation. But maybe I misremembered!

Edit: I know that this doesn't compile in VS2008:

class C {
    public void F(int i);
    void G() {
        Action<C, int> test = this.F;
    }
}

I was just wondering if MS provides a way to do this in the BCL, or if the feature would be added in a future version.

+2  A: 

The easiest way is probably to create a lambda which takes a C and an int, and calls F on the C, passing the int:

Action<C, int> test = (c, v) => c.F(v);

You can also create what's called an open delegate to the instance method C.F, as opposed to the usual type of delegate which is "closed over it's instance parameter". This would be done using reflection and the Delegate.CreateDelegate method. While that would result in a more 'direct' delegate, it is in all likelihood more complex than you require.

Wesley Hill
This "open delegate" is precisely what I wanted. The lambda solution isn't bad, but theoretically should be slower, and I wanted the maximum possible performance (I was generating code at run-time so avoiding the complexity of reflection would be impossible either way). Since this question wasn't answered for a long time, I ended up taking a very different approach than I initially envisioned.
Qwertie