views:

71

answers:

2

In relation to my last question (http://stackoverflow.com/questions/1588135/is-there-an-easier-way-of-passing-a-group-of-variables-as-an-array)

I was trying to pass string variables to a method to write to a stream, rather than doing the writing in each individual method.

The use of the params keyword is obviously a solution, however by using it I believe I can't do things like this:

Write("hello {0}",var1);

Which without makes the code quite messy. Is there a way to force this feature to my own methods?

+6  A: 
void MyMethod(string format, params object[] obj) {
    var formattedString = String.Format(format, obj);
    // do something with it...
}
Mehrdad Afshari
You may have missed the question? What I'd like to be able to do is pass arguments into a string when passing the whole thing as an argument to another method.All I can do at the moment is this:Write("Hello ",var1);which when dealing with long strings becomes very messy.I'd like to be able to do this:Write("Hello {0}",var1);
George
George: I can't see what you can't do right now. The output of `String.Format` is a string with `{0}`, `{1}` replaced by value of the respective argument.
Mehrdad Afshari
Ignore the comment, I just understood what you did :VThanks.
George
George: This is exactly what he's doing here. You get "formattedString" to work with, which will put that together for you.
Reed Copsey
+1  A: 

A method that has the params keyword can be passed an explicit array or an inline array.

Therefore, you can write the following:

public static void Write(params string[] stringsToWrite) {
    //...
    writer.WriteLine("Hello {0} {1} {2}", stringsToWrite);
    //...
}

EDIT Your question is unclear. If your asking whether a params array parameter can be given only one value, the answer is yes.

For example:

Write("myString");

The reason that many params methods in .Net have separate overloads that take just one parameter is to avoid creating an array for optimization reasons.

SLaks