C # Overwrite string and string [] in another function

I am overwriting the variables 'arr [1]' and 'test' in the setValues ​​() function.

arr [1] changed to "BBB"

but the test will not change to '222'

Output: BBB111

but he must be BBB222

Why is the test line not updated?

public class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[10];

            arr[1] = "AAA";
            string test = "111";

            setValues(arr, test);

            int exit = -1;
            while (exit < 0)
            {

                for (int i = 0; i < arr.Length; i++)
                {
                    if (!String.IsNullOrEmpty(arr[i]))
                    {
                        Console.WriteLine(arr[i] + test);
                    }
                }
            }
        }

        private static void setValues(string[] arr, string test)
        {
            arr[1] = "BBB";
            test = "222";
        }
    }
+4
source share
5 answers

You need to pass this line by reference in order to be able to modify it in the method, you can do this by adding the keyword ref:

public class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[10];

            arr[1] = "AAA";
            string test = "111";

            setValues(arr, ref test);

            int exit = -1;
            while (exit < 0)
            {

                for (int i = 0; i < arr.Length; i++)
                {
                    if (!String.IsNullOrEmpty(arr[i]))
                    {
                        Console.WriteLine(arr[i] + test);
                    }
                }
            }
        }

        private static void setValues(string[] arr, ref string test)
        {
            arr[1] = "BBB";
            test = "222";
        }
    }
+5
source

You change the local link to testin your setValuesfunction. You will need to pass this variable by reference ( ref)

private static void setValues(string[] arr, ref string test)
{
    arr[1] = "BBB";
    test = "222";
}

:

setValues(arr, ref test);
+2

, prameter test setValues ref, , .

0

, . , setValues ​​() , , [] arr, , .

0

- . , SetValues ​​(), , Main. , :

  • As indicated in other answers, pass the values ​​by reference in the SetValues ​​method (this keeps your code as it is):
private static void setValues(string[] arr, ref string test)
{
    arr[1] = "BBB";
    test = "222";
}
  1. Move the variable declaration outside the Main body (This changes the scope of the variables to class level variables, which covers their entire class and, possibly, allows access to them from other classes):
public class Program
    {
        static string[] arr = new string[10];
        static string test = "111";

        static void Main(string[] args)
        {
            arr[1] = "AAA";

and then call it at the link:

SetValues(arr, ref test);

0
source

Source: https://habr.com/ru/post/1623463/


All Articles