Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a new method with a user-defined name. Reflection C#

Tags:

c#

reflection

I want to create a method on RunTime. I want the user to enter a string and the method's name will be DynamicallyDefonedMethod_#### (ends with the user string).

i want the same string to be embeded in the method's body: It will call StaticallyDefinedMethod (####, a, b)

Something like:

public MyClass1 DynamicallyDefonedMethod_#### (int a, int b)
{
return  StaticallyDefinedMethod (####, a, b)
}

The idea is that the user will create a new method on runtime and invoke it afterward (with a, b parameters).

i googled C# reflection but found no easy way of doing that. Does someone knows how to do it simply ?

Regards,

like image 509
Elad Benda Avatar asked Jun 17 '26 00:06

Elad Benda


1 Answers

As already noted (comments), the easier approach is just to use a lambda:

Func<int,int,Whatever> func = (a,b) => StaticallyDefinedMethod(s,a,b);

but you can also use meta-programming for this (below). Here you control the method name, and have more flexibility (not that you need it here). But note that this doesn't really add a method to the type - the dynamic method is separate and disconnected. You can't really add members to types at runtime.

using System;
using System.Reflection.Emit;
public class MyClass1  {
    static void Main()
    {
        var foo = CreateMethod("Foo");
        string s = foo(123, 456);
        Console.WriteLine(s);
    }
    static Func<int,int,string> CreateMethod(string s)
    {
        var method = new DynamicMethod("DynamicallyDefonedMethod_" + s,
            typeof(string),
            new Type[] { typeof(int), typeof(int) });
        var il = method.GetILGenerator();
        il.Emit(OpCodes.Ldstr, s);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.EmitCall(OpCodes.Call, typeof(MyClass1).GetMethod("StaticallyDefinedMethod"), null);
        il.Emit(OpCodes.Ret);
        return (Func<int,int,string>)method.CreateDelegate(typeof(Func<int, int, string>));
    }
    public static string StaticallyDefinedMethod(string s, int a, int b)
    {
        return s + "; " + a + "/" + b;
    }
}

A final thought here might be to use dynamic, but it is very hard to choose names at runtime with dynamic.

like image 180
Marc Gravell Avatar answered Jun 19 '26 13:06

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!