Attributes can be used to add more information about a particular class in C#. This is an example (and code) of where you would use one. More info can be found here.
// Lets create an attribute that only works on classes that are used for databases[System.AttributeUsage(System.AttributeTargets.Class)]publicclassDatabaseAttribute:Attribute{privatestring_url;privateint_id;publicstringcomment;publicDatabaseAttribute(stringurl,intid){this._url=url;this._id=id;comment="";}publicstringSayUrl(){return"My url is "+url;}}[Database("https://....",1,comment="My mongo database class")]publicclassMongoDB{// ...}
Retrieving
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Given the code abovepublicclassGetAttributeClass{publicstaticvoidGetAttributeData(){// Get the attributes for MongoDB class, can have more than 1System.Attribute[]attrs=System.Attribute.GetCustomAttributes(typeof(MongoDB));// System.Type// Display themforeach(System.Attributeattrinattrs){if(attrisDatabase){Databasea=(Database)attr;System.Console.WriteLine("{0} - {1}",a.SayUrl(),a.comment);}}}}// Output:// My url is https://.... - My mongo database class
publicclassNoAttribute{}[Database("https://something....",2)]publicclassSql{}publicclassProgram{publicstaticvoidMain(string[]args){// Retrieve all the classes that have a DatabaseAttributevardatabaseClasses=fromtinAssembly.GetExecutingAssembly().GetTypes()wheret.GetCustomAttributes<DatabaseAttribute>().Count()>0selectt;foreach(vardbindatabaseClasses){Console.WriteLine(t.Name);}}}// Output:// MongoDB// Sql