0

I want to make a DynamicMethod which in turn behave like the following for example:

AnyClass myClass = new AnyClass();
Func<AnyClass> myFunc = () => myClass;

I know that when I want to make it work with an int instead of AnyClass I have to use the following snippet to return every time the number 12:

// Define method
DynamicMethod method = new DynamicMethod(
    "Name",
    typeof(int),
    new Type[] { });

// Define method body
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, 12);
il.Emit(OpCodes.Ret);

But now I ask myself how to do it with a not build-in class.

Edit:

At the end I want to get a reference from a local variable when I call the DynamicMethod. Look at the following snippet to better understand what I wanted to archieve. Here I want a func which returns on every call the variable I passed to the function which creates the func.

Func<AnyClass> GetMethodWithAFunc(AnyClass myClass) {
   Func<AnyClass> myFunc = () => myClass;
   return myFunc;
}

The generated IL Code for the snippet can be found on SharpLab. Unfortunately we have to provide a context where the data to return in the DynamicMethod could be saved. Finally I suggest a static cache and to use converting and unboxing when returning the values.

Dragonblf
  • 115
  • 1
  • 8
  • "But now I ask myself how to do it with a not build-in class." It's unclear what you mean here. You can't have a constant for a type that's not built into the CLR. It would help if you'd first show what the C# equivalent is for what you're trying to emit, then we can help work out how to emit the IL. – Jon Skeet Sep 09 '20 at 06:52
  • @JonSkeet Finally, I would like to know what the snippet is using the DynamicMethod to get the same result as the snippet I showed above which uses Func<>. – Dragonblf Sep 09 '20 at 07:05
  • Ah, so not a constant, but a reference to a local variable. That's going to be tricky, because you'd need the context of the local variable. If you decompile the `Func` code you'll see the compiler creates a new class to hold all the context, then a method within that class. If you want a dynamic method to return a static variable, that would be much simpler. Please edit your question with more context - at the moment I doubt that an answer is really feasible. – Jon Skeet Sep 09 '20 at 07:08
  • @JonSkeet Well, I think there is no way arround to generate this "extra" classes to provide the context right? – Dragonblf Sep 09 '20 at 07:36
  • 2
    Well if you know that you're going to have *this specific situation* you could probably create a single generic class and reuse it. But we don't have much context of what you're trying to do or why you're using DynamicMethod. – Jon Skeet Sep 09 '20 at 07:51

0 Answers0