David G

David G

  • NA
  • 58
  • 1.1k

C# variable defined then redefined issue

Jun 5 2017 11:54 AM

Hey all I have a question that may or may not have the answer I am looking for.

I want to set the variable _data to something generic so that I can set it again with the proper class name in an if statement.

Example is:

  1. public static void whichStatus(string dataName, object data, sessionVars sVars)  
  2. {  
  3.    if (dataName == "SAVE_PNo_tTrip")  
  4.    {  
  5.        object _data; //This is where I attempt to set the variable generic  
  6.        var pageName = data.GetType().DeclaringType.Name;  
  7.   
  8.        if (pageName == "CAttend")  
  9.        {  
  10.             CAttend.SAVE_PNo_tTrip _data = (CAttend.SAVE_PNo_tTrip)data;   
  11.             //This is where I need to actually define the real data type for _data.  
  12.        }  
  13.        etc...etc...  
  14.    }  
  15.   
  16.    switch (sVars.userCategory.ToUpper())  
  17.    {  
  18.        case "CCLASS":  
  19.            //_data.ID;  
  20.            break;  
  21.        case "LNC":  
  22.            //_data.ID;  
  23.            //_data.Name;  
  24.            break;  
  25.        etc.. etc...  
  26.    }  

 

As you see from the above, I am trying to just set _data to something so that I actually define it in the if statement below it. I'll also need to access it from other places within that function so that's why I need to define it at the beginning. Though I am getting an error:

Error CS0136 A local or parameter named '_data' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

Is it at all possible to do this the way I am trying to do it?


Answers (2)