GetValue<T>() extension method for RegistryKey class

I needed some elegant method to read registry values in my Live Writer Delicious bookmarks plug-in. RegistryKey has GetValue() method but it returns values as object. I wrote generic version of GetValue() as RegistryKey extension method. It returns you specified value from key and converts it to type you ask. If conversions are not successful then default value of given type will be used.

I have two overloads for GetValue<T>(). First of them wants only value name to be specified. Second one expects also default value that is returned in the case of problems. I give some credits to Tony Wright whose blog entry How to add a ToNumber C# language extension method to the String class calling TryParse using reflection gave me some directions.

Here are my extension methods in C# and VB.NET. Don’t forget to import Microsoft.Win32 namespace.

C#

public static T GetValue<T>(this RegistryKey key, string name)

{

    return key.GetValue<T>(name, default(T));

}

 

public static T GetValue<T>(this RegistryKey key, string name,
                            T defaultValue)

{

    var obj = key.GetValue(name, defaultValue);

 

    if (obj == null)

        return defaultValue;

 

    try

    {

        return (T)obj;

    }

    catch(InvalidCastException)

    {

    }

 

    if (typeof(T) == typeof(string))

    {

        obj = obj.ToString();

        return (T)obj;

    }

 

    var types = new[]{typeof(string),typeof(T).MakeByRefType()};

 

    var method = typeof (T).GetMethod("TryParse", types);

    if (method == null)

        return defaultValue;

 

    var valueString = obj.ToString();

    T value = defaultValue;

    var params = new object[] {valueString, value};           

 

    method.Invoke(obj, params);

    return (T)methodParams[1];

}


 
VB.NET

<System.Runtime.CompilerServices.Extension()> _

Public Function GetValue(Of T)(ByVal key As RegistryKey, ByVal name As String) As T

    Return key.GetValue(Of T)(name, Nothing)

End Function

 

<System.Runtime.CompilerServices.Extension()> _

Public Function GetValue(Of T)(ByVal key As RegistryKey, ByVal name As String, ByVal defaultValue As T) As T

    Dim obj = key.GetValue(name, defaultValue)

 

    If obj Is Nothing Then

        Return defaultValue

    End If

 

    Try

        Return DirectCast(obj, T)

    Catch generatedExceptionName As InvalidCastException

    End Try

 

    If GetType(T) Is GetType(String) Then

        obj = obj.ToString()

        Return DirectCast(obj, T)

    End If

 

    Dim paramTypes = New Type() {GetType(String), GetType(T).MakeByRefType()}

 

    Dim method = GetType(T).GetMethod("TryParse", paramTypes)

    If method Is Nothing Then

        Return defaultValue

    End If

 

    Dim valueString = obj.ToString()

    Dim value As T = defaultValue

    Dim methodParams = New Object() {valueString, value}

 

    method.Invoke(obj, methodParams)

    Return DirectCast(methodParams(1), T)

End Function


Example

And here is my little example in C# and VB.NET.

C#

var softKey = Registry.CurrentUser.OpenSubKey("Software");

var myKey = softKey.OpenSubKey("MyAppSettings");

 

showTitle.Checked = myKey.GetValue<bool>("ShowTitle",true);

showDescr.Checked = myKey.GetValue<bool>("ShowDescriptions");


 
VB.NET

Dim softKey As RegistryKey

Dim myKey As RegistryKey

 

softKey = Registry.CurrentUser.OpenSubKey("Software")

myKey = softKey.OpenSubKey("MyAppSettings")

 

showTitle.Checked = myKey.GetValue(Of Boolean)("ShowTitle", True)

showDescr.Checked = myKey.GetValue(Of Boolean)("ShowDescriptions")


That’s it. If you know better solution for reading registry keys or you find bugs here then please feel free to drop me a line. All your feedback is very welcome.


kick it on DotNetKicks.com pimp it Progg it 顶 Shout it

3 Comments

Comments have been disabled for this content.