Search code examples
c#variablespass-by-referenceref

Why isn't this ref parameter changing the value passed in?


The variable asynchExecutions does get changed, but it doesn't change the reference variable.
Simple question, why isn't this ref parameter in this constructor changing the original value passed in?

public partial class ThreadForm : Form
{
    int asynchExecutions1 = 1;
    public ThreadForm(out int asynchExecutions)
    {
        asynchExecutions = this.asynchExecutions1;
        InitializeComponent();
    }

    private void start_Button_Click(object sender, EventArgs e)
    {
        int.TryParse(asynchExecution_txtbx.Text, out asynchExecutions1);

        this.Dispose();
    }

}

Solution

  • How do you know that asynchExecutions is not changing? Can you show your testcase code that proves this?

    It appears that on constructing ThreadForm asynchExecutions will be set to 1. However when you call start_Button_Click, you set asyncExecutions1 to the value in the text box.

    This WILL NOT set asyncExecutions to the value in the text box, because these are value types. You are not setting a pointer in the constructor.

    It seems to me that you are confused between the behavior of value types versus reference types.

    If you need to share state between two components, consider using a static state container, or passing in a shared state container to the constructor of ThreadForm. For example:

     public class StateContainer
     {
         public int AsyncExecutions { get; set;}
     }
    
    public class ThreadForm : Form
    {
         private StateContainer _state;
    
         public ThreadForm (StateContainer state)
         {
              _state = state;
              _state.AsyncExecutions = 1;
         }
    
         private void start_Button_Click(object sender, EventArgs e)
         {
              Int.TryParse(TextBox.Text, out _state.AsyncExecutions);
         }
    }