Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Action<T> to Action<object>

Tags:

c#

I am stuck.

How do I convert the Action<T> to an Action<Object> in C#?

Regards Magnus

like image 332
Magnus Gladh Avatar asked Aug 09 '10 21:08

Magnus Gladh


2 Answers

Here's a sample of what you ask for (type check can be added in last line to properly handle invalid cast exception to be more user-friendly):

public Action<object> Convert<T>(Action<T> myActionT) {     if (myActionT == null) return null;     else return new Action<object>(o => myActionT((T)o)); } 

May be you can give more details about the task though, because right now it looks a bit odd.

like image 60
DK. Avatar answered Oct 08 '22 17:10

DK.


You can add generic parameter like this

    Action<object> Function<T>(Action<T> act) where T : class     {         return (Action<object>)act;     } 
like image 41
Sameman Avatar answered Oct 08 '22 17:10

Sameman