Fylix
Fylix

Reputation: 2713

Find generic object property attribute value using reflection at run time

I created a custom attribute class that I use to control certain aspect when I export an object to CSV format.

[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
    public bool Exportable { get; set; }
    public string ExportName{ get; set; }
}

Here is an example of one of the object I want to export:

public class ObjectA
{
    [MyCustom(Exportable = true, ExportColumnName = "Column A")]
    public string PropertyA {get; set; }

    [MyCustom(Exportable = false)]
    public string PropertyB {get; set; }

    public string PropertyC {get; set; }
}

I create my Export function that accept a generic object.

public void Export<T>(T exportObject)
{
   //I get the property name to use them as header
   var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

   foreach (var property in properties)
   {
      //find the list of attribute of this property.
      var attributes = Attribute.GetCustomAttributes(property, false);

     //if attribute "Exportable" value is false or doesn't exists then continue foreach
     //else continue export logic

   } 
}

My question is how can I use reflection to find if the property has the attribute "Exportable" and that if it is true?

Please note I can pass in any generic object, in this case I want my final export to contain one column that contains PropertyA data and that my column header value is "Column A"

Upvotes: 0

Views: 43

Answers (2)

William Silva
William Silva

Reputation: 31

@Sohaib Jundi gave a very good answer. If, for some reason, you decide to create more Custom Attributes, you can do somethink similar to this:

public void Export<T>(T exportObject)
{
    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (var property in properties)
    {
        var attributes = Attribute.GetCustomAttributes(property, false);

        foreach (var attribute in attributes)
        {
            if (attribute is MyCustomAttribute)
            {
                if (((MyCustomAttribute)attribute).Exportable)
                {

                }
            }

            if (attribute is MyCustomAttribute2)
            {
                if (((MyCustomAttribute2)attribute).AnotherThing)
                {

                }
            }
        }
    }
}

This way you could check for multiple attributes of your object

Upvotes: 1

Sohaib Jundi
Sohaib Jundi

Reputation: 1664

You are on the right path, replace the froeach body with this:

var attribute = property.GetCustomAttribute<MyCustomAttribute>();

if(attribute != null)
{
  bool isExportable = attribute.Exportable;
  // rest of the code
}

Upvotes: 1

Related Questions