tags:

views:

195

answers:

5

Hi, 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

+2  A: 

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.

David Liddle
+2  A: 

In C# 3 you can use object initializers to instantiate and populate an object in a single statement, like this:

var obj = new MyObject { MyProperty = "Foo", MyOtherProperty = 42 };

Is that what you mean?

Mark Seemann
A: 

I am not quite sure what it is you're after, but I have a feeling that what you're trying to do is link expressions so that you don't have to create new variables to hold your instances.

I am thinking that you want to replace this:

Thingy thing = new Thingy("This is a constructor call") 
this.myObject.Add(thing);

by this:

this.myObject.Add(new Thingy("This is a constructor call"));

As you can see, the only difference is that in the first case you'll get a handle to the instance of Thingy that you've created, called 'thing' that you can then use to call methods on, while you in the other case don't store this instance in a variable.

If this is the roblem you're having I suggest you start off by learning about constructors, because without understanding what they do there's little gain in writing short, compact code.

Best of luck.

Banang
Instead of explicit <pre> tags, put four spaces before the code. You get syntax highlighting for free with that.
Martinho Fernandes
Thank you Martinho. Didn't know that.
Banang
A: 

Petr, you can specify property values of your new object like this:

this.Form.Controls.Add(new PictureBox() { Image = XYZ, AnotherProperty = 123 });

Which saves you doing the following:

PictureBox abc = new PictureBox();
abc.Image = XYZ;
abc.AnotherPropery = 123;
this.Form.Controls.Add(abc);
joshcomley
+1  A: 

Perhaps you are looking for something like this?

this.Controls.Add(new PictureBox() { Image = myImage, Dock = DockStyle.Fill });
Mikael