title: Fastest way for Get Value of a property (Reflection) in C#
body: <p>I want to know what is fastest way to get value (only for this problem) from an object`s property ?</p>
  
  <p>after some searching I saw a post from @MarkGravell in this site</p>
  
  <p>He wrote this code :</p>
  
  <pre><code>using System;
  using System.Reflection;
  using System.Reflection.Emit;
  
  public class Foo
  {
      public Foo(int bar)
      {
          Bar = bar;
      }
      private int Bar { get; set; }
  }
  static class Program {
      static void Main()
      {
          var method = new DynamicMethod("cheat", typeof(int),
              new[] { typeof(object) }, typeof(Foo), true);
          var il = method.GetILGenerator();
          il.Emit(OpCodes.Ldarg_0);
          il.Emit(OpCodes.Castclass, typeof(Foo));
          il.Emit(OpCodes.Callvirt, typeof(Foo).GetProperty("Bar",
              BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
              ).GetGetMethod(true));
          il.Emit(OpCodes.Ret);
          var func = (Func&lt;object, int&gt;)method.CreateDelegate(
              typeof(Func&lt;object, int&gt;));
  
          var obj = new Foo(123);
          Console.WriteLine(func(obj));
      }
  }
  </code></pre>
  
  <p><strong>OR</strong> </p>
  
  <pre><code>var method = typeof(Foo).GetProperty("Bar",
  BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                                    .GetGetMethod(true);
  var func = (Func&lt;Foo, int&gt;)
  Delegate.CreateDelegate(typeof(Func&lt;Foo, int&gt;), method);
  </code></pre>
  
  <p>I changed it to </p>
  
  <pre><code>var pt = propertyInfo.PropertyType; // I dont know what is Type
  var method = pt.GetProperty("Bar",
      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                                        .GetGetMethod(true);
  var func = (Func&lt;Foo, object&gt;) // I dont know what is return type so set object !!!
  Delegate.CreateDelegate(typeof(Func&lt;Foo, object&gt;), method); // I want get value as object ?!!!
  return func(entity).ToString(); // cast return value to string
  </code></pre>
  
  <p>but I got an exception</p>
  
  <pre><code> Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
  </code></pre>
  
  <p>I dont know what is my property type It can be anything How customize code for this purpose ?</p>
  
  <p>If anyone can help me in better way (fastest way) without property Type restriction please introduce it </p>