Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement with changing used variable

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

I thought of something like this (for registry access and 32/64 windows - though 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
}

Above code does not compile:

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

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

Is there a way to keep using using, with the correct object being disposed afterwards?

like image 993
Andreas Reiff Avatar asked Dec 18 '22 17:12

Andreas Reiff


2 Answers

Maybe Null coalesce?

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

    // use key
}
like image 129
Wjdavis5 Avatar answered Jan 05 '23 02:01

Wjdavis5


Just take the if out of the 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
   }
}

Just as an FYI and to explain why you can do this, a using statement is just syntactical sugar for:

readonly IDisposable item;
try
{

}
finally
{
   item.Dispose();
}

Because it's marked as readonly this also explains why you can't assign to it within the using statement.

like image 44
Liam Avatar answered Jan 05 '23 04:01

Liam