Reputation: 115
It may be a little unnecessary, but I am looking for a way in C# to convert a String to a List< String > and pass it to a function all in one shot.
Let's say I have a function that takes a list of Strings and spits them out to the console.
public static void PrintStrings( List<String> messages )
{
foreach ( String message in messages )
{
Console.WriteLine( message );
}
//Do other things
}
Now assume there is a case where I want to have only one String passed into the function. This is my question: How can I call this method passing only one String without putting it into a list beforehand? I thought this would have worked:
PrintStrings( Convert.ToString( "mymessage" ).ToList() );
But it is flagged in Visual Studio as 'The best overloaded match for 'PrintStrings' has some invalid arguments. Any suggestions would be great!
Upvotes: 0
Views: 5586
Reputation: 48596
You can use the params
keyword to allow a variable number of arguments:
public static void PrintStrings(params string[] messages )
{
foreach ( String message in messages )
{
Console.WriteLine( message );
}
//Do other things
}
Now, you can pass either an array of string
s, a single string
, or even multiple string
s:
PrintStrings("hi");
PrintStrings("hi", "there");
PrintStrings(stringList.ToArray());
Note that this does become less efficient if you already have the List<string>
. The best way to get around that, though, is to just create an overload that accepts a single string
and operate on it accordingly:
public static void PrintStrings(string myString) { ... }
Finally, if you want to keep your current signature and not add an overload, you can call the method on a new List<string>
like so:
PrintStrings(new List<string>() { myString });
Upvotes: 1
Reputation: 17808
PrintStrings( (new string[] { "myMessage" }).ToList() );
edit - or maybe do an overload ie:
PrintStrings( "myMessage" );
public static void PrintStrings( string message )
{
AcutallyDoSomething( message );
}
public static void PrintStrings( List<String> messages )
{
foreach ( String message in messages )
{
AcutallyDoSomething( message );
}
//Do other things
}
private static void AcutallyDoSomething(string msg)
{
foreach ( String message in messages )
{
Console.WriteLine( message );
}
}
Upvotes: 0
Reputation: 69372
You could just create an overloaded method:
public static void PrintStrings( string message )
{
//Do other things
}
Upvotes: 1
Reputation: 6550
Try PrintStrings (new List<String>(new string[]{"String"}));
Or create an overload of PrintStrings that accepts a single string.
Btw, I think it's better to accept IEnumerable<String>
rather then List<String>
Upvotes: 3