Petr Petr - 2 months ago 6
C# Question

Simple C# "new" question - syntax related

I am just curious how to create new object in the command. (in order to save space and learn it of course).
Just to combine the commands together and do not have picturebox abc= new picturebox on the extra line,
Like this:

this.Form.Controls.Add(new Picturebox abc)
//something like that?

Thanks for help

Answer

You have to instantiate the object and pass it as a parameter to another object.

For example here is how you would write it in 2 lines of code

Picturebox.TEST myPictureBox = new Picturebox.TEST();
Form.Controls.Add(myPictureBox);

You are just passing the object into the method of Form.Controls.Add. So to do it in 1 line...

Form.Controls.Add(new Picturebox.TEST());

The 1st example is more readable and also allows you to use the myPictureBox instance in that method block.