Simplified way to get assembly description in C#?
I would use an extension method for ICustomAttributeProvider to provide a strongly typed GetCustomAttributes
which returns a strongly typed enumerable. The only linq usage would be the call to FirstOrDefault
and OfType
public static void Main() {
Assembly assembly = Assembly.GetExecutingAssembly();
var descriptionAttribute = assembly
.GetCustomAttributes<AssemblyDescriptionAttribute>(inherit: false)
.FirstOrDefault();
if (descriptionAttribute != null) {
Console.WriteLine(descriptionAttribute.Description);
}
Console.ReadKey();
}
public static IEnumerable<T> GetCustomAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute {
return provider.GetCustomAttributes(typeof(T), inherit).OfType<T>();
}
There isn't, really. You can make it a bit 'more fluent' like this:
var descriptionAttribute = assembly
.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)
.OfType<AssemblyDescriptionAttribute>()
.FirstOrDefault();
if (descriptionAttribute != null)
Console.WriteLine(descriptionAttribute.Description);
[EDIT changed Assembly to ICustomAttributeProvider, cf. answer by Simon Svensson)
And if you need this kind of code a lot, make an extension method on ICustomAttributeProvider:
public static T GetAttribute<T>(this ICustomAttributeProvider assembly, bool inherit = false)
where T : Attribute
{
return assembly
.GetCustomAttributes(typeof(T), inherit)
.OfType<T>()
.FirstOrDefault();
}
Since .Net 4.5, as Yuriy explained, an extension method is available in the framework:
var descriptionAttribute =
assembly.GetCustomAttribute<AssemblyDescriptionAttribute>();
var attribute = Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false)
.Cast<AssemblyDescriptionAttribute>().FirstOrDefault();
if (attribute != null)
{
Console.WriteLine(attribute.Description);
}