1

im not sure why this isnt working, Im just passing a blank string and a number and it should check if that number is in the string, if not then it should add it into the string.the variable 'thing' gets set but the global variable that it is supposed to update(strduplicates) is never updated.

I call the function like this Trackstats(strduplicates,"1337");

     private void TrackStats(string thing, string variable)
    {
        if (!(thing.Contains(variable)))
        {
            thing += variable + ",";
        }           
    }
Batista
  • 141
  • 1
  • 2
  • 13

4 Answers4

3

A better design might be to return the new value:

private string TrackStats(string thing, string variable)
{
    if (!(thing.Contains(variable)))
    {
        thing += variable + ",";
    }         

    return thing;  
}

and call it using:

strduplicates = this.TrackStats(strduplicates, "1337");
Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
1

You are passing thing by value. You need to pass it by reference to make changes visible outside the method:

private void TrackStats(ref string thing, string variable)
{
    if (!(thing.Contains(variable)))
    {
        thing += variable + ",";
    }           
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
1

Strings in .NET are immutable. Every modification will allocate and return a new instance.

To alter your global variable, you have to pass it as ref parameter, like this:

 private void TrackStats(ref string thing, string variable) 
{ 
    if (!(thing.Contains(variable))) 
    { 
        thing += variable + ","; 
    }            
} 

Then you can call it like this:

TrackStats(ref strduplicates, "42");
Nuffin
  • 3,882
  • 18
  • 34
  • @Batista: You can mark an answer as "accepted answer" if it solved your problem, thus giving the person who answered more points. – Tudor Jan 16 '12 at 09:44
0

string thing is not an output param. Use 'out string thing' to signal for output.

craig1231
  • 3,769
  • 4
  • 31
  • 34
  • 3
    I think he needs ref, because thing seems to already have a value before calling the method. out expects you to pass a variable with the default value. – Tudor Jan 16 '12 at 09:33