Using switch in C# to handle all hives

Viewed 65

I was trying to use switch to handle all possibles hives from registry - later on, i want to generate SubKeyNames for key (together with hive) provided as an input, but i still get errors like: ‘A local variable named ‘regKey’ is already defined in this scope’ ‘The name ‘regKey’ does not exists in the current context’

switch (hive) {  

    case "HKEY_CLASSES_ROOT":

                   RegistryKey regKey=Registry.ClassesRoot.OpenSubKey(key,false);
                   break;                                 

    case "HKEY_CURRENT_USER":

                   RegistryKey regKey=Registry.CurrentUser.OpenSubKey(key,false);
                   break;  

    case "HKEY_LOCAL_MACHINE":

                   RegistryKey regKey=Registry.LocalMachine.OpenSubKey(key,false);
                   break;

    case "HKEY_USERS":

                   RegistryKey regKey=Registry.Users.OpenSubKey(key,false);
                   break;  

    case "HKEY_CURRENT_CONFIG":

                   RegistryKey regKey=Registry.CurrentConfig.OpenSubKey(key,false);
                   break;  

    default:
        throw new System.Exception("Incorrent hive");
}
2 Answers

If you want case you can try pattern matching (you need c# 8.0), e.g.

RegistryKey regKey = hive switch {
  "HKEY_CLASSES_ROOT"   => Registry.ClassesRoot.OpenSubKey(key, false),
  "HKEY_CURRENT_USER"   => Registry.CurrentUser.OpenSubKey(key, false),
  "HKEY_LOCAL_MACHINE"  => Registry.LocalMachine.OpenSubKey(key, false),
  "HKEY_USERS"          => Registry.Users.OpenSubKey(key, false),
  "HKEY_CURRENT_CONFIG" => Registry.CurrentConfig.OpenSubKey(key, false),
  _ => throw new NotSupportedException("Incorrent hive")
};

Or to get rid of pesky Registry ... OpenSubKey(key, false) you can move keys to Dictionary:

private static Dictionary<string, RegistryKey> s_RegRoots = 
  new Dictionary<string, RegistryKey>(StringComparer.OrdinalIgnoreCase) {
    {"HKEY_CLASSES_ROOT",   Registry.ClassesRoot},
    {"HKEY_CURRENT_USER",   Registry.CurrentUser},
    {"HKEY_LOCAL_MACHINE",  Registry.LocalMachine},
    {"HKEY_USERS",          Registry.Users},
    {"HKEY_CURRENT_CONFIG", Registry.CurrentConfig},
};

...


RegistryKey regKey = s_RegRoots.TryGetValue(hive, out var root)
  ? root.OpenSubKey(key, false)
  : throw new NotSupportedException("Incorrent hive");

I believe the error is that you are trying to declare the variable multiply times in the same program I would try moving the creation of the variable to outside your switch structure and then just assign a value to it during the switch structure

Related