tags:

views:

128

answers:

6

Are there any overheads to using the following sytax:

Form1 myForm = new Form1();
myForm.Show();

As opposed to:

Form1 myForm;
myForm = new Form1();
myForm.Show();

When I was learning VB6, I was told doing the quivelent in VB had an overhead - is the same true in .NET?

+5  A: 

No. Both are same.

Ismail
A: 

I doubt there is, but even if there was, the performance overhead would be so negligible that there wouldn't be any percievable benefit by choosing one over the other.

lomaxx
+1  A: 

You have only seperated the declaration from instantiation in the latter case. There's no significant impact of this. I read somewhere that .Net object instantiation takes 0.000007 seconds so it hardly matters though recommended practice would be to instantiate the object only when needed and dispose when not needed or caching not required..

this. __curious_geek
well not exactly - you might want to declare an object at higher scope and instantiate-or-dispose the object on some events. In my app, I keep a reference of a prop-grid window object which is only instantiated when user wishes to see the prop-grid. I dispose the prop-grid object on close event of prop-grid form.
this. __curious_geek
I agree with this._courious_geek. +1
Robert Williams
+2  A: 

Resulting bytecode when compiling in release mode (and probably debug mode) will be the same.

Daniel Dolz
A: 

In this example you create a variable [myForm] of type Form1 and allocate it memory at creation.

Form1 myForm = new Form1(); 

In this example the first line creates a variable of type Form1, but no memory has been allocated for this myForm object.

Form1 myForm;   

Then the second line can be used whenever you need a new instance of type Form1 [at that point, the memory will be allocated for the myForm object].

myForm = new Form1(); 

In my opinion, it is really a good pratice to declare all of your variables to there types and then when you need a live instance you can do your ... obj = new Foo1();

Robert Williams
+5  A: 

There is no difference in .Net.

But in VB6 As New was evil. It had a special meaning: it created an auto-instantiating variable. You could never get a null reference exception with these variables. The VB6 runtime would automatically create a new instance of the object for you.

Dim x As New Foo
x.Bar = 10      ' creates a new Foo '
Set x = Nothing ' destroys the first Foo'
x.Bar = 20      ' NO ERROR - creates a second Foo '

This behaviour was considered evil by most right-thinking programmers: and we avoided As New like the plague.

But in VB.Net (and C#) there is no difference between Dim x As New Foo and Dim x As Foo: Set x = New Foo

MarkJ