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";
}
}
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";
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With