4

I'm creating a custom attribute in C#.

So I have something like this:

[AttributeUsage(AttributeTargets.Property)] public class Something : Attribute { public Something { Assembly a = Assembly.GetCallingAssembly(); } } 

The code above will give me the assembly name of the assembly where the attribute is being called from.

What I would like to know is if there is a way to get the name and type of the property to which the attribute was added. So as an example if I had:

// This should return System.Int32 and MyString [Something] public int MyInt {get; set;} // This should return me System.String, and MyString [Something] public string MyString {get; set;} 

Is there any way to get those values upon adding the attribute, or will I have to resort to looping trough all the properties in the type and see which ones have an attribute assigned to them?

Thanks in advance.

6
  • You could add the type to the attribute's constructor and then retrieve them with a call to the new generic method in 4.5 Commented Jul 19, 2013 at 9:29
  • I'm looking to have it working with .Net 4.0 Commented Jul 19, 2013 at 9:30
  • @Garrry, Do you have quick a sample ? Commented Jul 19, 2013 at 9:31
  • Yes, but he's working in 4.0 and my stuff is in 4.5 and will not even compile in 4.0 Commented Jul 19, 2013 at 9:33
  • A 4.5 answer can be usefull for other people such as me ;) In fact I don't understand which "new generic method in 4.5" you are talking about Commented Jul 19, 2013 at 9:35

1 Answer 1

1

There is no other way then iterating over the properties and check the attributes. But you should be able to do this in one Linq statement.

Use GetCustomAttributes on the GetProperties method of the types.

You could optimize the performance, if you mark all classes that use this attributes are marked by an interface, common base class or an class attribute. So you could prefetch the classes instead to iterate over all types.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.