Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Ability to change reference without types check via DynamicMethod

$
0
0

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";
			Console.WriteLine(a.Name.GetType().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.Ldarg_0);
			gen.Emit(OpCodes.Ldarg_1);
			gen.Emit(OpCodes.Call, pi.GetSetMethod(true));
			gen.Emit(OpCodes.Ret);			

			SetValue setMethod = (SetValue)method.CreateDelegate(typeof(SetValue));

			int val = 123;
			setMethod(a, val);
			Console.WriteLine(a.Name.GetType().Name);

			A anotherA = new A();
			anotherA.Name = "Another A";
			setMethod(a, anotherA);
			Console.WriteLine(a.Name.GetType().Name);
		}
	}

	public class A
	{
		public string Name { get; set; }
	}

	public delegate void SetValue(object obj, object val);
}
(.NET 4.5)


Alexander Anisov




Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>