title: C#, How to dynamically create with Reflection.Emit property getter setter in mvvmlight style
body: <h3>How to create Property like the following in Reflection.Emit</h3>
  
  <pre class="lang-cs prettyprint-override"><code>    private string _Name;
  
      public override string Name{ get =&gt; _Name; set =&gt; Set(ref _Name, value); }
  </code></pre>
  
  <h3>I tried this with Reflection.Emmit</h3>
  
  <pre class="lang-cs prettyprint-override"><code>    private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
      {
        // propertyName = "Name";
        // propertyType = typeof(string);
        // private string _Name;
        FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
  
        // public string Name {get; set;}
        PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
        // get;
        MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
        ILGenerator getIl = getPropMthdBldr.GetILGenerator();
        // get =&gt; _Name
        getIl.Emit(OpCodes.Ldarg_0);
        getIl.Emit(OpCodes.Ldfld, fieldBuilder);
        getIl.Emit(OpCodes.Ret);
  
        // set;
        MethodBuilder setPropMthdBldr =
            tb.DefineMethod("set_" + propertyName,
              MethodAttributes.Public |
              MethodAttributes.SpecialName |
              MethodAttributes.HideBySig,
              null, new[] { propertyType });
  
        ILGenerator setIl = setPropMthdBldr.GetILGenerator();
  
  
        var MvvmLightSetMethod = typeof(ObservableObject)
                                 .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                                 .Where(m =&gt; m.Name == "Set").ToList()[2];
  
        // set =&gt; Set(ref _Name, value);
        setIl.Emit(OpCodes.Mkrefany, fieldBuilder);
        setIl.Emit(OpCodes.Ldarg_0);
        setIl.Emit(OpCodes.Ldarg_1);
        setIl.Emit(OpCodes.Stfld, propertyName);
        setIl.Emit(OpCodes.Call, MvvmLightSetMethod);
        setIl.Emit(OpCodes.Ret);
  
        // public string Name {get; set;}
        propertyBuilder.SetGetMethod(getPropMthdBldr);
        propertyBuilder.SetSetMethod(setPropMthdBldr);
      }
  </code></pre>
  
  <h3>My Problem</h3>
  
  <p>If I run this code and call the setter i get  "Invalid class token exception" in set_Name(string)</p>