0

In relation to my last question (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?

Community
  • 1
  • 1
George
  • 1,964
  • 2
  • 19
  • 25

2 Answers2

6
void MyMethod(string format, params object[] obj) {
    var formattedString = String.Format(format, obj);
    // do something with it...
}
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 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 Oct 30 '09 at 17:08
  • 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 Oct 30 '09 at 17:11
  • Ignore the comment, I just understood what you did :V Thanks. – George Oct 30 '09 at 17:11
  • George: This is exactly what he's doing here. You get "formattedString" to work with, which will put that together for you. – Reed Copsey Oct 30 '09 at 17:11
1

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
  • 868,454
  • 176
  • 1,908
  • 1,964