Simplified way to get assembly description in C#?
.net-4.0, c#, lambda, linq, reflection
Solution
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>();
Problem
I was reading through a .NET 2.0 book and came across this sample code which gets the applications assembly description : ``` static void Main(string[] args) { Assembly assembly = Assembly.GetExecutingAssembly(); object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length > 0) { AssemblyDescriptionAttribute descriptionAttribute = (AssemblyDescriptionAttribute)attributes[0]; Console.WriteLine(descriptionAttribute.Description); } Console.ReadKey(); } ``` It's quite a lot of code to simply get the assembly description and I would like to know if there's a simpler way of doing this in .NET 3.5+ using LINQ or lambda expressions?