1

I have a class with a large count of properties (about 30), for example

 [DisplayName("Steps to stacker"), DefaultValue(20)]
 [Description("Value in obturator steps")]
 public int StepsToStacker { get; set; }

 [DisplayName("Enter time"), DefaultValue(120)]
 [Description("Value in milliseconds")]
 public int EnterTime { get; set; }

Is there a simple way to implement LoadDefaultValues() which load values from DefaultValue atrribute?

Max
  • 170
  • 1
  • 10

2 Answers2

1

Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway.

foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
        {
            DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];

            if (myAttribute != null)
            {
                property.SetValue(this, myAttribute.Value);
            }
        }
Thilina H
  • 5,754
  • 6
  • 26
  • 56
0

Sorry, my qustion id duplicate. This code works fine

public void LoadDefaultValues()
{
   foreach (PropertyInfo p in this.GetType().GetProperties())
   {
       foreach (Attribute attr in p.GetCustomAttributes(true))
       {
           if (attr is DefaultValueAttribute)
           {
                DefaultValueAttribute dv = (DefaultValueAttribute)attr;
                p.SetValue(this, dv.Value, null);
           }
        }
    }
}
Max
  • 170
  • 1
  • 10