Use parent class to declare a child object or how compiler allocates memory 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?
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);
}