Yuriy
Yuriy

Reputation: 2691

How to get PropertyDescriptor for current property?

How can I get the PropertyDescriptor for the current property? For example:

[MyAttribute("SomeText")]
public string MyProperty
{
    get{....}
    set
    {
        // here I want to get PropertyDescriptor for this property.
    }
}

Upvotes: 13

Views: 40570

Answers (5)

IAbstract
IAbstract

Reputation: 19881

I found that the following worked:

//  get property descriptions
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( this );

//  get specific descriptor
PropertyDescriptor property = properties.Find ( PropertyName, false );

where PropertyName is a value passed into a method.

Upvotes: 5

Mike Christiansen
Mike Christiansen

Reputation: 1149

For future reference, you can now do this:

public static PropertyDescriptor? GetPropertyDescriptor(
    this object target, 
    [CallerMemberName] string propertyName = ""
) => TypeDescriptor.GetProperties(target.GetType())
        .Find(propertyName, ignoreCase: false)

Upvotes: 0

toddmo
toddmo

Reputation: 22406

Here's a re-usable conversion function for those who got to this post looking for a general function:

public static PropertyDescriptor GetPropertyDescriptor(PropertyInfo PropertyInfo)
{
    return TypeDescriptor.GetProperties(PropertyInfo.DeclaringType).Item(PropertyInfo.Name);
}

and here's an extension method:

public static PropertyDescriptor PropertyDescriptor(this PropertyInfo propertyInfo)
{
  return TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name];
}

Upvotes: 12

WraithNath
WraithNath

Reputation: 18013

You could try this:


        public string Test
        {
            get
            {
                //Get properties for this
                System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties( this );

                //Get property descriptor for current property
                System.ComponentModel.PropertyDescriptor pd = pdc[ System.Reflection.MethodBase.GetCurrentMethod().Name ];
            }
        }

Upvotes: 16

James Gaunt
James Gaunt

Reputation: 14783

How about this?

this.GetType().GetProperty("MyProperty")

I think you're asking if you can do this without the string - i.e. some other token that represents 'this property'. I don't think that exists. But since you are writing this code anyway (?) what is the difficulty in just putting the name of the property in the code?

Upvotes: 0

Related Questions