Stuck in function and booleans

寵の児 提交于 2019-12-20 07:49:08

问题


I have function called firstRun(), inside of it I have two defined booleans filesDeleted and dirsDeleted.

Also inside in function I have if (filesDeleted == true && dirsDeleted == true) {
When I try to debug application I get error - Use of unassigned local variable 'filesDeleted' and Use of unassigned local variable 'dirsDeleted' tried a lot of different solutions, did not work at all.

Here's the code:

private void firstRun(bool forceDelete) {
  string Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myLauncher");
  string[] Files = Directory.GetFiles(Path);
  string[] Dirs = Directory.GetDirectories(Path);
  bool filesDeleted; 
  bool dirsDeleted;

  if (forceDelete == true)
  {
      if (Directory.Exists(Path))
      {
          string lastFile = Files[Files.Length - 1];
          foreach (string file in Files)
          {
              if (file == lastFile)
              {
                  filesDeleted = true;
                  MessageBox.Show("test");
              }
              File.Delete(file);
          }
          string lastDir = Dirs[Dirs.Length - 1];
          foreach (string dir in Dirs)
          {
              if (dir == lastDir)
              {
                  dirsDeleted = true;
                  MessageBox.Show("test2");
              }
              Directory.Delete(dir, true);

          }
          if (filesDeleted == true && dirsDeleted == true)
          {
            //code when everything deleted
          }
      }
      else
      {
          Directory.CreateDirectory(Path);
      }
  }

回答1:


Change your

bool filesDeleted;
bool dirsDeleted;

to

bool filesDeleted = false;
bool dirsDeleted = false;

These are local variables and they must be assinged before use them.

From 5.1.7 Local variables

A local variable is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable is considered initially unassigned.




回答2:


Unlike class member variables, local variables in methods do not have a default value, and must be definitely assigned before you try and read from them:

so you need to use

bool fileDeleted = false;
bool dirsDeleted = false;

instead of

bool filesDeleted;
bool dirsDeleted;


来源:https://stackoverflow.com/questions/18419280/stuck-in-function-and-booleans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!