Get the default value for a property with its name

I have a property (an example is shown below).

 [DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }

The situation I'm using is to make sure that it appears as bold in the PropertyGrid if the default is not set.

It seems incredibly annoying to me that in my constructor I have to set the initial value of my property and hope that they match.

Is it possible for my constructor to "detect" the default value for this property and set it accordingly? Sort of:

myctor()
{
   myVal = GetDefaultValueProperty<bool>("MyProperty");
}
+3
source share
2 answers

You can use the following code to get the metadata you are after.

public static T GetDefaultValue<T>(string propertyName)
{
    var property = typeof(MyClass).GetProperty(propertyName);

    var attribute = property
        .GetCustomAttribute(typeof(DefaultValueAttribute)) 
            as DefaultValueAttribute;

    if(attribute != null)
    {
        return (T)attribute.Value;
    }
}

- , Lambda:

public static T GetDefaultValue<T>(
    Expression<Func<T, MyClass>> propertySelector)
{
    MemberExpression memberExpression = null;

    switch (expression.Body.NodeType)
    {
        case ExpressionType.MemberAccess:
            // This is the default case where the 
            // expression is simply member access.
            memberExpression 
                = expression.Body as MemberExpression;
            break;

        case ExpressionType.Convert:
            // This case deals with conversions that 
            // may have occured due to typing.
            UnaryExpression unaryExpression 
                = expression.Body as UnaryExpression;

            if (unaryExpression != null)
            {
                memberExpression 
                    = unaryExpression.Operand as MemberExpression;
            }
            break;
    }


    MemberInfo member = memberExpression.Member;

    // Check for field and property types. 
    // All other types are not supported by attribute model.
    switch (member.MemberType)
    {
        case MemberTypes.Property:
            break;
        default:
            throw new Exception("Member is not property");
    }

    var property = (PropertyInfo)member;

    var attribute = property
        .GetCustomAttribute(typeof(DefaultValueAttribute)) 
            as DefaultValueAttribute;

    if(attribute != null)
    {
        return (T)attribute.Value;
    }
}

:

myctor()
{
   myVal = GetDefaultValue(x => x.MyProperty);
}
+5

GetProperty, , GetCustomAttributes(typeof(DefaultValueAttribute) ( ), .

+4

All Articles