c# – How to access attribute properties?

Question:

I have a Type attribute. I'm parsing the Assembly into types that have the desired attribute.

types = ass.GetTypes().Where(t => t.CustomAttributes.Any(a => a.AttributeType == utilTypes[1]));

That is I receive the list of types. It is necessary for me, sorting through this list, to get attribute properties. Well, for example, from this

[MyAttribute("Hello")]
class MyClass{}

I need to get the Prop1 property, which is equal to "Hello" . How to do it? What is already completely confused in these reflections 🙁

UPD1

I forgot to say. I don't have direct access to the attribute type. That is, I can't do that.

foreach (var type in types)
{
    var MyAttr = (MyAttributeAttribute)type.GetCustomAttribute(utilTypes[0].GetType())
}

Because I have this very type of MyAttributeAttribute attribute only in text form. This means that I need to somehow get a property from it that I do not have direct access to.

Answer:

Try the following approach.
Let the type of an instance of the class MyClass lie in the variable type . That is:

Type type = typeof(MyClass);

Or in your case:

Type type = types[i];

Then the following code:

var attr = type.CustomAttributes.FirstOrDefault(a => a.AttributeType == utilTypes[0]);
if (attr != null)
{
    var attrType = attr.AttributeType;
    var propInfo = attrType.GetProperty("Prop1", BindingFlags.Instance | BindingFlags.Public);
    Console.WriteLine(propInfo.GetValue(mcType.GetCustomAttribute(attrType)));
}

Output:

hello


Here it is in the form of a method:

public static object GetAttributeProperty(Type classType, Type attributeType, string propertyName)
{
    var propInfo = attributeType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
    return propInfo.GetValue(classType.GetCustomAttribute(attributeType));
}
Scroll to Top