How can I dynamically create an Action<T> at runtime?

c# create instance of generic type at runtime
c# create action
dynamic property c#
dynamic types
c# dynamic
c# dynamic object
dynamic parameters in c#
c# action

I want to be able to do the equivalent to the following at runtime:

var action = new Action<ANYTHING AT RUNTIME>(obj => Console.WriteLine("Called = " + obj));

I know I need to get the correct type for the Action, but not sure how to get the final bit using Delegate.Create. Type represent T in the Action definition.

var actionType = typeof(Action<>).MakeGenericType(Type);
var constructor = actionType.GetConstructors()[0];
var @delegate = Delegate.CreateDelegate(actionType, <WHAT GOES HERE>);

the point people seem to be missing is I'm trying to create an instance of Action where T can not be specified statically because it is being used from a class derived from Attribute - this means T could be anything and it can not be defines as a generic definition

Cheers

If you know what the operation you need to perform is and how to perform it regardless of type (as in your example) why not just make a generic method that performs the operation and create your delegate that way?

class Program
{
    public static void Perform<T>(T value)
    {
        Console.WriteLine("Called = " + value);
    }

    public static Delegate CreateAction(Type type)
    {
        var methodInfo = typeof (Program).GetMethod("Perform").MakeGenericMethod(type);
        var actionT = typeof (Action<>).MakeGenericType(type);
        return Delegate.CreateDelegate(actionT, methodInfo);
    }

    static void Main(string[] args)
    {
        CreateAction(typeof (int)).DynamicInvoke(5);
        Console.ReadLine();
    }
}

How to: Define and Execute Dynamic Methods, Create an instance of the delegate (declared in step 1) that represents the dynamic method by calling the CreateDelegate method. Creating the� Create two actions. 1st Action would take from 1st bar chart to dashboard 1 and second action from duplicate bar chart to dashboard 2. The button you are looking for would be your parameter. Parameter swaps the sheets, which inturn lets you navigate to your preferred dashboard.

You can use following code, it works if type can be casted to an object:

Action<object> func = o => Console.WriteLine("Called = " + o.GetType().Name);
var actionType = typeof(Action<>).MakeGenericType(type);
var constructor = actionType.GetConstructors()[0];
var @delegate = Delegate.CreateDelegate(actionType, func.Method);

However if type is enum or other value type it won't work.

Create a data gathering action for a dynamic object, Create an action to collect output values. Then, pass the values to a parent action as a dynamic object. Thanks to "@prashanth" suggestion, I managed to dynamically create and call an Action<> with a runtime type thanks to the dynamic keyword : public Action<dynamic> GetDynamicAction(/* some params */) { return oDyn => { //here is the action code with the use of /* some params */ }; }

Thanks to "@prashanth" suggestion, I managed to dynamically create and call an Action<> with a runtime type thanks to the dynamic keyword :

        public Action<dynamic> GetDynamicAction(/* some params */)
        {
            return oDyn =>
            {
                //here is the action code with the use of /* some params */
            };
        }

Example with a basic action handler :

public class ActionHandler
{
     public ReturnType DoAction<T>(Action<T> t)
     {
         //whatever needed
     }
}

Use case :

/* some params */ = Any runtime type specific data (in my case I had a Type and a MethodInfo passed as parameters and that were called in the action)

var genericMethod = actionHandler.GetType().GetMethod(nameof(ActionHandler.DoAction));
var method = genericMethod.MakeGenericMethod(runtimeGenericType);

var actionResult = (ReturnType) method.Invoke(actionHandler, new object[]
                    {
                        GetDynamicAction(/*some params*/)
                    }
                );

how to create dynamic matrix value? - GitHub Actions, hello, I know from this post that the matrix can not be a value from secrets. any thoughts on how to make matrix value can be dynamic, so I don't� Create an Action object. Through arguments, you can specify the text and icon to be used in the components that the action is attached to. void setEnabled(boolean) boolean isEnabled() Set or get whether the components the action controls are enabled. Invoking setEnabled(false) disables all the components that the action controls.

The short answer is to create a delegate MyActionDelegate and then use:

delegate void MyActionDelegate(T arg);
Delegate @delegate = new MyActionDelegate((a) => Console.WriteLine(a));

Here's a working example using a generic class:

public class MyClass<T>
{
    public delegate void ActionDelegate(T arg);

    public void RunGenericAction(T arg)
    {
        var actionType = typeof(Action<>).MakeGenericType(typeof(T));
        var constructor = actionType.GetConstructors()[0];
        Delegate @delegate = new ActionDelegate((a) => { Console.WriteLine(arg); });
        var inst = (Action<T>)constructor.Invoke(new object[] { 
            @delegate.Target,  
            @delegate.Method.MethodHandle.GetFunctionPointer() 
        });
        inst(arg);
    }
}

Use it like this, which outputs 123 to the console:

var c = new MyClass<int>();
c.RunGenericAction(123);

You'll notice I'm passing two parameters to Constructor.Invoke; that's because it turns out that a delegate argument actually compiles as two arguments: the target object of the function, and a pointer to the function. I can't take credit for the fancy footwork there; "borrowed" info from this excellent answer on how to pass a delegate argument using reflection.

Building C# objects dynamically with ExpandoObject – O'Reilly, Create objects that can be enhanced with properties, methods, and events. new Action<object, EventArgs>((sender, eventArgs) => { dynamic� New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach. Example 1: In this example, a newly created element is added as a child to the parent element. The type of the

Create Link to Action dynamically, Hi, I want to create "Link to Action" element at runtime inside a transparent container. can anybody help me out in this. Regards, Kanakaraj V A. Javafx -- dynamically adding buttons and calling setonAction() on it So I am currently doing a personal project where I encountered this situation A user inputs a data (numeric) this generates a no. of Labels and buttons on to a javafx scene..

Dynamic Action Control, Creating, configuring, and implementing the BO-specific action - if you have not yet already done so. Reactivating the business object - if necessary. Implementing� With document.createElement () method you can create a specified HTML element dynamically in JavaScript. Once created, you can insert (or add) the element to your web page, or add it to a pre-defined element or a dynamically created element. In fact, you can create an entire form dynamically using this method.

Managing Dynamic Actions, Once you create a dynamic action, you can modify attributes defined during the creation process, specify attributes not available during the process (such as� how can i dynamically create ajax.actionlinks from the returned Json objectsRSS 3 replies Last post Oct 11, 2012 08:57 AM by johnjohn123123

Dynamic QML Object Creation from JavaScript, Creating a component is better if you have an existing component defined in a QML document and you want to dynamically create instances of that component. you need to create the eventhandler for the button OnClick event. btnobj1.Click += new EventHandler(btnobj1_Click); and you should have the method private void btnobj1_Click(Object sender, EventArgs e) { // here you can play with the txtobj3.Text }

Comments
  • Which part of action = new Action<int>(obj => Console.WriteLine("Called = " + obj)); do you want to generate dynamically?
  • I want to create\initialise the parameter 'action'
  • I'm confused. There is no parameter called action. What do you want to achieve?
  • simple how do you at run time create an instance of Action<T> when T is only know at runtime, you can not infer it statically
  • If you are on .NET 4, you could try Action<dynamic>
  • "No performance difference" To what? you haven't provided any code that actually dynamically creates a delegate. You conveniently provide an abstract class with an abstract method CreateActionImpl but don't provide an implementation--the only method that would actually dynamically create the action.
  • @Peter I've explained the performance implications in the paragraph following the claim. Also, the OP wanted just the type parameter of the delegate late bound. Which the code does without Reflection.Emit.