Referencing assembly attributes
In .NET, when you go to the properties of a project and select Application > Assembly Information, you can fill in some basic information about the application you're making. It would be convenient if you could reference these fields from within your code, to avoid having to duplicate this information. There is a fairly easy way to do this. To get the company:
public static string Company {
get {
object[] attr = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attr == null || attr.Length <= 0)
return string.Empty;
else
return (attr[0] as AssemblyCompanyAttribute).Company;
}
}
This can now be written shorter. To get the title:
private static string GetTitle() => Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>()?.Title;
I put this as static properties in the Program class. That way I can reference these fields anywere I need them.
Using them in XAML
One useful purpose for this is setting the window title of a WPF application. To do this, you need to declare the namespace of the application in XAML. By convention, it's tag is xmlns:local. Then you can simply write:
Title="{x:Static local:App.Title}"
Assuming you have a method that retrieves the AssemblyTitleAttribute in the App class, the window will now display this title. Also note that the method has to be public for this.