0

For example, you have the array (called array1): {"1","2","3"}

And the string (called string1): "0"

Can you do the following: array1[string1]

And have it equal: "1"

I have checked How can I evaluate a C# expression dynamically? and call a c# function that is defined in a string however I did not understand the answers. I apologize.

When I try string1 = int.Parse(string1); I get an error:

Or string1 = Convert.ToInt32(string1); :

Cannot implicitly convert type 'int' to 'string'

To elaborate, (sorry if my description wasn't very clear), my code does this:

btnName =  btn.Name.ToString(); //btnName for example == btn01
btnCo1 = btnName[3].ToString(); // btnCo1 will equal "0"
btnCo2 = btnName[4].ToString(); //btnCo2 will equal "1"
btnCo1 = Convert.ToInt32(btnCo1); //I want btnCo1 as a int to use like so :
btnCo2 = Convert.ToInt32(btnCo2);
   grid[btnCo1][btnCo2] //grid is a jagged array
Community
  • 1
  • 1
bubblez go pop
  • 147
  • 1
  • 1
  • 10

2 Answers2

1

You have to parse the string to int, preferably using TryParse:

int idx;
if (Int32.TryParse(string1, out idx)) Console.WriteLine(array1[idx]);

Other way would be using Convert.ToIn32. However this might throw an exception if string1 cannot be converted to int, for example if it contains "Hello World".

EDIT concerning yours: you can´t change a variables data-type once you´ve declared it. So if btnCo1 already is a string you can´t change it to be an int, you have to define a new variable for it:

int idx1 = Convert.ToInt32(btnCo1);
int idx2 = Convert.ToInt32(btnCo2);

DoSomething(grid[idx1][idx2]);
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

Yes you can, just parse the string index to int.

string[] array = new string[]{ "a", "b" };
string idx = "0";

Console.WriteLine(array[Convert.ToInt32(idx)]); //Will log "a"

See fiddle here

Bon Macalindong
  • 1,310
  • 13
  • 20