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?
If you know the assembly's file system path, you can call the static (C#) or Shared (Visual Basic) AssemblyName. GetAssemblyName method to get the fully qualified assembly name.
GetAssemblyName(assembly. Location). Version. ToString(); will get you the 'compiled' version number - which should be the same as FileVersion, if you're setting both versions the same way.
Three attributes, together with a strong name (if applicable), determine the identity of an assembly: name, version, and culture. These attributes form the full name of the assembly and are required when referencing the assembly in code.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With