New Keyword?

A

Arpan

Consider the following 2 statements (VB.NET):

Dim Button1 As System.Windows.Forms.Button
Dim Button2 As New System.Windows.Forms.Button()

The .NET Framework 2.0 SDK states that:

The first statement declares an object variable that can contain a
reference to a button object. However, the variable Button1 contains
the value Nothing until you assign an object of type Button to it. The
second statement also defines a variable that can contain a button
object, but the New keyword creates a button object and assigns it to
the variable Button2.

I couldn't exactly follow the difference stated above. The value of the
variable Button1 is Nothing but then what is the value of Button2?
Moreover, why is the value of the variable Button1 Nothing? Also is
"declaring an object variable" same as "defining an object variable"?

Can someone please explain me the difference in a simpler way, if
possible?

Thanks,

Arpan
 
M

Marina Levit [MVP]

Button1 points to Nothing. It does not point to an object, it is not
referencing anything. All Button1 can do at this point, is it is capable of
pointing to a button, but it isnt actually.

Button2 points to an instance of a button.

Declaring a variable and defining it are the same thing, different wording.
Instanciating a variable, that is different. Instanciating is what you are
doing with Button2 - you are giving it an object it can point to.
 
P

Phill W.

Arpan said:
Dim Button1 As System.Windows.Forms.Button
Dim Button2 As New System.Windows.Forms.Button()
I couldn't exactly follow the difference stated above. The value of the
variable Button1 is Nothing but then what is the value of Button2?

The above is a "compact" syntax the VB lets you get away with. It makes
[a little] more sense if you look at the /full/ syntax:

Dim Button1 As System.Windows.Forms.Button

Dim Button2 As System.Windows.Forms.Button _
= New System.Windows.Forms.Button()

The first gets you a variable that I would call "Button-shaped"
(formally it's an Object Reference to a Control of Type Button), but it
doesn't actually point at a anything (it's a null reference).
The second gets you another "Button-shaped" variable, but /also/ creates
a Button control (the "= New Button" bit) and stores a reference to that
Button in the variable.
Moreover, why is the value of the variable Button1 Nothing?

Because you haven't /assigned/ anything to it, so VB implicitly
initialises it to Nothing.
Also is "declaring an object variable" same as "defining an object variable"?
In this context, yes.

HTH,
Phill W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top