Getting a property description attribute
Existing code (simplified)
I have this function
public static string[] GetFieldNames<T>(IEnumerable<T> items)
where T : class
{
var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types
return properties.Select(p => p.Name).ToArray();
}
So if I have this class
class MyClass {
public string Name { get; set; }
[Description("The value")]
public int Value { get; set; }
}
I may have a code like this
List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]
This works great.
Problem
I need to get the description (if it exists), so it GetFieldNames(items)
returns["Name", "The value"]
How do I change the function GetFieldNames()
to read the Description attribute if it exists?
(Note that this function has been simplified, the real function is much more complex, so please don't change the logic)
source to share
NOTE: just add using System.Reflection
as GetCustomAttribute
this is an extension method in .Net 4.5
public static Tuple<string,string>[] GetFieldNames<T>(IEnumerable<T> items) where T : class
{
var result =
typeof (T).GetProperties()
.Where(p => SystemTypes.Contains(p.PropertyType) &&p.GetCustomAttribute<DescriptionAttribute>() != null)
.Select(
p =>
new Tuple<string, string>(p.Name,
p.GetCustomAttribute<DescriptionAttribute>().Description));
return result.ToArray();
}
for an earlier version of the .NET Framework, we can use this extension method:
public static class Extension
{
public static T GetCustomAttribute<T>(this System.Reflection.MemberInfo mi) where T : Attribute
{
return mi.GetCustomAttributes(typeof (T),true).FirstOrDefault() as T;
}
}
source to share
This is a generic function that you can use if the attribute fieldName
has an attribute description
, it returns a value, otherwise it returns null
.
public string GetDescription<T>(string fieldName)
{
string result;
FieldInfo fi = typeof(T).GetField(fieldName.ToString());
if (fi != null)
{
try
{
object[] descriptionAttrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
DescriptionAttribute description = (DescriptionAttribute)descriptionAttrs[0];
result = (description.Description);
}
catch
{
result = null;
}
}
else
{
result = null;
}
return result;
}
Example:
class MyClass {
public string Name { get; set; }
[Description("The age description")]
public int Age { get; set; }
}
string ageDescription = GetDescription<MyClass>("age");
console.log(ageDescription) // OUTPUT: The age description
source to share