Question

I'm wondering how to "lazy" instantiate the object from an event handler

If I have a WinForms application and two buttons for example:

public partial class Form1 : Form
{
    //MyClass obj = new MyClass();

    MyClass obj;

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        obj = new MyClass();
        obj.StartWork();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        obj.StopWork();
    }
}

Since we won't need to access MyClass' members before the user clicks button1, it would make sense to only instantiate the class in that event handler. However, clicking on the second button will throw null reference exception, because obj variable in that scope doesn't reference anything.

Was it helpful?

Solution

You can use Lazy<T>.

public partial class Form1 : Form
{
    Lazy<MyClass> obj = new Lazy<MyClass>();

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        obj.Value.StartWork();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        obj.Value.StopWork();
    }
}

Accessing its Value property will force the creation of object.

You can also supply a custom initialization function to Lazy constructor.

OTHER TIPS

This should stop the exception:

private void button2_Click(object sender, EventArgs e)
{
    // You need to make sure that obj is not null when this button is clicked.
    // One way is to disable this button until button1 is pressed. 
    // Or you can add this if statement.
    if(obj != null)
    {
        obj.StopWork();
    }
}

But your statement

because obj variable in that scope doesn't reference anything

is wrong. obj can be accessed by all the methods in your Form1 class. So when you click on button1 first, then you instantiate your class variable obj, which can be used anywhere in your class. But you need to add the if(obj != null) in case the user clicks on button2 first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top