c# help.
I have a file that takes arguments but for some reason isn't picking up this one:
public void ReadFromFile2(int[] numbers)
{
string path = "FILEPATH\\numbers.txt";
StreamReader sr = new StreamReader(path);
for (int index = 0; index < numbers.Length; index++)
{
numbers[index] = Convert.ToInt32(sr.ReadLine());
}
sr.Close();
}
The other file reads this:
else if (option == 2)
{
Console.WriteLine("Option 2 chosen........");
obj.ReadFromFile2(numbers);
Console.Write("Not sorted: \n");
obj.DisplayArray(numbers);
Console.Write("\nSorted: \n");
obj.SortArray(numbers);
obj.DisplayArray(numbers);
}
Problem is with string arrays:
public void ReadFromFile3(string[] array)
{
string file1 = "FILEPATH\\Month_1.txt";
array = File.ReadAllLines(file1);
}
and this section is the problem:
else if (option == 3)
{
Console.WriteLine("Option 3 chosen........");
obj.ReadFromFile3(array);
Console.Write("Not sorted: \n");
obj.DisplayArray(array);
Console.Write("\nSorted: \n");
// obj.SortArray2(arr1);
// obj.DisplayArray(arr1);
}
It doesn't recognise array.
Why not?
And can I use stream reader like before?
I think the problem here is that c# passes arguments by value and not by reference by default, what this means is when you try to assign an argument like in ReadFromFile3 (array = File.ReadAllLines(file1);) what's actually going on is that array when passed in is a shallow copy of the array above.
now, the quick and dirty solution to this problem would be to either return the array that you get from ReadAllLines OR you can pass array by reference like so:
public void ReadFromFile3(ref string[] array)
and then you would have to change:
obj.ReadFromFile3(ref array);
hope this helped ^^
other useful links:
https://stackoverflow.com/questions/18066429/shallow-copy-or-deep-copy
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters
>>355577
C# passes *object references* by value, which is a very important distinction when you're dealing with mutable objects.
Arrays are mutable objects, so methods that mutate the object will work as OP expects (see his functions that work with arrays of ints), wheras methods that create a new object and mutate the object reference will not.
So File.ReadAllLines(...).CopyTo(array,0) will work, because it mutates array, and
array=File.ReadAllLines(...) won't work because it mutates the reference to array.