Archives

Good stuff, but it will also apply…

Comment on “DefaultValue Attribute as Initial Value” by Jens

Good stuff, but it will also apply default values for the properties of the base class - which you may have modified inside your constructor prior to calling this function... The following is slightly modified code that ignores base class properties:

public static class DefaultValues
{
static public void Apply(object self)
{
if (self == null)
return;

Type baseType = self.GetType().BaseType;
PropertyInfo[] baseProps = baseType != null ? baseType.GetProperties() : new PropertyInfo[0];

foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self))
{
bool skip = false;

foreach (PropertyInfo info in baseProps)
if (prop.Name == info.Name)
{
skip = true;
break;
}

if (skip)
continue;

DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;

if (attr == null)
continue;

prop.SetValue(self, attr.Value);
}
}
}

Share

Comments are closed.