Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Convert array to use in params with additional parameters

Tags:

arrays

c#

params

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()?

like image 297
AHalvar Avatar asked Nov 07 '12 10:11

AHalvar


Video Answer


1 Answers

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.

like image 118
Jan Avatar answered Oct 03 '22 17:10

Jan