1

is it possible to accept more than one entires,as variables, and then change it to an array! as for example, the user would enter more than one name, but not defined how many names they should enter, and when I received the names I would change it to an array, is that possible ?

Thanks!

4
  • 1
    How is the user entering the names? Commented Oct 28, 2011 at 17:44
  • 1
    What do you mean by "accept more than one entires,as variables"? Is your data entry needing to display a dynamic number of input fields or are you wanting to split arbitrary input from one field into multiple variables (such as spliting by comma or something else)? Ultimately, your results can be stored in a List<T> or a fixed-length array (created once you know how many elements you have). Commented Oct 28, 2011 at 17:49
  • @MiguelAngelo for example, as prompt the app asks the user to enter their favorite name of songs.. Commented Oct 29, 2011 at 11:23
  • @DanC Thanks, yes, that is the case, and I will try to separate them and see what I can do with it! Commented Oct 29, 2011 at 11:25

3 Answers 3

10

In .NET arrays have fixed length. If you want to be able to dynamically add elements to a list you could use the List<T> class.

For example:

List<string> names = new List<string>(); 

Now you could start adding elements to the list:

names.Add("foo"); names.Add("bar"); names.Add("baz"); 

And you could also get the corresponding fixed length array using the ToArray() method:

string[] namesArray = names.ToArray(); 
Sign up to request clarification or add additional context in comments.

3 Comments

And if you really, really, need an array, use the ToArray() method of List.
Thanks Darin, that is a very interesting approach!
Late to the party, but ToArray() is not a method of List, but rather an extension method of IEnumerable<T>, which List<T> implements.
2

I think what you're looking for is the param object []. It's used for an undetermined number or parameters into a function. Your function would go like this:

public static void SayHello(params string[] names){ foreach(var name in names){ Console.WriteLine("Hello " + name); } } 

And you could call it like this:

SayHello("Bob", "Bill", "Susan"); SayHello("Jenny"); 

Comments

0

If the user is going to enter more than one name, then I suggest you create a list of strings instead of an array.

1 Comment

I have thought about that as well, but this Prof of mine dont want to use something that he didn't cover! at least he wants to be fair on the skill of other students! Thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.