snipef
snipef

Reputation: 33

C# Class instance

I'm a beginner in programming and I've read several tutorials. I'm still unclear about the following:

When clicking on a button, that event creates an instance of a class:

private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;
    myClass test = new myClass(a);
}

myClass is doing a long processing job (several minutes). If I click 5 times on my button, is it gonna create 5 instances? Or is the "test" going to be "overwritten" 4 times?

Thanks

Upvotes: 3

Views: 387

Answers (2)

Chad Moran
Chad Moran

Reputation: 12854

It will create however many instances that you click. However, if the work is synchronous and blocks the UI thread you can't click it again until the work has completed. If your work is asynchronous it will create a new instance every time you click.

Instead try...

private myClass _test;
private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;

    if (_test == null)
    {
        _test = new myClass(a);
    }
}

Though, I would not recommend doing synchronous work on the UI thread.

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160942

If I click 5 times on my button, is it gonna create 5 instances ? Or the "test" instance will be "overwritten" 4 times ?

Yes its going to create 5 separate instances. You are creating an object that immediately falls out of scope after it is constructed, so the next time a different instance of the same class is constructed.

I assume you were planning to do the processing as part of your constructor, keep in mind this will block the UI thread, your program will "freeze" - if you are looking to do a long processing job, you shouldn't do it on the UI thread - look into i.e. the BackgroundWorker.

Upvotes: 8

Related Questions