1

How can I write an extension method for an existing method like :

static class Extensions { public static void RunAsThread(this Action func) { Thread t = new Thread(delegate() { try { if (func != null) func(); } catch (ThreadInterruptedException tie) { } catch (ThreadAbortException tae) { } catch (Exception ex) { Logger.LogDebug(ex); } }); t.Start(); } } 

is there any way that i can run this methods perfectly in the way i wanted

class WorkingClass { public void Work() { //Works fine ((Action)DoSomething).RunAsThread(); //Works fine Extensions.RunAsThread(DoSomething); //But I really need this to work DoSomething.RunAsThread(); } private void DoSomething() { //Do Something } } 

I really wanted to make DoSomething.RunAsThread() work. I tried to change "static void RunAsThread(this delegate .... or this Delegate)". Could not do it properly. Is there any work around for that? Is there any way for that?

1
  • 3
    No, you can't do this. DoSomething isn't an Action. In certain contexts, the compiler can create an Action from it, but this isn't one of those contexts. Commented Jan 24, 2014 at 11:14

3 Answers 3

1

No, you can't do this, as DoSomething is not a type, it's a method.

Also, just because you can attach an extension method to a type it doesn't mean you should..!

Sign up to request clarification or add additional context in comments.

Comments

1

If DoSomething doesn't have to be an actual method, a slight tweak would make this compile:

class WorkingClass { public void Work() { //Works fine ((Action)DoSomething).RunAsThread(); //Works fine Extensions.RunAsThread(DoSomething); //But I really need this to work DoSomething.RunAsThread(); } private Action DoSomething = () => { //Do Something }; } 

Whether that fits in with everything else you're writing or not, I couldn't say.

Comments

0

DoSomething is just a "Method group" it will be implicitly converted to Action or compatible delegate type whenever possible.

DoSomething itself not a Delegate, so not possible. but you could do the following with the help of implicit method group conversion.

Action a = DoSomething; a.RunAsThread(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.