c# - Accessing a variable's name by using index of for loop -


let's have 4 strings.

private string string_1, string_2, string_3, string_4; 

then let's have loop. how can access variable name index of loop? here's idea of i'm talking about:

for(int = 0; < 4; i++) {     string_ + = "hello, world! " + i; } 

i understand doing above not compile.

thanks help.

you can't you're asking - @ least directly.

you start putting strings array , work array.

string[] strings = new [] {     string_1,     string_2,     string_3,     string_4, };  for(int = 0; < 4; i++) {     strings[i] = "hello, world! " + i; }  console.writeline(string_3); // != "hello, world! 2" console.writeline(strings[2]); // == "hello, world! 2" 

but original string_3 unchanged, although slot in array correct.

you can go 1 step further , way:

action<string>[] setstrings = new action<string>[] {     t => string_1 = t,     t => string_2 = t,     t => string_3 = t,     t => string_4 = t, };  for(int = 0; < 4; i++) {     setstrings[i]("hello, world! " + i); }  console.writeline(string_3); // == "hello, world! 2" 

this works intended - string_3 updated. little contrived though, may useful you.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -