Skip to content

Extending the C# Registry-based configuration class.

So we now have our RegistryConfig class ready…but how can we make it better?!

Use reflection!

We will use reflection to perform initialization on the classes properties, so that the settings can be added to the registry straight away. This will ensure that the registry has all the properties you have set up in your class have been initialized in the registry with the default values.

Getting the classes properties

The method below will get a list of all the properties in your class!

protected virtual IEnumerable<PropertyInfo> GetProperties()
{
    return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.GetProperty);
}

We mark this as virtual so we can filter out properties we don’t want to initialize into the registry.

Here is the initialization method

public void Initialize()
{
    foreach (var propInfo in GetProperties())
    {
        try
        {
            if (propInfo != null)
            {
                var o = propInfo.GetValue(this, null);
            }
        }
        catch (Exception ex)
        {
            Trace.TraceError("Failed to initialize {0}: {1}", propInfo.Name, ex);
        }
    }
}

This will invoke the getter in each of the properties that will add the value to the registry if it doesn’t exist

The following method will be used for when we start making some sub-classes! It is just a little helper function to parse the property name.

protected static string ParsePropertyMethodName(string methodName)
{
    if (methodName.StartsWith("get_") || methodName.StartsWith("set_"))
        methodName = methodName.Substring(4);
    return methodName;
}


Next we will make a subclass that we can use in a .NET program.

Published in.NETC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *