Search code examples
c#winformsref

How to access a ref bool variable passed into the constructor?


I have a main form, which calls a smaller form. In the main form I have a bool called _dataReady which is set to false, however the purpose of the smaller form is to check a few things and see if the data is ready, in which case it sets the _dataReady to true.

Here is my problem: I call the mini form with an input parameter such as (ref bool _dataReady) but the problem is I don't have access to it outside of the constructor block.

I tried making a private bool and set the ref to that, but after changing the state of the private bool the ref did not take the changes, unlike how object oriented programming works.

Here is some of my code:

//this is how i call my mini form within the main

new FrmAccounting(MyTextBox1.Text.Trim().Replace(",", "").ToInt32(),ref _dataReady).ShowDialog();

This is the constructor of the mini form and the code:

public FrmAccounting(decimal Price,ref bool _dataReady)
{
    InitializeComponent();
    dataReady=_dataReady;
}

private bool dataReady;

However setting the private bool within the form (dataReady) to true does not change the ref (again unlike how objects work)... that's what I thought would happen.

My question is: how to change the ref so I can have the results directly in the main?


Solution

  • You can't do that using ref since the field in your class can't be made a ref.

    I would suggest to wrap your variable into a class. You can pass that class around and use the inner value.

    public class Wrapper<T>
    {
        public T Value {get;set;}
    }
    

    Then use it like this:

    Wrapper<bool> w = new Wrapper<bool>() { Value = _dataReady };
    
    new FrmAccounting(MyTextBox1.Text.Trim().Replace(",", "").ToInt32(),w).ShowDialog();
    

    The value can be retrieved afterwards using w.Value.