From: Mike Lovell on
"Rich P" <rpng123(a)aol.com> wrote in message
news:#AGRy9JwKHA.3764(a)TK2MSFTNGP04.phx.gbl...
> Thank you again for your reply. I did play around with your sample
> suggestions and eventually got brave and tried the sameple from BOL
> which ended up working. Here is what I tried (not using var)
>
> //Delete and recreate the test key.
>
> Registry.CurrentUser.DeleteSubKey("ImgViewerCsharp2008\\TimeInterval",
> false);
> RegistryKey rk =
> Registry.CurrentUser.CreateSubKey("ImgViewerCsharp2008\\TimeInterval");
> rk.Close();
>
> // Obtain an instance of RegistryKey for the CurrentUser registry root.
>
> RegistryKey rkCurrentUser = Registry.CurrentUser;
>
> // Obtain the test key (read-only) and display it.
>
> RegistryKey rkTest =
> rkCurrentUser.OpenSubKey("ImgViewerCsharp2008\\TimeInterval",true);
> rkTest.SetValue("TimeInt", "3");
> Console.WriteLine("Test key: {0}", rkTest.GetValue("TimeInt"));
>
> --and I get a 3 in the console window.
>
> rkTest.Close();
> rkCurrentUser.Close();
>
> Now I can read/write keys. Question: if I use "var" this would seem
> less verbose, but in the BOL sample they close their registrykey
> objects. Any wisdom on how var deals with this? Or is this a redundant
> step? Would GC close it for me (or is that only in VB.Net) ?

Yes, you should really close them. I'm lazy and just knocked up a quick
sample. Definitely close them, good practice. Eventually the garbage
collector will do it for you, but never the less, it's a good idea.

If you used 'var' to declare the object:

var rkTest =
rkCurrentUser.OpenSubKey("ImgViewerCsharp2008\\TimeInterval",true);

The compiler would work out it was of type 'RegistryKey' for you. So it's
identical to this:

RegistryKey rkTest =
rkCurrentUser.OpenSubKey("ImgViewerCsharp2008\\TimeInterval",true);

As far as Visual Studio and the compiler are concerned. It's a matter of
preference really. It more comes into play I guess if you're using
anonymous types and classes. I always var myself, but I'm sure other people
would always declare! I think it looks a bit ugly having to do this:

MyClass myClass = new MyClass();

I like this better:

var myClass = new MyClass();

After all, I know what I'm getting back in this case anyhow!

--
Mike
GoTinker, C# Blog
http://www.gotinker.com