Results 1 to 4 of 4

Thread: [RESOLVED] Form a variable name using concatenation

  1. #1

    Thread Starter
    Lively Member bcass's Avatar
    Join Date
    Dec 2007
    Location
    Island of Dots
    Posts
    108

    Resolved [RESOLVED] Form a variable name using concatenation

    The variable in question is an array. Let's say I want to loop through a series of arrays (array1; array2; array3; etc.). I want to form the loop like this:

    Code:
    for (int i = 0; i < 4; i++)
    {
      currentXUBound = array + i.GetUpperBound(0);
      currentYUBound = array + i.GetUpperBound(1);
      //do other processes here...
    }
    This doesn't work because of the way I've concatenated the variable name. What is the correct way to express this in C#?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Form a variable name using concatenation

    You don't. Variable names are something you write explicitly in your code. Arrays are objects, just like any other. If you have multiple arrays that you want to select from then you put those arrays into an array or collection and then select one by index or key.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Form a variable name using concatenation

    The way to loop over a series of object would be to add them to a collection that supports IEnumerable, such as List<T>:

    csharp Code:
    1. int[,] array1 = new int[3,4];
    2. int[,] array2 = new int[9,8];
    3. int[,] array3 = new int[2,2];
    4. int[,] array4 = new int[6,9];
    5.  
    6. List<int[,]> arrays = new List<int[,]>() {array1, array2, array3, array4};
    7.  
    8. foreach (int[,] currentArray in arrays)
    9. {
    10.     int currentXUBound = currentArray.GetUpperBound(0);
    11.     int currentYUBound = currentArray.GetUpperBound(1);
    12.     // do other processes here...
    13. }

  4. #4

    Thread Starter
    Lively Member bcass's Avatar
    Join Date
    Dec 2007
    Location
    Island of Dots
    Posts
    108

    Re: Form a variable name using concatenation

    That's exactly what I needed. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width