Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Beginning Microsoft Visual Basic 2008 ISBN: 978-0-470-19134-7
This is the forum to discuss the Wrox book Beginning Microsoft Visual Basic 2008 by Thearon Willis, Bryan Newsome; ISBN: 9780470191347
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning Microsoft Visual Basic 2008 ISBN: 978-0-470-19134-7 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old September 18th, 2008, 08:34 PM
Registered User
Points: 16, Level: 1
Points: 16, Level: 1 Points: 16, Level: 1 Points: 16, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Sep 2008
Location: , , .
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default When to use NEW in declarations

I am teaching Beginning VB 2008.
Help me clarify when the NEW keyword is necessary when declaring a new object.
Page 161 Private objCustomers as New ArrayList
Page163 Dim objNewCustomer as Customer
Is there a general rule that is used in this book for using New for object declaration?


Reply With Quote
  #2 (permalink)  
Old September 19th, 2008, 05:01 AM
Thearon's Avatar
Wrox Author
 
Join Date: Dec 2003
Location: Fuquay Varina, NC, USA.
Posts: 396
Thanks: 0
Thanked 8 Times in 8 Posts
Default

Larry,

If an object has a New constructor then you'll need to use the New keyword when instantiating that object. The ArrayList class has a New constructor and Customer is a structure. However, if Customer were a class you could provide a public procedure called New and then that class would require the New keyword when instantiating that class.

Thearon
Reply With Quote
  #3 (permalink)  
Old September 19th, 2008, 03:50 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Thearon is correct, but I think he misses the essential part of your question.

The answer is pretty simple. Let's compare the two sets of code.

    Dim cust As Customer

This declares the variable cust as *capable* of referring to an object of class Customer. (Actually, it can refer to an object of class Customer *or* of any class that derives from [inherits from] Customer.)

That codes does *NOT* assign any value whatsoever to the cust variable. If you tested it, you would find that it is Nothing:
    If cust Is Nothing Then MsgBox("variable cust has not been assigned a value")

Compare and contrast that code to this:
    Dim cust As New Customer

Actually, in VB.NET version 1, you couldn't do that! You had to do it in two steps:
    Dim cust As Customer
    cust = new Customer

And so the current form is *still* simply a shortening of those two steps. "Syntactic sugar" that does two things at the same time.

After doing
    Dim cust As New Customer
if you then did
    If Not ( cust Is Nothing ) Then MsgBox("cust is initalized")
you would, indeed, see that the variable does refer to a ready-to-use object of type Customer.

So that's the difference: Without the word NEW, you are only creating an as-yet-to-be-initialized reference. With it, you already have the reference initialized.

And don't mistake a reference for the actual object! But that's a topic for a LOOONNNNG discusssion.
Reply With Quote
  #4 (permalink)  
Old September 19th, 2008, 04:54 PM
Friend of Wrox
 
Join Date: Nov 2004
Location: Port Orchard, WA, USA.
Posts: 1,621
Thanks: 1
Thanked 3 Times in 3 Posts
Default

Another way to put it.
Code:
    Dim myVar As myClsName
in any form (with or without new, with or without an assignation) establishes that the variable called myVar can only be an instance of myClsName. This establishment, by itself, does not create anything in memory.

The contents of Class myClsName describes what any instantiation of that class will operate like (the methods and properties it will have, etc.), but creates nothing that actually resides in memory.

Having a defined variable, that variable can now be used as a reference to an instance of a class of the type that it is set to be.

If you have an instantiation of that class, say in a variable named myOtherVar, you can cause myVar to refer to that instance with
Code:
    myVar = myOtherVar
Now that instance of the class will have a reference count of 2. No "New" is needed, because the instance already exists. But if you want myVar to be a reference to an instance that does not yet exist, you will need to use the "New" keyword with the variable name somewhere. The 2 ways can be
Code:
    ' One:
    Dim myVar As myClsName
    myVar = New  myClsName

    ' Or Two:
    Dim myVar As New myClsName
    So, in brief, New must be used to create a new instantiation of a class as an object of that type.
