Using a statement to change the variable used

I want to use the using statement, but I may need to change the value of the variable that I "use" if the object it points to does not exist.

I thought of something similar (for access to the registry and 32/64 windows - although this is my current use case, this is a general question):

using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform"))
{
    if (key == null)
        key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform");
    // use key
}

The above code does not compile:

error CS1656: Cannot assign to 'key' because it is a 'using variable'

I can solve this without using use, but try / catch / finally and / or testing if the registry key exists before using it.

Is there a way to keep using when the correct object is deleted after?

+4
source share
3 answers

Maybe Null is merging?

using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform") ?? Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform"))
{

    // use key
}
+4

if using:

var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform");
if (key == null)
        key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform");

//prob best to null check
if (key != null)
{
  using (key)
  {

      // use key
   }
}

FYI , , using :

readonly IDisposable item;
try
{

}
finally
{
   item.Dispose();
}

readonly, , using.

+3

All Articles