Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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
Posted: Aug 20 2009, 01:37 PM by DigiMortal | with 9 comment(s)
Filed under: ,

Comments

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# August 20, 2009 6:49 AM

DotNetBurner - Windows Forms said:

DotNetBurner - burning hot .net content

# August 20, 2009 6:50 AM

PimpThisBlog.com said:

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

# August 20, 2009 6:51 AM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# August 20, 2009 6:52 AM

progg.ru said:

Thank you for submitting this cool story - Trackback from progg.ru

# August 20, 2009 6:53 AM

9eFish said:

9efish.感谢你的文章 - Trackback from 9eFish

# August 20, 2009 6:54 AM

bin said:

looks very handy :) Thx!

# August 21, 2009 11:53 AM

Henrique said:

instead of:

try

{

  return (T)obj;

}

catch(InvalidCastException)

{

}

you should use:

if(obj is T)

  return (T)obj;

Always avoid an exception where is possible.

Anyway, I liked your idead, but I think things as GetInt32, GetBoolean, GetString would be more handy.

# August 21, 2009 6:40 PM

DigiMortal said:

Thanks for feedback, Henrique :)

I chose generic method because I didn't want to introduce more than one method.

# August 22, 2009 3:18 AM