Reply With Quote
  #5 (permalink)  
Old September 19th, 2008, 05:39 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Not sure that Brian said anything different than I did. Just another way of phrasing it.

I would like to point out that C# (and C++ and Java and other languages) don't have this nice "syntactic sugar" that the VB.NET team added (one of my friends on the team was instrumental in pushing for it, I believe).

In C#/C++/Java you have to do
Code:
    Customer cust = new Customer( );
so you have to repeat the class name. Not a big deal in this case, but what about when it is
Code:
    com.astromedics.utilities.strings.Builder build = new com.astromedics.utilities.string.Builder();
Yes, yes, I know. You can do an import at the top of the page and then just use "Builder" in the declaration and initializer. (*UNLESS* you have two classes named "Builder" that are both accessible in the page.)

Still, the VB.NET way is a nice piece of "sugar" to have available. Just be sure you understand that it really is only "sugar" and doesn't imply anything that can't be done the long way.
Reply With Quote
  #6 (permalink)  
Old September 22nd, 2008, 04:43 PM
Friend of Wrox
 
Join Date: Nov 2004
Location: Port Orchard, WA, USA.
Posts: 1,621
Thanks: 1
Thanked 3 Times in 3 Posts
Default

"That codes does *NOT* assign any value whatsoever to the cust variable" doesn't seem as meaningful to a beginner as explaining that it puts nothing in memory. You and I know what happens, so a terse explanation puts us both on the same page. But as I read your post, and tried to put myself in the place of someone who does not yet know how this works, it seemed like it would be hard to grasp.

You pointed out that there was a new way to combine 2 steps needed in .NET 1 (is that right? you could add New to a Dim statement in VB 6...), but the question seemed to be more in the realm of what does "New" do, than when can you use it, syntactically.

I felt that "...you are only creating an as-yet-to-be-initialized reference..." was possibly unclear for 2 reasons. First of all, you aren't creating an reference at all. And also, one who was unclear could inadvertently confuse your use of "initialized" with the initialization that a class does within the constructor.

You weren’t wrong. I just thought I might be able to make some things clearer. Please don’t take it as contradiction, but as fortification & amplification.



But, as to your 2nd post, the poster didn’t ask anything about C (of any flavor) nor Java. By covering such a broad field, it seems likely to me to lose the assistance that you are trying to provide through too much information.

And again, the poster seems to me to be asking, "How do I decide that I need to use ‘New,’" not "What are the various ways to employ ‘New’ (syntactically), once I’ve decided I need it."
Reply With Quote
  #7 (permalink)  
Old September 22nd, 2008, 05:13 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Well, the original poster said
     I am teaching Beginning VB 2008.

So I guess I figured he could handle more info than a real newbie could. But maybe he is a non-native English speaker and meant "learning," in which case, yeah, my answers were both unclear and confusing.

And I really do love being out-pedanticized! I may get to change my moniker, yet. <grin/>

