Alexxxx Alexxxx - 10 months ago 22
Java Question

How do I convert this for loop into C# loop?

I have this for loop working in JAVA. How do I implement the loop in C# with same functionality?

List<Instruction> ins = ThreeAddressBuilder.Build(lines);


Print unoptimized 3-Address code
System.out.println("\n\nUnoptimized 3-Address Code:");
for(Instruction i : ins){
System.out.println(i.toString());
}


The loop I tried

foreach (var match in ins)
{
Console.WriteLine(match.ToString());
}

Answer

You have converted the code nicely, but you missed to specify the class name while iterating the collection, it is better to use the class name while doing the iteration, or else you have to cast the object. in your case The console is directly printing the object. So what you can do to achieve the goal is change the loop like this:

foreach (Instruction match in ins)
{
    Console.WriteLine(match.ToString());
}

Or

foreach (var match in ins)
{
  Console.WriteLine((Instruction)match).ToString();
}