I've recently been trying to make use of property attributes. The following code (in a different assembly) retrieves only those properties which have a specific attribute, by name. The problem is it requires that the searched for attribute be the first attribute. The code would break if a different attribute is added to the property, unless it is placed after the attribute being searched for.
IList<PropertyInfo> listKeyProps = properties
.Where(p => p.GetCustomAttributes(true).Length > 0)
.Where(p => ((Attribute)p.GetCustomAttributes(true)[0])
.GetType().Name == "SomeAttribute")
.Select(p => p).ToList();
I did look at this answer, but couldn't make it work since the objects are in Assembly.GetEntryAssembly() and I can't directly call typeof(SomeAttribute).
How can this be changed so as to be less fragile?
[Edit:] I found a way to determine the attribute type, despite it being in a different assembly.
Assembly entryAssembly = Assembly.GetEntryAssembly();
Type[] types = entryAssembly.GetTypes();
string assemblyName = entryAssembly.GetName().Name;
string typeName = "SomeAttribute";
string typeNamespace
= (from t in types
where t.Name == typeName
select t.Namespace).First();
string fullName = typeNamespace + "." + typeName + ", " + assemblyName;
Type attributeType = Type.GetType(fullName);
Then I was able to use IsDefined(), as proposed below by dcastro:
IList<PropertyInfo> listKeyProps = properties
.Where(p => p.IsDefined(attributeType, true)).ToList();