If all you want to do is obtain the value of a property, you don't
need to do all that work.  You can do it simply as follows:

Test t = new Test { Weird = 5 };
PropertyInfo pi = typeof(Test).GetProperty("Weird");
Console.WriteLine(pi.GetValue(t, null));


On Mar 4, 11:08 pm, HolyShea <[email protected]> wrote:
> I'm a bit new to this IL stuff and am stumped.
>
> Can someone tell me why this code throws an exception? (Or, more
> importantly, how I can fix it such that it simply gets the value of
> Weird and outputs that value (5) to the console).
>
> using System;
> using System.Reflection;
> using System.Reflection.Emit;
>
> namespace Test
> {
>         public class Test
>         {
>                 static void Main(string[] args)
>                 {
>                         PropertyInfo pi = typeof(Test).GetProperty("Weird");
>
>                         DynamicMethod dm = new DynamicMethod("hi", 
> typeof(int), null, typeof
> (Test));
>                         ILGenerator gen = dm.GetILGenerator();
>
>                         gen.Emit(OpCodes.Ldarg_0);
>                         gen.Emit(OpCodes.Call, pi.GetGetMethod());
>                         gen.Emit(OpCodes.Box, typeof(int));
>                         gen.Emit(OpCodes.Pop);
>
>                         gen.Emit(OpCodes.Ret);
>
>                         Test t = new Test {Weird = 5};
>
>                         object invoke = dm.Invoke(t, null);
>
>                         Console.WriteLine(invoke);
>
>                         Console.ReadLine();
>                 }
>
>                 public int Weird { get; set; }
>         }
>
> }

Reply via email to