0
\$\begingroup\$

I'm working with C# and .NET Framework 4.0 and Windows Forms.

On my project I have three custom objects that inherits from MyControl class (MyControl class inherits from UserControl).

I have this code:

private void ShowControlForBatchStatus(BatchStatus batchStatus)
{
    MyControl control = null;

    panelContainer.Controls.Clear();

    if (batchStatus == BatchStatus.NoBatch)
    {
        control = new InicializeLevel();
    }
    else if ((batchStatus == BatchStatus.BatchRunning) ||
                (batchStatus == BatchStatus.BatchPaused))
    {
        control = new Stadistics();
    }
    else if (batchStatus == BatchStatus.BatchFinish)
    {
        control = new FinishBatch();
    }

    panelContainer.Controls.Add(control);
}

Now I think that if it is correct to declare a MyControl control variable when I'm going to use bigger control like FinishBatch. I think that if compiler allocate memory for a MyControl object, and now I use a bigger one for that variable, is that a problem?

Maybe, I'm confuse and the compiler only allocate memory when I do new FinishBatch();.

Does the compiler allocate memory when I declare a variable?

\$\endgroup\$
  • 1
    \$\begingroup\$ Please be careful with your spelling! Stadistics = Statistics \$\endgroup\$ – d347hm4n Nov 19 '14 at 9:19
2
\$\begingroup\$

Kind of a strange question for CodeReview as I see nothing wrong with your code itself. Answering your questions:

  • ... is that a problem?

No.

  • Does the compiler allocate memory when I declare a variable?

Here's a good answer from Eric Lippert on storage location when declaring variables.

The only thing you could change about your code is make it a switch statement (although this change has nothing to do with the memory question):

private void ShowControlForBatchStatus(BatchStatus batchStatus)
{
    MyControl control = null;
    panelContainer.Controls.Clear();

    switch(batchStatus)
    {
        case BatchStatus.NoBatch: control = new InicializeLevel(); break;
        case BatchStatus.BatchRunning:
        case BatchStatus.BatchPaused: control = new Stadistics(); break;
        case BatchStatus.BatchFinish: control = new FinishBatch(); break;
    }

    panelContainer.Controls.Add(control);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.