KNOW IF A VARIABLE EXISTS

1

I want to know if a variable has already been created. I have an IF that instantiates a class and a variable is initialized.

if (nivel == "1")
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlGenericControl a = new HtmlGenericControl("a");
HtmlGenericControl ul = new HtmlGenericControl("ul");
tree2.Controls.Add(li);
a.Attributes.Add("href", "#");
a.InnerHtml = titulo;  //nivel 1
li.Controls.Add(a);
}

In this case I want to know if the variable li was already created. Something like this:

if(exists li){
 if (nivel == "2")
  {
     HtmlGenericControl ul2 = new HtmlGenericControl("ul");
     li.Controls.Add(ul2);
     HtmlGenericControl li2 = new HtmlGenericControl("li");
     ul2.Controls.Add(li2);
     HtmlGenericControl a2 = new HtmlGenericControl("a");
     a2.Attributes.Add("href", "#");
     a2.InnerHtml = nombre;
     li2.Controls.Add(a2);
     HtmlGenericControl ul3 = new HtmlGenericControl("ul");
     li2.Controls.Add(ul3);
   }
}

Since that variable is only created at runtime, I need to make that condition.

    
asked by JiMel 26.10.2018 в 18:36
source

1 answer

3

The variables have a scope in which they can be accessed, if you define the variable within a block if will only be accessed within it, now if you define it outside as being

HtmlGenericControl li = null;

if (nivel == "1")
{
   i = new HtmlGenericControl("li");
   //resto codigo
}

You could use the later to ask if it was instantiated or not

if(i != null){
   //fue instanciada
}
    
answered by 26.10.2018 / 21:24
source