I`m trying to reproduce a code example from the book, where the program calculates squares of provided numbers, shows results in cmd, and also record the results in txt.file. For provided numbers 1, 2, 3, 4 the program can calculate results and show them in cmd as:
1
4
9
16
However, when it needs to record the results in the txt file, it only records 16. I`m not sure if it overrides the previous data or just recording the last squared number. I would like to have a hint what is wrong here and how I can fix it to be able to record all results, just like in cmd.
using System;
using System.IO;
using System.Collections.Generic;
namespace Chapter4Practice
{
public interface ITransformer
{
int Transform(int x);
}
public class Util
{
public static void TransformAll(int[] values, ITransformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t.Transform(values[i]);
}
}
public class Squarer : ITransformer
{
public int Transform(int x) => x * x;
}
class Test
{
static void Main()
{
int[] values = { 1, 2, 3, 4 };
Util.TransformAll(values, new Squarer());
foreach (int i in values)
{
Console.WriteLine(i);
WriteProgressToFile(i.ToString());
}
}
static void WriteProgressToFile(string i) => System.IO.File.WriteAllText("progress.txt", i.ToString()+ Environment.NewLine);
}
}