0

In C#, is it possible to declare variables in a loop? I have an array of names, and I want them all to be variables. Is there a way to create them? something like

string[] nameArray{ name, othername, anothername };

foreach ( var file in nameArray ) {
    data 'file' = new data();
}
5
  • You can declare variables within a loop, but I think what you're looking for in this case is an array. The entries within an array are unnamed, but the array itself is named and individual entries are referred to by index. Commented Jul 23, 2014 at 17:55
  • you can create variable like this foreach ( var file in nameArray ) { //here i am creating var1 variable data var1= new data(); } Commented Jul 23, 2014 at 17:57
  • It is NOT possible. Why do you want to have something like this? Commented Jul 23, 2014 at 17:58
  • I am reading the names from a directory, and want to declare the file names as variables Commented Jul 23, 2014 at 18:04
  • You could declare and create variables inside a loop like at any other place but each would a) be recreated on each iteration and b) be lost when the loop goes out of scope. Use a dictionary as Thomas suggests! Commented Jul 23, 2014 at 18:15

1 Answer 1

3

You can't declare variables "dynamically" like this, variable names must be known statically at compile time. However you can achieve a similar result by using a Dictionary:

string[] nameArray = { "name", "othername", "anothername" };
var dict = new Dictionary<string, data>();
foreach ( var file in nameArray )
{
    dict[file] = new data();
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would you recall data?
Console.Write(dict["name"]);

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.