Question

I would like to flag a parameter in such a way that I can read the tag via reflection. The reason I want to do this is because I am creating business layer objects that map to a database and I want to flag certain parameters as 'read-only', such as uniqueidentifier fields that are being generated in the database.

I am already iterating through the properties for filling the parameters. This is a snippet of how I'm assigning values...

foreach (var prop in this.GetType().GetProperties())
{
   switch (prop.PropertyType.Name)
   {
      case "Int32":
          int tmpInt = -1;
          if (!DBNull.Value.Equals(rowFromDatabase[prop.Name]) && int.TryParse(rowFromDatabase[prop.Name].ToString(), out tmpInt))
          {
             prop.SetValue(sender, tmpInt);
          }
          break;
      case "Boolean":
          bool tmpBool = false;
          if (!DBNull.Value.Equals(rowFromDatabase[prop.Name]) && bool.TryParse(rowFromDatabase[prop.Name].ToString(), out tmpBool))
          {
             prop.SetValue(sender, tmpBool);
          }
          break;
          ..............
          continued...
          ..............
   }
}

I want to be able to access some kind of metadata on a parameter that is accessible via the prop variable shown above where I can specify some kind of extra information. How can I do this?

EDIT: I'd like to set the metadata like this

[CustomTag]
public Guid ID { get; set; }
Was it helpful?

Solution

Extend the class System.Attribute then decorate your properties with your custom attributes.

For example:

public class ReadOnlyAttribute : System.Attribute
{
}

or

public class DbColumnInfoAttribute : System.Attribute
{
    public string ColumnName {get; set; }
    public bool Required { get; set; }

    public DbColumnInfoAttribute( string name, bool req){
       ColumnName = name;
       Required = req;
    }
}

Then use them:

public class YourClass
{

   [ReadOnly]
   [DbColumnInfo( "User_Name", true)]
   public string UserName { get; set; }

}

To read them via Reflection:

var listOfAttrib = prop.GetCustomAttributes(typeof(MyAttribute), true);

I would recommend that ALL of your attribute classes extend a common class so you can get all custom properties without having to know the exact attribute you're looking for otherwise you'll end up having to fire multiple GetCustomAttributes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top