user1051477
user1051477

Reputation: 117

How to "out" an array of strings and pass it through into a listbox

This is a part of UpdateGUI():

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings);
listBox1.Items.Clear();
listBox1.Items.AddRange(strSeatInfoStrings);

The compiler is complaining about this row (And the parameter of the last row):

seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings);

What I'm trying to do is to take an array (strSeatInfoStrings) and put it inside a listbox.

Any ideas?

Upvotes: 1

Views: 1891

Answers (2)

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

This smells more like a code design issue. The method name GetSeatInfoStrings clearly expresses that it returns some strings. Based on your use of the method, it looks like it's declared like so:

public void GetSeatInfoStrings(string choice, out string[] result)

In my opinion, it would be far better to declare it like this instead:

public void IEnumerable<string> GetSeatInfoStrings(string choice)

...and just return the array from the method as you normally would. The primary uses for out, as I see it is when you need to return more than one value from the method. The Int32.TryParse method is a great example; the method returns a bool indicating success, and the out parameter will contain the result.

In your case it seems as if you have one result, so using out will only be confusing.

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

You have to add the declaration of that variable before the call:

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
string[] strSeatInfoStrings;
seatMngr.GetSeatInfoStrings(choice, out strSeatInfoStrings); 
listBox1.Items.Clear(); 
listBox1.Items.AddRange(strSeatInfoStrings); 

The other oppinion is to change the signature of your method and return the values, so you can write this

DisplayOptions choice = (DisplayOptions)comboBox1.SelectedIndex;
listBox1.Items.Clear(); 
listBox1.Items.AddRange(seatMngr.GetSeatInfoStrings(choice)); 

Upvotes: 2

Related Questions