3

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]

Vectorinx
  • 59
  • 3

2 Answers2

4

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
3

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);
}
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57