Search code examples
c#propertiescustom-properties

Custom attribute internal properties null c#


I have a problem with a custom property. This is the property in question:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public class UIProperty : Attribute
{   
    public UIProperty(string property, Type target) { Property = property; TargetType = target; }

    private string property; 
    public string Property { get{return property;} set{property = value;} }

    private PropertyInfo targetProperty; 
    public PropertyInfo TargetProperty { get { return targetProperty; } protected set { targetProperty = value; } }

    private Type targetType; 
    public Type TargetType { get{ return targetType; } set{ targetType = value; } }

    private object target; public object Target { get{return target; } set{ target = value;} }

    public void SetTargetProperty(PropertyInfo targetPropertyInfo, object target)
    {
        targetProperty = targetPropertyInfo;
        this.target = target;
    }

    public object TargetValue 
    { 
        get { return targetProperty.GetValue(target, null); }
        set { if (!value.Equals(TargetValue)) targetProperty.SetValue(target, value, null); }
    }
}

So, if I set the custom attribute with SetTargetProperty after taking out in this way:

UIProperty uip = this.GetType (). GetProperty ("name"). GetCustomAttributes (typeof (UIProperty), true) [0] as UIProperty;

uip.SetTargetProperty (...);

My attribute has correctly set its target and its properties. Nothing is null or not set. But when I go to pick up that property elsewhere in the code everything is back to null as if I had never set ...

The classes Attribute are instantiated when i get from a PropertyInfo dynamically or they have a physical instance set to the property?

What is wrong?


Solution

  • You are right. As pointed out in that article If you want to construct an attribute object, you must call either GetCustomAttributes or GetCustomAttribute. Every time one of these methods is called, it constructs new instances of the specified attribute type and sets each of the instance’s fields and properties based on the values specified in the code.