title: C# Add dynamically attribute to PropertyInfo
body: <p>I have a generic method, which uses custom property attributes to do some stuff.
  I'll show an example in order to explan faster:</p>
  <pre class="lang-cs prettyprint-override"><code>public class Custom1Attribute : Attribute
  { 
  }
  
  public class Custom2Attribute : Attribute
  { 
  }
  
  public class SomeModel
  {
      [Custom1]
      public string Property1 { get; set; }
      [Custom2]
      public string Property2 { get; set; }
  }
  
  class Program
  {
      static readonly MethodInfo method = typeof(Program).GetMethod(nameof(DoSomeReflexion), BindingFlags.Static | BindingFlags.Public);
  
      static void Main(string[] args)
      {
          var myModel = new SomeModel();
  
          var properties = myModel.GetType().GetProperties().Where(p =&gt; !p.CanRead);
          foreach (PropertyInfo property in properties)
          {
              var value = property.GetValue(myModel);
              var propertyHystory = method
                  .MakeGenericMethod(property.PropertyType)
                  .Invoke(null, new object[] { property, value});
          }
      }
  
      static void DoSomeReflexion&lt;T&gt;(PropertyInfo propertyInfo, T value)
      {
          if (propertyInfo.IsDefined(typeof(Custom1Attribute)))
          {
              // Do some stuff
          }
          else if (propertyInfo.IsDefined(typeof(Custom2Attribute)))
          {
              // Do some other stuff
          }
      }
  }
  </code></pre>
  <p>This works well, but now I would like to use this service in another context, and I would create the attributes dynamically in order to use this service.</p>
  <p>For example, given an object instance, I would call DoSomeReflexion on it.
  I tried to obtain and modify the propertyInfo, but it seems not to work :</p>
  <pre class="lang-cs prettyprint-override"><code>var model2PropertyInfo = myModel2Parent.GetType().GetProperty(&quot;Value&quot;); // let's assume I can have access to model2 parent, and model2 is in Value field
  var attributeArrayPropInfo = model2PropertyInfo.GetType().GetProperty(&quot;AttributeArray&quot;, BindingFlags.Instance | BindingFlags.NonPublic);
  var newArray = new Attribute[1] { new Custom2Attribute()};
  attributeArrayPropInfo.SetValue(valuePI, attributeArray, null);
  </code></pre>
  <p>How can I do something like that?
  Not using attributes is not an option, I have a ton of models with plenty of attributes.</p>
  <p>Maybe I can change the PropertyInfo parameter type in the DoSomeReflexion method, for a custom class which can be generated from a PropertyInfo object, or from the dynamic way.
  What do you think?</p>