class DM_Matrix {
public string[] DMInput_Name = new string[] {};
public string[] DMOutput_Name = new string [] {};
public int[] DMInput = new int[] { 99, 1, 2, 3, 4 };
public int[] DMOutput = new int[] { 99, 1, 2, 3, 4 };
}
public void Initialize() {
foreach (var i in DM_Matrix.DMInput_Name) {
CrestronConsole.PrintLine("[DM.Module.Input_Name"
+ DM_Matrix.DMInput_Name[i]);
}
}
Compiler error on "i":
"(local variable) string i
ERROR cannot implicitly convert type 'string' to 'int'"
I'm trying to print every the whole DM.Module.Input_Name array
I've tried to set use "int i" instead of "var i" or cast i from string to integer buy no joy. Not sure why "i" is recognised as string. In my understanding it should be recognised as "int" for the array.
2 Answers 2
You are using a foreach loop, not a for loop. If this were a for loop like this:
foreach (var i = 0 ; i < DM_Matrix.DMInput_Name.Length ; i++)
{
CrestronConsole.PrintLine("[DM.Module.Input_Name" +DM_Matrix.DMInput_Name[i]);
}
Then yes you can use i as an array index.
But in a foreach loop, the loop variable represents an item of the array, so your loop should be written like this:
foreach (var name in DM_Matrix.DMInput_Name) {
CrestronConsole.PrintLine("[DM.Module.Input_Name" + name);
}
Comments
Here you need to understand difference between for and foreach loop.
for loop : If you want to access element from an array by index, then use for loop.
foreach loop : If you want to iterate through each object, then use foreach loop
To solve your problem, use for loop or foreach loop, you are mixing both loops into one.
Solution using for loop,
//Use index to get value from an array
for (int i = 0; i < DM_Matrix.DMInput_Name.Length; i++)
{
CrestronConsole.PrintLine("[DM.Module.Input_Name" +DM_Matrix.DMInput_Name[i]);
}
Solution using foreach loop
//Iterate over elements instead of index
foreach (var item in DM_Matrix.DMInput_Name)
{
CrestronConsole.PrintLine("[DM.Module.Input_Name" + item);
}
DM_Matrix.DMInput_Name[i].iitself is the string item coming fromDM_Matrix.DMInput_Namecollection. So you can simply doCrestronConsole.PrintLine("[DM.Module.Input_Name" + i);