Who's me
Who's me

Reputation: 31

How to get an attribute of a property in c#?

Going direct to the point,

How can I get Property's attribute, and, the type or the value of this attribute? For example an attribute like this:

[ForeignKey(typeof(SomeObject))]

I wanna know or get its type "SomeObject". I know I can get Properties() and etc, but attributes I have no Ideia.

That is a doubt I have and it is freaking me off. Thanks in advance for helpin!

Upvotes: 1

Views: 192

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503180

Once you've got the PropertyInfo for the property you're interested in, you just call GetCustomAttributes on it:

ForeignKey[] keys = (ForeignKey[]) 
    property.GetCustomAttributes(typeof(ForeignKeyAttribute), false);

There's also the CustomAttributes property, but that's only available in .NET 4.5 and Windows Store apps.

Upvotes: 3

Related Questions