Question

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?

Was it helpful?

Solution

void MyMethod(string format, params object[] obj) {
    var formattedString = String.Format(format, obj);
    // do something with it...
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top