Barış Velioğlu
Barış Velioğlu

Reputation: 5817

Check if property has an specified attribute, and then print value of it

I have a ShowAttribute and I am using this attribute to mark some properties of classes. What I want is, printing the values by the properties that has a Name attribute. How can I do that ?

public class Customer
{
    [Show("Name")]
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Customer(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

class ShowAttribute : Attribute
{
    public string Name { get; set; }

    public ShowAttribute(string name)
    {
        Name = name;
    }
}

I know how to check the property has a ShowAttribute or not, but I couldnt understand how to use it.

var customers = new List<Customer> { 
    new Customer("Name1", "Surname1"), 
    new Customer("Name2", "Surname2"), 
    new Customer("Name3", "Surname3") 
};

foreach (var customer in customers)
{
    foreach (var property in typeof (Customer).GetProperties())
    {
        var attributes = property.GetCustomAttributes(true);

        if (attributes[0] is ShowAttribute)
        {
            Console.WriteLine();
        }
    }
}

Upvotes: 5

Views: 5714

Answers (3)

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

foreach (var customer in customers)
{
    foreach (var property in typeof (Customer).GetProperties())
    {
        if (property.IsDefined(typeof(ShowAttribute))
        {
            Console.WriteLine(property.GetValue(customer, new object[0]));
        }
    }
}

Please be aware of performance hit.

Upvotes: 2

Mare Infinitus
Mare Infinitus

Reputation: 8162

You can try the following:

var type = typeof(Customer);

foreach (var prop in type.GetProperties())
{
    var attribute = Attribute.GetCustomAttribute(prop, typeof(ShowAttribute)) as ShowAttribute;

    if (attribute != null)
    {
        Console.WriteLine(attribute.Name);
    }
}

The output is

 Name

If you want the value of the property:

foreach (var customer in customers)
{
    foreach (var property in typeof(Customer).GetProperties())
    {
        var attributes = property.GetCustomAttributes(false);
        var attr = Attribute.GetCustomAttribute(property, typeof(ShowAttribute)) as ShowAttribute;

        if (attr != null)
        {
            Console.WriteLine(property.GetValue(customer, null));
        }
    }
}

And the output is here:

Name1
Name2
Name3

Upvotes: 5

Ben Voigt
Ben Voigt

Reputation: 283614

Console.WriteLine(property.GetValue(customer).ToString());

However, this will be pretty slow. You can improve that with GetGetMethod and creating a delegate for each property. Or compile an expression tree with a property access expression into a delegate.

Upvotes: 6

Related Questions