Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Assemblies and Methods

I've programmed .NET and C# for years now, but have only recently encountered the DynamicMethod type along with the concept of a Dynamic Assembly within the context of reflection. They seem to always be used within IL (runtime code) generation.

Unfortunately MSDN does an extraordinarily poor job of defining what a dynamic assembly/method actuallty is and also what they should be used for. Could anyoen enlighten me here please? Are there anything to do with the DLR? How are they different to static (normal) generation of assemblies and methods at runtime? What should I know about how and when to use them?

like image 478
Noldorin Avatar asked Dec 21 '11 15:12

Noldorin


1 Answers

DynamicMethod are used to create methods without any new assembly. They also can be created for a class, so you can access it's private members. Finally, the DynamicMethod class will build a delegate you can use to execute the method. For example, in order to access a private field:

var d = new DynamicMethod("my_dynamic_get_" + field.Name, typeof(object), new[] { typeof(object) }, type, true);
var il = d.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, field);
if (field.FieldType.IsValueType)
    il.Emit(OpCodes.Box, field.FieldType);
else
    il.Emit(OpCodes.Castclass, typeof(object));

il.Emit(OpCodes.Ret);
var @delegate = (Func<object, object>)d.CreateDelegate(typeof(Func<object, object>));

Hope it helps.

like image 129
Ivo Avatar answered Sep 24 '22 20:09

Ivo