[You are dead-on right when you say "..., you aren't creating an reference at all." Very very unclear of me. My intent, poorly implemented, was to make sure that people don't confuse an object reference with an object. In my experience, newbies have the worst time understanding why code such as
     Dim a As Foo
     Dim b As Foo
     a = New Foo
     b = a
doesn't end up creating two distinct objects. I do much better in person, honest.]
Reply With Quote
  #8 (permalink)  
Old September 24th, 2008, 01:40 PM
Registered User
Points: 16, Level: 1
Points: 16, Level: 1 Points: 16, Level: 1 Points: 16, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Sep 2008
Location: , , .
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Good stuff and I appreciate the feedback.
New students struggle with concept of Dim and what is an object.
Dim strMystring as String is easy.
Dim strMyStrings(4) as String also is easy to explain as a string array…
Then you move to
Dim myArrayList as New ArrayList and students ask why they need New now… and not before.
You say "because ArrayList is an object with a New constructor…"
So they ask… how are we supposed to know when we are declaring a variable if it’s an object that will require “New”… our just a simple Dim intMynumber as Integer.
And you say…(be kind)


Reply With Quote
  #9 (permalink)  
Old September 24th, 2008, 04:02 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Sorry, but I don't see the difference between
    Dim s As String
and
    Dim a As ArrayList

In neither case did you actually *create* anything. Both of those are just variables that have the *potential* to reference an object of the given type.

The fact that you can then do
    s = "Foo"
whereas with the ArrayList you must do
    a = New ArrayList
has nothing to do with the *declarations*, per se.

It just so happens that VB.NET (and, indeed, most languages) has a convenient way to specify a literal value for a String but there's no similarly easy way to create a "literal ArrayList".

In point of fact,
    s = "foo"
is really a sort of shorthand for
    s = New String("foo")
because don't forget that you *could* do
    Dim ca() As Char = {Chr(&h66), Chr(&H6f), Chr(&H6f)
    s = New String(ca)
(and yes, if you write that variable s, you will see "foo")

And the same is true of
    Dim sa(4) As String
versus
    Dim aa(4) As ArrayList

Again, neither of those has *created* anything at all except an array of empty object references. You still need to do
    sa(0) = "first"
    sa(1) = "second"
    ...
    aa(0) = New ArrayList
    aa(1) = New ArrayList

****************

In summary, I think that making a major distinction between String and any other class is a mistake. Instead, just emphasize that the language(s) treat a string literal (something in quotes) as a special case of a pre-constructed string object.

****************

Now...

The situation is much different when it comes to the primitive types: Integer, Boolean, Double, etc.

All primitive types really *are* initialized when you DIM them.

Dim i As Integer
Dim ia(17) As Integer

And all the primitive types are initialized to a value of zero (or the equivalent for the given type: i.e., 0.0 for Double, False for Boolean.)

Primitive types don't have a constructor and so you can't possibly use NEW with them.

************

"Wait," you say, "What about creating dynamic arrays?"

Dim ai() As Integer
Dim x As Integer
x = 98
ai = New Integer(x) ' a dynamic array

Strictly speaking, you don't need this capability in VB. You *could* instead code that as

Dim ai() As Integer
Dim x As Integer
x = 98
ReDim ai(x)

But the New form is more conventional in other languages and VB has implemented it. In any case, the effect is the same. Until you define a *size* for an array, the variable's value (the value of ai, above) is Nothing. All you have really done is deferred defining the *size*, and thus creating the array-of-values-all-initialized-to-zero, until you decide what size you need.

************

This is all a bit simplistic. There are some pretty subtle differences between declaring a fixed size array and a dynamic array, but they are mostly (or maybe all?) holdovers from prior versions of VB.

We'll see whether and how much Brian Wren agrees with me.

***************************
***************************

ADDENDUM:

The more I think of it, the more I'm sure that the right way to explain string literals is by saying that
    "foo"
is just language shorthand for
    New String( {Chr(&h66), Chr(&H6f), Chr(&H6f)} )

Because, under the covers, this is exactly what the compiler does. It creates an array of Char (characters) and, from that, creates an instance of a String object. The fact that this is done at compile time, to avoid the overhead of a run-time NEW operation, is "syntactic sugar": a convenience for the user.
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Why do API Declarations Incr. .EXE size? BrianWren Pro VB 6 6 December 21st, 2007 03:23 PM
Where are my control declarations? Ron Howerton ASP.NET 2.0 Basics 13 December 6th, 2007 03:11 PM
Chap 18 XML,error: multiple DOCTYPE declarations cJeffreywang BOOK: Beginning ASP 3.0 1 November 9th, 2005 03:54 PM
Variable Declarations New2ASPnet General .NET 1 July 30th, 2004 09:49 AM
retaining ENTITY declarations arvin XSLT 3 July 23rd, 2003 01:51 AM



All times are GMT -4. The time now is 01:57 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.