[.net] conersion of object to value type

Started by
2 comments, last by u235 18 years ago
I started working with the registry a little tonight and ran into a problem. I can create, open, and set subkey data just fine, but I have problems when trying to read that data. The GetValue method of the RegistryKey class returns an object, so naturally, one (ie. I) would think that a simple type cast would do the trick. But no, I got an InvalidCastException thrown. Then I broke out my trusty copy of "The C# programming Language" to find out about unboxing. Apparently, you can't unbox an object that wasn't previously created by boxing. But the book goes on to say:
Quote: If the source operand is a reference to an incompatible object, a System.InvalidCastException is thrown.
So I'm having trouble figuring out if my problems lies in the type i am trying to cast to (short) or if no cast will work because the object was never created by boxing. If the former, is there a workaround and if the latter, how do you cast an object to a value type if the object wasn't created by boxing? Thanks, I will be ever greatful to those who help me out here. -AJ
V/R,-AJThere are 10 kinds of people in the world: Those who understand binary and those who don't...
Advertisement
Have you tried using Convert.ToInt16()? Casting may not work in this case if the value is coming back as an Int32, but Convert should handle it just fine.
In one of my application I'm doing it this way and it is working fine:
Dim x As IntegerDim defaultX as integer = SOMEDEFAULTVALUEDim regKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(PathInRegistryToSubKey) x = regKey.GetValue(KeyName,defaultX)
Quote:Original post by DaWanderer
Have you tried using Convert.ToInt16()? Casting may not work in this case if the value is coming back as an Int32, but Convert should handle it just fine.


Perfect, many thanks.

Quote: Original post by RizMan
In one of my application I'm doing it this way and it is working fine:
**Code snippet removed**


Must be a VB thing, cause it works like that for me in VB, but I had tried that also before posting and it didn't work in C#. Thanks for the reply though.


-AJ
V/R,-AJThere are 10 kinds of people in the world: Those who understand binary and those who don't...

This topic is closed to new replies.

Advertisement