Jump to content
  • Advertisement
Sign in to follow this  
u235

[.net] conersion of object to value type

This topic is 4636 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
In one of my application I'm doing it this way and it is working fine:

Dim x As Integer
Dim defaultX as integer = SOMEDEFAULTVALUE
Dim regKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(PathInRegistryToSubKey)
x = regKey.GetValue(KeyName,defaultX)


Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!