C Sharp

Field Attributes

In the last example of querying members as to their attached attributes, we'll look at how to query a class's fields. Let's say you have a class that contains some fields the values of which you want to save in the Registry. To do that, you could define an attribute with a constructor that takes as its parameters an enum representing the correct Registry hive and a string representing the Registry value name. You could then query the field at run time as to its Registry key: -

using System;
using System.Reflection;
public enum RegistryHives
{
    HKEY_CLASSES_ROOT,
    HKEY_CURRENT_USER,
    HKEY_LOCAL_MACHINE,
    HKEY_USERS,
    HKEY_CURRENT_CONFIG
}
public class RegistryKeyAttribute : Attribute
{
    public RegistryKeyAttribute(RegistryHives Hive, String ValueName)
    {
        this.Hive = Hive;
        this.ValueName = ValueName;
    }
    protected RegistryHives hive;
    public RegistryHives Hive
    {
        get { return hive; }
        set { hive = value; }
    }
    protected String valueName;
    public String ValueName
    {
        get { return valueName; }
        set { valueName = value; }
    }
}
class TestClass
{
    [RegistryKey(RegistryHives.HKEY_CURRENT_USER, "Foo")]
    public int Foo;
    public int Bar;
}
class FieldAttrApp
{
    public static void Main()
    {
        Type type = Type.GetType("TestClass");
        foreach(FieldInfo field in type.GetFields())
        {
            foreach (Attribute attr in field.GetCustomAttributes())
            {
                RegistryKeyAttribute registryKeyAttr =
attr as RegistryKeyAttribute;
                if (null != registryKeyAttr)
                {
                    Console.WriteLine
                        ("{0} will be saved in {1}\\\\{2}",
                         field.Name,
                         registryKeyAttr.Hive,
                         registryKeyAttr.ValueName);
                }
            }
        }
    }
}

I won't walk through all of this code because some of it is duplicated from the previous example. However, a couple of details are important. First notice that just as a MethodInfo object is defined for retrieving method information from a type object, a FieldInfo object provides the same functionality for obtaining field information from a type object. As in the previous example, we start by obtaining the type object associated with our test class. We then iterate through the FieldInfo array, and for each FieldInfo object, we iterate through its attributes until we find the one we're looking for: RegistryKeyAttribute. If and when we locate that, we print the name of the field and retrieve from the attribute its Hive and ValueName fields.