Custom Assembly Attributes

C#.NetAssembliesAttributes

C# Problem Overview


I would like to know if I can define custom assembly attributes. Existing attributes are defined in the following way:

[assembly: AssemblyTitle("MyApplication")]  
[assembly: AssemblyDescription("This application is a sample application.")]  
[assembly: AssemblyCopyright("Copyright © MyCompany 2009")]  

Is there a way I can do the following:

[assembly: MyCustomAssemblyAttribute("Hello World! This is a custom attribute.")]

C# Solutions


Solution 1 - C#

Yes you can. We do this kind of thing.

[AttributeUsage(AttributeTargets.Assembly)]
public class MyCustomAttribute : Attribute {
    string someText;
    public MyCustomAttribute() : this(string.Empty) {}
    public MyCustomAttribute(string txt) { someText = txt; }
    ...
}

To read use this kind of linq stmt.

var attributes = assembly
    .GetCustomAttributes(typeof(MyCustomAttribute), false)
    .Cast<MyCustomAttribute>();

Solution 2 - C#

Yes, use AttributeTargets.Assembly:

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyAttribute : Attribute { ... }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharlie SaltsView Question on Stackoverflow
Solution 1 - C#Preet SanghaView Answer on Stackoverflow
Solution 2 - C#LeeView Answer on Stackoverflow