Fonte originale
[Code Project - articolo originale](https://www.codeproject.com/Articles/827091/Csharp-Attributes-in-minutes)
**Gli attributi in C# non sono altro che informazioni che vengono scambiate tra gli sviluppatori.**
Queste informazioni possono essere attaccate a class, method, namespace, assembly, property, delegate, enum, event, interface e struct per aggiungere informazioni metadati al proprio assembly.
Gli attributi sono definiti utilizzando le "parentesi quadre" [ e ].
1public class Class12{3 [Obsolete]4 public void Method1()5 {6 }78 public void Method2()9 {10 }11}
In questo esempio il Method1 è stato adornato con l'attributo Obsolete e quando si utilizzerà il metodo, verrà comunicato allo sviluppatore che questo metodo è obsoleto.
1. Creare attributi personalizzati
Gli attributi devono derivare dalla classe Attribute
1class PersonalAttribute : Attribute2{3 public string AttributeText { get; set; }4}567[PersonalAttribute(AttributeText="Attributo personalizzato per classe")]8public class Class19{10 [PersonalAttribute(AttributeText="Attributo personalizzato per metodo")]11 public void Method1()12 {13 }1415 [PersonalAttribute(AttributeText="Attributo personalizzato per proprietà")]16 public void Property1{ get; set; }17}
2. Reflection
Gli attributi hanno una grande importanza quando si utilizza la reflection perchè permettono di fornire maggiori informazioni agli sviluppatori che analizzano le nostre classi
1[AttributeUsage(AttributeTargets.Property)]2class Check : Attribute3{4 public int MaxLength { get; set; }5}678public class Class19{10 private string _CustomerCode;11 [Check(MaxLength=10)]12 public string CustomerCode13 {14 get { return _CustomerCode; }15 set { _CustomerCode = value; }16 }1718}
Quando si utilizza la Reflection per accedere ai dati ed alle informazioni:
1Class1 myClass = new Class1();2myClass.CustomerCode = "1234567890123456789";3Type classType = myClass.GetType();45foreach(PropertyInfo p in classType.GetProperties())6{7 foreach(Attribute a in p.GetAttributes(false)) {8 Check c = (Check)a;9 if (c.Name.Equals("CustomerCode"))10 {11 if (my.CustomerCode.Length > c.MaxLength)12 throw new Exception("Lunghezza troppo lunga!");13 }14 }15}