0

I am trying to make a dynamical assignment to an array as it follows:

int var_1 = 10;
int var_2 = 100;
int var_3 = 1000;
int[] arr = new int[3];

for (int i = 0; i < 3; i++)
{
   arr[i] = var_**i**;
}

I've already seen that it is a question quite similar in Adding a number to variable names in C# but I will need something less complex, since they are working with classes and me just with variables and vectors.

Does anybody have an idea how to implement that in a easy way? Thanks a lot!

Community
  • 1
  • 1
ironzionlion
  • 832
  • 1
  • 7
  • 28

3 Answers3

0
int[] vars = {10, 100, 1000};
double[] arr = new double[3];

for (int i = 0; i < 3; i++)
{
    arr[i] = vars[i];
}
dovid
  • 6,354
  • 3
  • 33
  • 73
  • thanks for your answer. the problem is that "vars" is not an array. I would need to do and assigment as I stated, since I am getting that values from the database – ironzionlion Mar 31 '14 at 09:53
  • @ironzionlion, I did not understand, can you post more backround code in your question? – dovid Mar 31 '14 at 09:55
  • I am getting all my "vars" from a database. I did not wrote the way to obtain the values. If I could obtain them as you proposed, that would be perfect, but I am getting them as single variables – ironzionlion Mar 31 '14 at 11:22
0

It is not possible to use Reflection to read variables local to the function. You can only read fields and properties of a class.

So it is not possible to achieve what you are asking without promoting the variables to fields in a class.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • Could you please explain me a little bit more about Reflection? You said that for a class it could work? – ironzionlion Mar 31 '14 at 09:55
  • Reflection is the mechanism used to dynamically retrieve or set values, invoke methods in *runtime* by using their names. You can use reflection to retrieve the value of the field that is defined like `class Foo { public int Bar; }` with code like `typeof(Foo).GetField("Bar").GetValue(new Foo())`. – Knaģis Mar 31 '14 at 09:57
  • Thanks again for your comment. Using a class will work, the problem will be to build that class out from single variables. It does not seem trivial... – ironzionlion Mar 31 '14 at 12:01
0
            int var_1 = 10;
            int var_2 = 100;
            int var_3 = 1000;
            int[] arr = new int[3];

            var dict = new Dictionary<string, int> 
            { 
                { "var_1", var_1 },
                { "var_2", var_2 },
                { "var_3", var_3 }
            };

            Random rand = new Random();

            for (int i = 0; i < 3; i++)
            {
                var suff = rand.Next(1, 4);
                arr[i] = dict["var_" + suff];
            }

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(arr[i]);
            }
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48