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 + ",";
        }           
    }
2

4 Answers 4

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");
Sign up to request clarification or add additional context in comments.

Comments

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 + ",";
    }           
}

Comments

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");

1 Comment

@Batista: You can mark an answer as "accepted answer" if it solved your problem, thus giving the person who answered more points.
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.