CraftMine3001 CraftMine3001 - 1 month ago 7
C# Question

How to shorten the usage of methods in C#?

I have many string variables like this;

string x1, x2, x3, x4, x5, x6, x7, x8;


Is it possible to shorten this code

method(x1);
method(x2);
method(x3);
method(x4);
method(x5);
method(x6);
method(x7);
method(x8);


so I can use something like this instead (This below doesn't work):

for(int i = 1; i <= 8; i++)
{
method("x" + i);
}


Thanks in advance!

Answer

Use an array for all these strings:

string[] data = new []
{
    "string1",
    "string2",
    "string3",
    "string4",
    x1,
    x2,
    x3,
    x4
};

foreach(var item in data)
{
    method(item);
}

With arrays it is the same, just have a collection of arrays:

var data = new List<string[]>
{
    new [] {"1","2","3"},
    new [] {"a","b","c"},
};

foreach(var item in data)
{
    method2(item); //notice that this method must get as a parameter a string[]
}