Search code examples
c#registryusingnull-coalescing-operator

C#: Is there a clean pattern for finding the right object combined with using?


I would like a clean/compact pattern that is exception safe and will properly dispose rulesKey, even if something has thrown. This does not appear to be possible with using (unless maybe 4 usings but that seems so verbose and opening extra resources that I might not even need opened). What gets me is that this would be so direct/easy in C++. Is there a good solution?

{
    RegistryKey rulesKey = null;
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product");

    // Code using rulesKey, might throw

    rulesKey.Close();
}

Solution

  • You could use

    using (RegistryKey rulesKey = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product")
                                    ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product")
                                    ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product")
                                    ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product"))
    {
        //use rulesKey here
    }
    

    Since

    The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. MSDN