Reflect on attributes

Hadn't had much to do with reflection until I started my current job. Came across some code that 'reflected' over itself to find out if it can be saved. Basically a check to see if all Mandatory fields have been supplied. It loops through all properties of itself, if it finds it has a particular Custom Attribute it then checks the type and whether it has a value. The code can then decide if it can save the details or if it needs to raise an exception/return an error code to indicate that something is missing.
public bool CanBeSaved()
{
 //reflect on properties marked [NecessaryToSave] to determine result.

 PropertyInfo[] properties = this.GetType().GetProperties();

 for (int i = 0; i < properties.Length; i++)
 {
   object[] customAttributes = properties[i].GetCustomAttributes(false);
   foreach (object obj in customAttributes)
   {
     if (obj is NecessaryToSave)
     {
     if (properties[i].PropertyType == typeof(string))
     {
       string t = (string)properties[i].GetValue(this, null);
       if (t == "" || t == null)
       {
         return false;
       }
     }
     }
   }
 }

 return true;

}
And then on each Property that is mandatory add the required custom attribute...
[NecessaryToSave]
public string Title
{
 get { return _title; }
 set { _title = value; }
}

0 comments: