1

I would like to do something like the following in C#, but I can't figure out how to instantiate any of the container types in place:

foreach (string aOrB in new Tuple("A","B"))
{
    fileNames.Add("file" + aOrB + ".png");
}

I know the typical way it to create the Tuple/Array/Set container in the surrounding scope. Is there something better?

Andrew Wagner
  • 20,197
  • 19
  • 75
  • 95

2 Answers2

12

As far as I understand, you want to provide a set of items defined ad-hoc for your loop. You can do this with the array initialization syntax:

foreach (string aOrB in new[] { "A", "B" })
{
    fileNames.Add("file" + aOrB + ".png");
}

This is already a shortened form of

foreach (string aOrB in new string[] { "A", "B" })
{
    fileNames.Add("file" + aOrB + ".png");
}

(the long form would be necessary if the compiler could not figure out the array element type from the elements)

O. R. Mapper
  • 19,469
  • 9
  • 63
  • 110
1

You can try the following:

foreach(string aOrB in new List<string>() { "a", "b" })
{
    fileNames.Add("file" + aOrB + ".png");
}
Chris Wohlert
  • 611
  • 3
  • 12