Making Extension method Generic

Posted by Ian on Stack Overflow See other posts from Stack Overflow or by Ian
Published on 2010-06-12T14:35:57Z Indexed on 2010/06/12 14:42 UTC
Read the original article Hit count: 170

Filed under:

In this post there's a very interesting way of updating UI threads using a static extension method.

public static void InvokeIfRequired(this Control c, Action<Control> action)
{
    if(c.InvokeRequired)
    {
        c.Invoke(() => action(c));
    }
    else
    {
        action(c);
    }
}

What I want to do, is to make a generic version, so I'm not constrained by a control. This would allow me to do the following for example (because I'm no longer constrained to just being a Control)

this.progressBar1.InvokeIfRequired(pb => pb.Value = e.Progress);

I've tried the following:

  public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
    {
        if (c.InvokeRequired)
        {
            c.Invoke(() => action(c));
        }
        else
        {
            action(c);
        }
    }

But I get the following error that I'm not sure how to fix. Anyone any suggestions?

Error 5 Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

© Stack Overflow or respective owner

Related posts about c#3.0