Using C# attribute as a variable

June 7, 2014

Just for fun, let's try treating a variable attribute like a normal variable. That is, setting and getting values at will. Here is a simple attribute class in a C#
[AttributeUsage(AttributeTargets.Property)]
public class SpecialAttribute : Attribute
{
    public int Index { get; set; }	
    public SpecialAttribute()
    {
    }
}
And a class with a variable decorated by the SpecialAttribute
public class SampleClass
{
    [Special(Index=55)]
    public string Text { get; set; }
      ...
}
To get attribute value, in this case 55, we first query the variable property and then its attribute.
public int getAttribute()
{
    var textVar = TypeDescriptor
                  .GetProperties(this.GetType())["Text"];
    var attr = (SpecialAttribute)textVar
               .Attributes[typeof(SpecialAttribute)];
    return attr.Index; 
}
And to set attribute value, first get attribute's property. Then using SetValue() function, update the attribute to a new value.

public void setAttribute(int index)
{
    var textVar = TypeDescriptor
                  .GetProperties(this.GetType())["Text"];
    var attr = (SpecialAttribute)textVar
               .Attributes[typeof(SpecialAttribute)];
    var attProp = typeof(SpecialAttribute)
                  .GetProperty("Index");
    attProp.SetValue(attr, index, null);
}
Updating attribute value effects only current run-time. Reinitializing the object resets the value back to 55.

Entire example on github.