awh112
awh112

Reputation: 1484

Setting a non-static variable in separate static method

This question is an expansion of one I asked previously, linked here.

Since then, I have changed my application to not use static global variables for storing API endpoint information. What I didn't mention was that I was also setting token variables aside from the Dictionary. My code now looks something like this:

public partial class TestControl : UserControl
{
    private string _token = null;  //this used to be a static variable
    protected Dictionary<string, string> _endpoints = new Dictionary<string, string>();

    protected void Page_Load(object sender, EventArgs e)
    {
        //clear the lists of endpoints each time the page is loaded
        _endpoints.Clear();
        ...
        var sessionInfo = MethodThatAddsToDictionary(_endpoints, _token);
        //logic that sets the global tokens based on return values
        ...
    }

    public static Dictionary<string, string> MethodThatAddsToDictionary(Dictionary<string, string> endpoints, string token)
    {
        var returnedTokens = new Dictionary<string, string>();
        token = "returned_token";  //this doesn't set the global _token value
        ...
        endpoints.Add(response.First(), response.Last());
    }
}

In the MethodThatAddsToDictionary() I was setting the "global" variable _token straight from the method. However, now that the variable is no longer static I can't do that.

I guess I have two fundamental questions with this setup:

  1. Why does changing endpoints in MethodThatAddsToDictionary() change _endpoints? I assume because it is a non-static variable.
  2. Why doesn't this work the same for _token?

These questions seem like a nuance between passing-by-value and passing-by-reference but I'm not sure what I'm missing here. For now I got away with just saving the token varaibles to a Dictionary that is returned and set the variables in Page_Load after the method call.

Thanks!

Upvotes: 0

Views: 1748

Answers (1)

D Stanley
D Stanley

Reputation: 152566

Why does changing endpoints in MethodThatAddsToDictionary() change _endpoints?

Because you're passing _endpoints to the function, and Dictionary is a reference type, so endpoints is a reference to the same dictionary as _endpoints.

Why doesn't this work the same for _token?

string is also a reference type, but you're not changing the value it's referring to, you're setting the reference to point to a new string value, which has no effect on the original value.

These questions seem like a nuance between passing-by-value and passing-by-reference

Sort of. All of the parameters are passed "by value", but for reference types (like Dictionary), the value is a reference to an object. You could do something similar with token if you used the ref keyword before the parameter type, which would pass the string by reference.

Upvotes: 2

Related Questions