0

Can someone please tell me why the code below works but if I move the Application.Run(new Form1(env)) statement to be outside the brackets as in:

  if (key != null)
        {
            env = (string)key.GetValue("Environment");
            key.Close();
        }
 Application.Run(new Form1(env));     
        

it generates a message saying that env is an unassigned local variable

Code that works:

    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string env;
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\VB and VBA Program Settings\Fisk\Installation");
            if (key != null)
            {
                env = (string)key.GetValue("Environment");
                key.Close();
                Application.Run(new Form1(env));     
            }
        }
    }```
felix
  • 7
  • 4
  • Use `string env = null;` or remove that code and use `var env = (string)key.GetValue("Environment");` later. It is complaining that you aren't _always_ assigning a value to it. – mjwills Feb 21 '21 at 22:25
  • `string env = string.Empty;`. I would do something like `key.GetValue("Environment")?.ToString()`. FWIW, you should be disposing registry keys as well, not just close them. – Trevor Feb 21 '21 at 22:26
  • @Codexer while I agree you should typically `Dispose` anything implementing `IDisposable`, `RegistryKey.Close` is a single statement method which calls `Dispose(true)`. RegistryKey is a weird class in how it disposes, it will keep system keys open (a no-op) unless part of PerfData... So in some instances it's perfectly safe to not do anything at all – pinkfloydx33 Feb 21 '21 at 23:35

0 Answers0