simple out parameter as ArrayList

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Why is it that I get these errors on this function

1.) The out parameter 'Avalues' must be assigned to before control leaves
the current method
2.) Use of unassigned local variable 'Avalues'

public bool getStringFieldAsArrayList( out ArrayList Avalues)
{
bool retVal=false ;
Avalues.Add("fooAvalues");
return retVal;
}


BUT NOT for this:
public void getOutString( out string test)
{
test ="foo";
}
They seem to be constructed the same way...
-
Andrew
 
andrewcw said:
Why is it that I get these errors on this function

1.) The out parameter 'Avalues' must be assigned to before control leaves
the current method
2.) Use of unassigned local variable 'Avalues'

public bool getStringFieldAsArrayList( out ArrayList Avalues)
{
bool retVal=false ;
Avalues.Add("fooAvalues");
return retVal;
}

BUT NOT for this:
public void getOutString( out string test)
{
test ="foo";
}
They seem to be constructed the same way...

No they're not. An out parameter *must* be assigned to before the end
of the method (unless you're throwing an exception) and is treated as
unassigned until you've assigned to it.

For the second point, think of it like a local variable - it's like
you're trying to do:

ArrayList Avalues;
Avalues.Add("fooAvalues"); // This wouldn't work

and in the second case

string test;
test = "foo";

In the second case, you're assigning to the variable. In the first case
you're trying to use the value as if it's already assigned.
 
because you don't need the 'out' modifier at all. If all you are trying to
do is add an element to an array, then you are NOT modifying the value of
the Avalues variable. You are modifying the list that the variable points
to.

Remove the 'out' keyword and your method will not only compile, it will
work.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Thank you Jon and Nick. I understand now I dont need the out. I understand
also now that the 2 functions are different.

I did not understand what it meant to assign in the ArrayList case. I had
wondered if it was because an ArrayList is an object , but I simply did not
understand what assign means as in terms of an ArrayList
.. Now I figured out with your suggestions -> .
Avalues= new ArrayList(); //inside the functions makes it compile

Thanks !!
 
Back
Top