Introduction
AssemblyAttributes
is a cute little helper class that is useful for almost every .NET/Silverlight application that displays some information about itself (think “About Box”). It retrieves the values of the following assembly attributes in an easy and consistent manner:
Title
Product
Copyright
Company
Description
Trademark
Configuration
Version
FileVersion
InformationalVersion
Doing so is a piece of cake for every experienced developer, but getting these information for the 100th time, manually, is quite cumbersome. And, junior developers sometimes struggle with Reflection to get these attributes. With the help of Generics and Lambda Expressions, you can code an elegant class that solves this problem once and for all.
Using the Code
Create an instance of the AssemblyAttributes
class and query its properties:
AssemblyAttributes assembly = new AssemblyAttributes();
Console.WriteLine("Title: " + assembly.Title);
Console.WriteLine("Product: " + assembly.Product);
Console.WriteLine("Version: " + assembly.Version);
You can give the constructor an explicit assembly like this:
var assembly = new AssemblyAttributes(Assembly.GetEntryAssembly());
Points of Interest
The implementation of each attribute property is elegant, thanks to Generics and lambdas:
public string Title
{
get { return GetValue<AssemblyTitleAttribute>(a => a.Title); }
}
The real workhorse of this class is the GetValue
method. It gets a generic custom attribute from an assembly. If it exists, it returns the result of the getValue
delegate on it. If the attributes does not exist, it returns the empty string.
string GetValue<T>(Func<T, string> getValue) where T : Attribute
{
T a = (T)Attribute.GetCustomAttribute(_assembly, typeof(T));
return a == null ? "" : getValue(a);
}
Note the workaround in the implementation of the Version
property, needed for Silverlight 3, because the GetName()
method is marked as security_critical
and cannot be called by user code.
public string Version
{
get
{
#if !SILVERLIGHT
return _assembly.GetName().Version.ToString();
#else
return _assembly.FullName.Split(',')[1].Split('=')[1];
#endif
}
}