-5

I'm trying to perform the job that an array is supposed to do, but without actually using one. I was wondering if this was possible, and if it is, how?

I have to initialize different variables, for example:

int value1 = 0;
int value2 = 0;
int value3 = 0;
int valueN = 0;

I want to receive a value from the user that determinate what is the for loop going to last.

Example: User --> 4

Then I can declare 4 variables and work with them.

for (i = 1; i <= 4; i++) {
    Console.Write("Insert a number: ");
    int value(i) = int.Parse(Console.ReadLine());
}

I expect to have 4 variables called equally, but with the only one difference that each one has a different number added at the end of the name.

// value1 = 0;
// value2 = 0;
// value3 = 0;
// valueN = 0;
7
  • What are you trying to achieve by doing this? Commented Jun 13, 2019 at 23:32
  • 4
    Why do you not want to use an array? Commented Jun 13, 2019 at 23:32
  • A behavior close to this can be achieved by using a dictionary: stackoverflow.com/a/16251774/302248 Commented Jun 13, 2019 at 23:34
  • 2
    If you declare them within the loop then you won't be able to use them outside the loop. This sounds like a really contrived requirement that has no basis in reality? Commented Jun 13, 2019 at 23:35
  • For all of them who're asking why I'm not using arrays: It's because a friend of mine has to solve a problem where he needs to receive university careers and the amount of student they have. His teacher didn't even mention arrays OR ANY OTHER DATA STRUCTURE other than variables. So that's why I wanted to solve this problem by declaring multiple variables inside a loop and automatically showing it's value inside the loop. Commented Jun 14, 2019 at 0:03

1 Answer 1

1

You cannot create dynamically named variables in C# (and I am with those who are wondering why you want to do that). If you don't want to use an array, consider a Dictionary -- it would perform better than an array in some circumstances.

Dictionary<string, int> values = new Dictionary<string, int>();
for (int i = 1; i <= 4; i++)
{
    values.Add("value" + i, 0);
}

value["value1"]; //retrieve from dictionary
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.