2

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
  • 22,677
  • 21
  • 86
  • 100

2 Answers2

13

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
  • 20,083
  • 9
  • 69
  • 114
1

You can try the following:

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