Ryu Kaplan Ryu Kaplan - 1 month ago 6
C# Question

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();
}
}
}

Answer
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.

Comments