C# string array scope

The code below succeeds test 1, fails test 2.  How do I declare arrDataObject outside the if statement
so it is in scope for test 2?

            if(request.QueryString["dataobjects"] != null)
            {
                  string [] arrDataObject = request.QueryString["dataobjects"].Split(new Char [] {'~'}, StringSplitOptions.RemoveEmptyEntries);
                  response.Write("test 1" + arrDataObject[0] );
            }

response.Write("test 2" + arrDataObject[0] );
maxdbaseAsked:
Who is Participating?
 
AndyAinscowFreelance programmer / ConsultantCommented:
string [] arrDataObject =null;
 if(request.QueryString["dataobjects"] != null)
            {
                  arrDataObject = request.QueryString["dataobjects"].Split(new Char [] {'~'}, StringSplitOptions.RemoveEmptyEntries);
                  response.Write("test 1" + arrDataObject[0] );
            }
if(arrDataObject != null)
  response.Write("test 2" + arrDataObject[0] );
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
ps.  You will need to test before the second response because arrDataObject could be null - which results in you program crashing if you try to access it when it is null.
0
 
Ryan ChongCommented:
try like:

 How do I declare arrDataObject outside the if statement
so it is in scope for test 2?

  string [] arrDataObject;

            if(request.QueryString["dataobjects"] != null)
            {
                  arrDataObject = request.QueryString["dataobjects"].Split(new Char [] {'~'}, StringSplitOptions.RemoveEmptyEntries);
                  response.Write("test 1" + arrDataObject[0] );
            }
//try check the arrDataObject.length when necessary else you may get error below
response.Write("test 2" + arrDataObject[0] );
0
 
Ryan ChongCommented:
sorry, ignore my last comment as it may not work.
0
 
maxdbaseAuthor Commented:
Great solution!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.