NateM24 NateM24 - 11 days ago 4
C# Question

Looping variables using index C#

I looked for something relating to this, but could not find anything.

Is there a way to use an index that attaches to a variable?

What I have so far is:

string tagName1 = tagNameBoxAMT1.Text;
string tagName2 = tagNameBoxAMT2.Text;
string tagName3 = tagNameBoxAMT3.Text;
string tagName4 = tagNameBoxAMT4.Text;
string tagName5 = tagNameBoxAMT5.Text;
string tagName6 = tagNameBoxAMT6.Text;


and what I would like to have is:

for(int i = 0; i < 6; i++)
{
string tagName[i] = tagNameBoxAMTi.Text;
}


Is this possible?

Answer

Manage a list of such controls:

var tagNames = new List<YourControl>() {
    tagNameBoxAMT1, tagNameBoxAMT2, tagNameBoxAMT3, tagNameBoxAMT4, tagNameBoxAMT5, tagNameBoxAMT6
};

and then you can use it appropriately:

for(int i = 0; i < 6; i++)
{
    string tagNamei = tagNames[i].Text;
}

If tagNameBoxAMT1 and others are fields/properties, you could use Reflection to do it automatically but it is rather not recommended.

If you would like to go with Reflection approach, here is the sample code:

class SomeWindow
{
    private SomeControl tagNameBoxAMT1;
    private SomeControl tagNameBoxAMT2;
    private SomeControl tagNameBoxAMT3;

    public SomeWindow()
    {
        tagNameBoxAMT1 = new SomeControl() { Text = "Text1" };
        tagNameBoxAMT2 = new SomeControl() { Text = "Text2" };
        tagNameBoxAMT3 = new SomeControl() { Text = "Text3" };
    }

    public void GiveMeWithReflection()
    {
        var thisType = typeof(SomeWindow);
        var controlType = typeof(SomeControl);

        var textProperty = controlType.GetProperty("Text");

        var props = thisType.GetFields(System.Reflection.BindingFlags.Instance |
                                       System.Reflection.BindingFlags.NonPublic)
                            .Where(fi => fi.Name.StartsWith("tagNameBoxAMT"));
        foreach (var prop in props)
        {
            var control = prop.GetValue(this);
            var tagName = textProperty.GetValue(control);
        }
    }
}
Comments