Click to See Complete Forum and Search --> : How can I 'return' an array of values


dejan1
May 6th, 2008, 11:18 PM
How can I return an array of values in C# (instead of the usual just one string or int or double, etc? I want to return an array of strings....
Thanks

Arjay
May 7th, 2008, 12:06 AM
While you can manually create an array of objects, an easier way to do it is to use a generic list (or array):

public string[] GetStrings( )
{
List< string > list = new List< string >( );

list.Add( "string1" );
list.Add( "string2" );

return list.ToArray( );
}

cjard
May 7th, 2008, 02:10 AM
Why didnt you just try it?

//if you know how to do this:
public string GetString(){
string s = "s";
return s;
}

//try this
public string[] GetStrings(){
string[] s = {"s","t"};
return s;
}

at a guess, i'd say you forgot to change the return type (underlined) of the method, and you were trying to return a string[] via a string

C# would give an error something like "no implicit conversion exists between string[] and strong"

boudino
May 7th, 2008, 03:32 AM
As cjar said: the answer is in the question itself :)

dejan1
May 7th, 2008, 07:15 AM
Ok guys, here's the tough part though...I'm trying to call that method GetStrings() to display on a checkbox list once a button is clicked. GetStrings() is actually in a dll file....So the difficulty I'm having is displaying the items in the array in GetStrings onto the checkbox list....
Any ideas?
Thanks again

cilu
May 7th, 2008, 08:52 AM
So, you're saying that you have an assembly, where there is a class with a method GetStrings, and you want to call this method and it should display some strings in a checkbox list? That is completely wrong. That method should return a list, and in your code you take that list and populate the control with its elements.

dejan1
May 7th, 2008, 11:48 AM
Well, cilu, it is returning a list....
this is what you mean right?

return list.ToArray( );