15

I have a method that takes params. Inside the method another variable shall be added to the output:

private void ParamsTest(params object[] objs)
{
  var foo = "hello";
  // Invalid: Interpretes objs as single array parameter:
  Console.WriteLine("{0}, {1}, {2}", foo, objs);
}

When I call

ParamsTest("Hi", "Ho");

I would like to see the output.

hello Hi Ho

What do I need to do?

I can copy foo and objs into a new array and pass that array to WriteLine but is there a more elegant way to force objs to behave as params again? Kind of objs.ToParams()?

1
  • Do not get sidetracked by the Console.WriteLine example or the format string. This is not my real issue. Real question: How can I make WriteLine see 4 (format, foo and 2 array elements) args instead of 3 (format, foo and array). Commented Nov 7, 2012 at 13:07

4 Answers 4

11

If your problem is just to add another element to your array, you could use a List

List<object> list = new List<object> { "hello" };
list.AddRange(objs);
Console.WriteLine("{0}, {1}, {2}, ...", list.ToArray());

params is not a datatype. The parameters datatype is just still a plain array.

Sign up to request clarification or add additional context in comments.

2 Comments

This is my current solution. So no way to do this more elegantly, i.e. without allocating a list and copying objects around?
The problem is, that you can't resize an array in .NET. So either use another collection datatype or copy values around.
6

I would use string.Join to do the formatting:

Console.WriteLine("{0}, {1}", foo, string.Join(", ", objs));

1 Comment

This solves the problem for the Console.WriteLine example, but naturally :) WriteLine is not my real problem, just a (too simple?) illustration.
1

You can use foreach loop like this

string objsString = string.Empty;
foreach (var ob in objs)
    objsString += ", " + ob.ToString();
Console.WriteLine("{0}{1}", foo, objsString);

Or there is even better way:

string paramsString = string.Join(", ", objs);
Console.WriteLine("{0}, {1}", foo, paramsString );

Comments

0

Loop through the params array

var foo = "hello";
Console.Write(foo);
objs.ForEach(obj => Console.Write(", {0}", obj.ToString()));
Console.WriteLine();

Or use String.Join() to create a string representation of the array.

var foo = "hello";
string output = String.Join(", ", objs);
Console.WriteLine("{0}, {1}", foo, output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.