Peter VARGA
Peter VARGA

Reputation: 5186

must be a control always assigned to a variable?

I tried this construct in C#:

    private class DailyTextBox : TextBox
    {
        public DailyTextBox(int x, int y)
        {
            ...
            this.Location = new Point(x, y);
            this.Size = new Size(50, 20);
            this.TextAlign = HorizontalAlignment.Right;
            ...
        }
    }

    ...
    groupBoxControl.Controls.Add(new DailyTextBox(100, 90));

The TextBox control created with new directly in the .Add() function is never assigned to a variable. The code is compiled without any error and the result on the screen looks OK. Because I am C# beginner I am not sure if there is a side effect I do not know.

Can I used it this way? I am accessing the variables in a general function which does not need the variables - only access to the controls which is also assured without variables.

Upvotes: 0

Views: 50

Answers (1)

O. R. Mapper
O. R. Mapper

Reputation: 20731

Yes, your code is correct.

You can create and pass objects without ever assigning them to a local variable, instance field, or similar.

The most extreme case to demonstrate that is something like the following - assume this class:

public class Example
{
    public int ProvideNumber()
    {
        return 42;
    }
}

You can then use this class, for example, as follows:

Console.WriteLine(new Example().ProvideNumber().ToString());

As you see, this instantiates the class Example, but it does not assign the reference to the new instance to any variable or anything else; it just invokes a method, and the new instance will immediately be out of scope after that again.

This works for arbitrary classes, control classes are not an exception. The only important issue you should be aware of is that some classes need to be disposed of. In that case, it makes sense to assign the reference to a variable simply because you probably want to do something with the new instance and then invoke Dispose.

Upvotes: 3

Related Questions