Liam Dyer Megamawman Liam Dyer Megamawman - 1 month ago 9
C# Question

C#: Using String Value as name of Object Reference

At the moment, I have multiple textblocks which I want to access according to the name of the string. Look at the example below:

TextBlock test1 = new TextBlock();
TextBlock test2 = new TextBlock();
TextBlock test3 = new TextBlock();
TextBlock test4 = new TextBlock();

public static void changeValues()
{
string name = "test";
for (int i = 1; i < 5; i++)
{
[name + i].Text = "Wow";
}
}


As you can see, I am trying to access text1, text2, etc. The reason I am doing this is because the value of "name" could change at any time so I can re-use this code. I can also make "i < 5" be "i < number" and have the method take an int as one of the arguments. The problem of course is that this won't actually work. I need the string name to be a reference to the TextBlock that the name gives. Any help is appreciated!

Answer

@PetSerAl is saying:

var yourBlocks = new TextBlock[]
{
    new TextBlock(),
    new TextBlock(),
    new TextBlock(),
    new TextBlock()
};

foreach (var block in yourBlocks)
{
    block.Text = "Wow";
}