AndrewR
AndrewR

Reputation: 624

Creating a reference to another object

I want to make an object that stores a reference to another object. I have a code like this:

public partial class Form1 : Form
{
    int test = 1;
    store st;       

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        st = new store(test);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        test = 7;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        label1.Text = Convert.ToString((int)st.o);
    }
}

public class store
{
    public object o;

    public store(object obj)
    {
        o = obj;
    }
}

If I click button2 - I can see "1" in my label. But if I click button2 and then button1 - I still see "1". How should I alter my code so I'll see "7" in that case?

Upvotes: 1

Views: 183

Answers (2)

Jitendra Gupta
Jitendra Gupta

Reputation: 824

With minimal changes, here you go. Properties and constructor of Form1:

public Form1()
{
    st = new store(test);
}
private int testPrivate { get; set; }

public int test
{
    get { return testPrivate; }
    set
    {
        testPrivate = value;
        st.o = value;
    }
}

public store st { get; set; }

The store class:

public class store
{
    public object o { get; set; }

    public store(object obj)
    {
        o = obj;
    }
}

Upvotes: -1

Servy
Servy

Reputation: 203848

When you create the store object you're evaluating the value of the test variable, and storing that value rather than the test variable. If you want to have a way of evaluating the variable to its value later, you can use a lambda to close over the variable, since closures in C# close over variables, not values.

public partial class Form1 : Form
{
    int test = 1;
    Store<string> store;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        store = new Store<string>(() => test.ToString());
    }

    private void button1_Click(object sender, EventArgs e)
    {
        test = 7;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        label1.Text = store.GetValue();
    }
}

public class Store<T>
{
    private Func<T> function;

    public Store(Func<T> function)
    {
        this.function = function;
    }

    public T GetValue()
    {
        return function();
    }
}

Note that I made a few changes to the names of items to be in line with standard C# conventions, rather than having Store expose the generator function's field publicly, I provide a function that lets you get the value, and I've also made it generic, rather than using object, as this both avoids boxing, and prevents the need to cast the object returned from the store.

Upvotes: 3

Related Questions