Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object Declarations

Tags:

c#

.net

vb.net

vb6

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?

like image 226
Paul Michaels Avatar asked Apr 28 '10 11:04

Paul Michaels


1 Answers

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

like image 138
MarkJ Avatar answered Sep 23 '22 22:09

MarkJ