Search code examples
c#variablesunassigned-variable

Use of unassigned bool? local variable


i have this:

   foreach (Software.dsBDD.list_table21 row in dataTable.Rows)
        {
            PictureBox box;
            MemoryStream stream;
            Panel panel;
            Label label;
            bool? pass;
            if (this.pass.HasValue && this.end)
            {
               pass = this.pass;
            }
            if ((pass.GetValueOrDefault() && pass.HasValue) || row.view_only)
        }

Variable "pass" near "GetValueOrDefault" underlined as an error: "Use of unassigned local variable pass". I don`t understand why this variable is unassigned because in the same line there is "pass" near "HasValue" and it is assigned. Where is my syntax error?!


Solution

  • You want to do either of these:

    Make sure you assign to your local pass before using it: On each iteration the local pass will be restored to null.

       foreach (Software.dsBDD.list_table21 row in dataTable.Rows)
            {
                PictureBox box;
                MemoryStream stream;
                Panel panel;
                Label label;
                bool? pass = null; //this line has changed
                if (this.pass.HasValue && this.end)
                {
                   pass = this.pass;
                }
                if ((pass.GetValueOrDefault() && pass.HasValue) || row.view_only)
            }
    

    Use normal bool instead of a nullable one, on each iteration the local pass will be set to default value, i.e. false:

       foreach (Software.dsBDD.list_table21 row in dataTable.Rows)
            {
                PictureBox box;
                MemoryStream stream;
                Panel panel;
                Label label;
                bool pass; //this line has changed
                if (this.pass.HasValue && this.end)
                {
                   pass = this.pass;
                }
                if ((pass.GetValueOrDefault() && pass.HasValue) || row.view_only)
            }
    

    Define pass before the foreach scope if you need to use value from previous iteration in next iteration as well:

       bool? pass = null; //this line has changed
       foreach (Software.dsBDD.list_table21 row in dataTable.Rows)
            {
                PictureBox box;
                MemoryStream stream;
                Panel panel;
                Label label;
    
                if (this.pass.HasValue && this.end)
                {
                   pass = this.pass;
                }
                if ((pass.GetValueOrDefault() && pass.HasValue) || row.view_only)
            }
    

    I am afraid these are the only options you have, if pass contains the value you actually need.