Skip to content

Deriving from our RegistryConfig class!

Now we have our abstract RegistryConfig class ready to use we can create our new subclass. This will hopefully show you how easy it is to create properties that utilize the methods of the RegistryConfig class!

Creating our subclass

Lets call our new class TestConfig and build a constructor that will pass some parameters down the RegistryConfig class.

public sealed class TestConfig : RegistryConfig
{
    public TestConfig()
        : base(RegistryHive.CurrentUser, @"SOFTWARE\Test")
    {
    }
}

This will create a new subkey at HKEY_CURRENT_USER\SOFTWARE\Test, which is where all our properties will be stored.

Setting up a new property

The properties should use the GetValue and SetValue! It will also be easy to create new properties without too much change to the code. We can do this with reflection and our ParsePropertyMethodName function we have in the RegistryConfig class.

public string TestSetting1
{
    get
    {
        return GetValue(ParsePropertyMethodName(MethodBase.GetCurrentMethod().Name), string.Empty);
    }
    set
    {
        SetValue(ParsePropertyMethodName(MethodBase.GetCurrentMethod().Name), value);
    }
}

The ParsePropertyMethodName basically strips out the get_ or set_ from the method name.

And there we have it!

This is what the new class should look like.

public sealed class TestConfig : RegistryConfig
{
    public string TestSetting1
    {
        get
        {
            return GetValue(ParsePropertyMethodName(MethodBase.GetCurrentMethod().Name), string.Empty);
        }
        set
        {
            SetValue(ParsePropertyMethodName(MethodBase.GetCurrentMethod().Name), value);
        }
    }

    public TestConfig()
        : base(RegistryHive.CurrentUser, @"SOFTWARE\Test")
    {
    }
}

When you first initialize a new instance of your RegistryConfig class you should probably call Initialize to set up the registry.

Published in.NETC#

Be First to Comment

Leave a Reply

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