Ability to change reference without types check via DynamicMethod RRS feed

  • Question

  • Why using DynamicMethod allow to change reference without any types check? Is this known and explainable thing?

    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    namespace Dynamics
    	internal class Program
    		private static void Main(string[] args)
    			var a = new A();
    			a.Name = "Name";
    			PropertyInfo pi = a.GetType().GetProperty("Name");
    			DynamicMethod method = new DynamicMethod(
    					"DynamicSetValue", // NAME
    					null, // return type
    					new Type[] 
                                    typeof(object), // 0, objSource
                                    typeof(object), // 1, value
                                }, // parameter types
    					typeof(Program), // owner
    					true); // skip visibility
    			ILGenerator gen = method.GetILGenerator();
    			gen.Emit(OpCodes.Call, pi.GetSetMethod(true));
    			SetValue setMethod = (SetValue)method.CreateDelegate(typeof(SetValue));
    			int val = 123;
    			setMethod(a, val);
    			A anotherA = new A();
    			anotherA.Name = "Another A";
    			setMethod(a, anotherA);
    	public class A
    		public string Name { get; set; }
    	public delegate void SetValue(object obj, object val);
    (.NET 4.5)

    Alexander Anisov

    • Edited by Alex AA Wednesday, July 31, 2013 3:49 PM
    Wednesday, July 31, 2013 3:45 PM

All replies

  • Hi Alex,

    I am very impressed with your high level of technical proficiency, it has been a pleasure working with you.

    Dynamic methods can be used to implement partial evaluation by generating specialized methods at run time, Dynamic methods allow reclamation of the MSIL method bodies and the related machine code produced by the JIT compiler.

    So, we could see the property named “Name” changes its data type whenever we call setMethod(obj1,obj2) method.

    I would like to provide some articles below regarding this event for your reference:




    • Marked as answer by Lilia gong - MSFT Tuesday, August 6, 2013 2:45 AM
    • Unmarked as answer by Alex AA Wednesday, August 7, 2013 3:14 PM
    Thursday, August 1, 2013 6:33 AM