Reputation: 3471
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!
Upvotes: 1
Views: 153
Reputation: 18895
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");
Upvotes: 2
Reputation: 24212
If the user is going to enter more than one name, then I suggest you create a list of strings instead of an array.
Upvotes: 0
Reputation: 1039448
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();
Upvotes: 10