I saved my variables into a string of data, and then tried to convert those string back into the variables like the following:
using System;
public class Program
{
static int pop;
static string[] log = new string[10];
public static void Main()
{
string abc = "5 6 10 345 23 45";
log = abc.Split(' ');
Conv(3,pop);
Console.WriteLine(pop); // expected result: pop == 345
}
static void Conv(int i, int load)
{
if (log[i] != null){ load = int.Parse(log[i]);}
}
}
Pop should be 345, but return 0 instead. There is no problem when using
pop = int.Parse.log[i]
Because load is being passed by value, not reference (meaning it's being copied). Use the ref or out keyword, or just return.
void Conv(int i, ref int load)
{...}
...
Conv(3,ref pop);
Check this fiddle.
Although Michael's answer is definitely correct, another way to get what you expect is to change the implementation of Conv to return a value instead of using pass by reference.
public static void Main()
{
string abc = "5 6 10 345 23 45";
log = abc.Split(' ');
int newPop = Conv(3,pop);
Console.WriteLine(newPop);
}
static int Conv(int i, int load)
{
if (log[i] != null)
{
return int.Parse(log[i]);
}
return load;
}
Or with a slight refactor:
static int Conv(int i, int load)
{
string entry = log[i];
return entry == null
? load
: int.Parse(entry);
}
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