Who's me
Who's me

Reputation: 31

Getting Attributes of a Property example in C#

today I'm facing the following problem: Get the especific attribute and his value of some properties.

Suppose this code:

Model:

public class ExampleModel : SBase
{
    [MaxLength(128)]
    public string ... { get; set; }

    [ForeignKey(typeof(Foo))] // Here I wanna get the "typeof(Foo)" which I believe it is the value of the attr
    public int LocalBarId { get; set; }

    [ForeignKey(typeof(Bar))]
    public int LocalFooId { get; set; }

    [ManyToOne("...")]
    public ... { get; set; }
}

Then inside another class I want to get all the "ForeignKey" attribute and their values, and more, their respective properties too, but I have no I ideia how to do this in practice. (At end, would be nice throw all this information into any array.)

I recently was writing a Reflection. The ideia of this was to get only especifics properties. Here's one piece of the code:

foreach (var property in this.allProperties)
{
    var propertyItself = element.GetType().GetProperty(property.Name);
    if (propertyItself.PropertyType != typeof(Int32))
    { continue; }

    if (propertyItself.ToString().Contains("Global") && (int)propertyItself.GetValue(element, null) == 0)
    { // doSomething; }

    else if (propertyItself.ToString().Contains("Local") && (int)propertyItself.GetValue(element, null) == 0)
    { // doSomething; }
}

So basically I was interested only in get properties of type int and if that property was which I was expecting then I'd work on em.

Well, I hope with this conversation, any or someone can help me on, or, only give a basic Idea of how you could do this. Thanks in Advance! :)

Upvotes: 0

Views: 758

Answers (1)

Tim S.
Tim S.

Reputation: 56536

var properties = typeof(ExampleModel).GetProperties();
foreach (var property in properties)
{
    foreach (ForeignKeyAttribute foreignKey in
                       property.GetCustomAttributes(typeof(ForeignKeyAttribute)))
    {
        // you now have property's properties and foreignKey's properties
    }
}

Upvotes: 3

Related Questions