user460667
user460667

Reputation: 1940

Obtaining all properties in a class marked with an attibute

I have produced a custom attribute which simply marks a classes property as being the 'display name'. What I would like to do is find the property within a given class which has been marked with my attribute. As far as I know, the only way I can do this is to loop through each property (via reflection) and check what attributes it has assigned. Is there any easier/quicker way than this?

foreach (PropertyInfo property in myClassProperties)
{
  //Get the alias attributes.
  object[] attr=
  property.GetCustomAttributes(typeof(DisplayField), true);

  if(attr.Count() > 0)
  {
   // This is a display field!
  }
}

Thanks

Upvotes: 0

Views: 89

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499770

Well, it's slightly simpler than checking all its attributes to find the one you want - you can ask any member whether it has a particular attribute using IsDefined:

var properties = type.GetProperties()
                     .Where(p => p.IsDefined(typeof(MyAttribute), false));

Obviously you can cache that result on a per-type basis if you're going to use it multiple times.

Upvotes: 4

sgtz
sgtz

Reputation: 9009

the only quicker way that I'm aware of is to create a dictionary either statically or in a singleton... so that subsequent visits are faster. I do this caching sometimes, but I do exactly as you outline above for the retrieve attribute functionality.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

As far as I know, the only way I can do this is to loop through each property (via reflection) and check what attributes it has assigned.

That's exactly the way to do it. Attributes are metadata which is baked into the assembly at compile time. In order to access them at runtime you need Reflection.

Upvotes: 4

Related Questions