April 25, 2010 by Christoff Truter C#
In C# we've got a mechanism called attributes, which we use to provide
extra information about certain elements within our code.
An example of attributes available within C# is the XmlAttribute/XmlRoot/XmlElement
attributes - which we use in conjunction with the XmlSerializer class - used to
serialize objects to XML.
using System; using System.IO; using System.Xml.Serialization; public class friend { [XmlAttribute()] public String firstname { get; set; } [XmlAttribute()] public String lastname { get; set; } } class Program { static void Main(string[] args) { friend f = new friend { firstname = "John", lastname = "Doe" }; using (StreamWriter sw = new StreamWriter(@"c:\abc.xml")) { XmlSerializer xs = new XmlSerializer(typeof(friend)); xs.Serialize(sw.BaseStream, f); } } }
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class Constraint : Attribute { public Boolean Unique { get; set; } public Boolean Required { get; set; } }
public class post { [Constraint(Unique = true, Required = true)] public String title { get; set; } [Constraint(Required = true)] public Int32 age { get; set; } }
public class posts : List<post> { // Hide inherited member "Add" public new void Add(post item) { // Get properties within our class PropertyInfo[] properties = item.GetType().GetProperties(); foreach (PropertyInfo property in properties) { object o = property.GetValue(item, null); // Get custom attributes of type Constraint object[] attributes = property.GetCustomAttributes(typeof(Constraint), true); foreach (Constraint attribute in attributes) { // Check Required Constraint if (attribute.Required) { if (o == null) throw new Exception(String.Concat(property.Name, " property required")); else if (o is int) { if (((int)o) == 0) throw new Exception(String.Concat(property.Name, " property required")); } } // Check Unique Constraint if (attribute.Unique) { // linq query testing for duplicate entries if ((from p in this where p.GetType().GetProperty(property.Name).GetValue(p, null) == o select p).Count() > 0) throw new Exception(String.Concat(property.Name, " property unique violation")); } } } base.Add(item); } }