0

Is there a way to "mark" a property in a class, so that when i loop through the class' properties, i can execute a method, base on the mark or unmarked property.

I cannot do this by checking the propertyvalue.

Test Class to loop through

public class SomeClass {
public List<Object> PropertyOne { get; set; }
public List<Object> PropertyTwo { get; set; }

public SomeClass() {
PropertyOne = new List<Object>();
PropertyTwo = new List<Object>();
}
}

Reading properties:

SomeClass myObject = new SomeClass();
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    // If this prop is "marked" -> Execute code below
}

Edit: Thank you both for the great answers.

2 Answers2

0

That's what attributes are for. Create your own attribute, apply it to the property and test that prop.GetCustomAttribute<MyMarkerAttribute>() is not null.

public class MyMarkerAttribute : Attribute 
{

}

public class SomeClass 
{
    // unmarked
    public List<Object> PropertyOne { get; set; }

    [MyMarkerAttribute] // marked
    public List<Object> PropertyTwo { get; set; }
}

foreach (PropertyInfo prop in props)
{
    if (prop.GetCustomAttribute<MyMarkerAttribute>() != null)
    {
        // ...
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

You can use Attributes for that

public class MyAttribute : Attribute
{

}

public class SomeClass {
[MyAttribute]
public List<Object> PropertyOne { get; set; }
public List<Object> PropertyTwo { get; set; }

public SomeClass() {
PropertyOne = new List<Object>();
PropertyTwo = new List<Object>();
}
}

And then check for attributes when iterating through properties as described here: How to retrieve Data Annotations from code? (programmatically)

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).FirstOrDefault();
}
Community
  • 1
  • 1
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50