Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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();
        }
    }
}
like image 974
Barış Velioğlu Avatar asked Jul 24 '12 18:07

Barış Velioğlu


2 Answers

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.

like image 114
Ben Voigt Avatar answered Sep 20 '22 21:09

Ben Voigt


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
like image 43
Mare Infinitus Avatar answered Sep 20 '22 21:09

Mare Infinitus