66

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.")]
starblue
  • 55,348
  • 14
  • 97
  • 151
Charlie Salts
  • 13,109
  • 7
  • 49
  • 78
  • 1
    For anyone curious, `AssemblyTitle` etc is located in `assemblyattributes.cs`. Here's the source: https://referencesource.microsoft.com/#mscorlib/system/reflection/assemblyattributes.cs. – mekb Aug 24 '19 at 05:37

2 Answers2

93

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>();
Dan Cecile
  • 2,403
  • 19
  • 21
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
8

Yes, use AttributeTargets.Assembly:

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyAttribute : Attribute { ... }
Lee
  • 142,018
  • 20
  • 234
  • 287