Jaimin
Jaimin

Reputation: 531

How can I get array with the string of that array's name?

I have multiple arrays in a script and I have to find the arrays among them with the string of the name of that array.

For example:

int[] no1, no2, no3, no4, etc..;


void Something(string str) {
     int[] array = int array with name str;
}

So, when I call this function like this:

Something("no1");

it will take the value of array "no1".

Thank you guys in advance.

Upvotes: 1

Views: 310

Answers (1)

Just Shadow
Just Shadow

Reputation: 11871

Using a dictionary would solve the problem.
Try this:

// Declare the dictionary
private Dictionary<string, int[]> myArrays;

public void Main()
{
    // Initialize the arrays. This can also be done in constructors or wherever needed
    myArrays.Add("no1",new int[10]);
    myArrays.Add("no2",new int[10]);
    myArrays.Add("no3",new int[10]);
}

void Something(string str){
    int[] array = myArrays[str];
    // CONTINUE YOUR CODE HERE
}

P.S. Don't forget to include this to the top of your file for dictionaries:

using System.Collections.Generic;

Upvotes: 4

Related Questions