Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Overwrite string and string[] in another Function

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

arr[1] is changed to 'BBB'

but test doesn't change to '222'

Output: BBB111

but it should be BBB222

Why string test doesn't get 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";
        }
    }
like image 972
Chelayos Avatar asked Mar 14 '23 16:03

Chelayos


2 Answers

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

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";
        }
    }
like image 182
vrwim Avatar answered Mar 16 '23 08:03

vrwim


You are only altering the local reference to test in your setValues function. You would need to pass this variable by reference (ref)

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

then call it like this:

setValues(arr, ref test);
like image 34
Brian Rudolph Avatar answered Mar 16 '23 06:03

Brian Rudolph