473,385 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Should I Use "Dim ___ As New ___"?

Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?
TIA
~Tim
Mar 15 '06 #1
17 1554
There is a bit more flexibility in declaring first and instantiating second
that *may* be usefull in certain scenarios. Other than this, it doesn't
matter.

"Tim Baur" <tr**********@ARDyahoo.com> wrote in message
news:Xn**********************************@207.46.2 48.16...
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?
TIA
~Tim

Mar 15 '06 #2
jvb
Using New is required except when using shared members of the class.
The new keyword creates a reference to the object that you are using.

Mar 15 '06 #3
"Tim Baur" <tr**********@ARDyahoo.com> schrieb
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general
question about variable declaration. In VB, I've always tried to
avoid using the "As New" construct when declaring a variable
preferring instead to instantiate in the class' or form's initialize
event or as needed. Using "As New" created unnecessary overhead and
resulted in a loss of control over my object's life cycle.

Is this advisable practice in .Net?


The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this does
not exist anymore. Now it means that the object is created as soon as the
variable is created. So, if you write

dim bla as new form

in a procedure, it is exactly the same as writing

dim bla as form
bla = new form
If you declare it at class level, it is exactly the same as writing

dim bla as form
'...
sub New()
bla = new form
end sub
See also:
http://msdn.microsoft.com/library/en...ctCreation.asp
Though, it is sometimes not advisable, but this is personal taste. I always
assume that the order of declaration doesn't matter. This is not true
anymore if the declaration contains a New statement. Example:

dim con as new oledbconnection(...)
dim cmd as new oledbcommand(con)

You see that the app will fail if you change the order because the 2nd
statement depends on the 1st one.

Armin

Mar 15 '06 #4
"Armin Zingler" <az*******@freenet.de> wrote in
news:#m**************@TK2MSFTNGP10.phx.gbl:

The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this
does not exist anymore. Now it means that the object is created as
soon as the ...

Thank you all for the input. Thanks for the thourough analysis, Armin.
This is good news -- I had hoped VB.Net would handle it this way.
Mar 15 '06 #5
Tim,

Dim ds as new Dataset
For each whatever
ds = new Dataset
'The first instanced object will only be cleaned up unused by the GC

Therefore you can do better
Dim ds as Dataset
For each whatever
ds = new dataset

Although when I don't need the dataset outside the loop I prefer even

For each whatever
dim ds as new Dataset

I hope this gives some ideas

Cor
"Tim Baur" <tr**********@ARDyahoo.com> schreef in bericht
news:Xn**********************************@207.46.2 48.16...
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?
TIA
~Tim

Mar 15 '06 #6
"Cor Ligthert [MVP]" <no************@planet.nl> wrote in
news:uK**************@TK2MSFTNGP10.phx.gbl:

For each whatever
dim ds as new Dataset


In this example, ds scopes the loop and drops the reference on completion?
Nice, very C-ish.

This brings up a new question, if I followed the example above, wouldn't a
thousand whatevers result in ds being created a thousand times? A thousand
sets of variables on the stack, memory reservations, methods registered,
constructors running, etc.

If I instantiate ds outside the loop and reuse the reference, haven't I
saved effort?
Mar 15 '06 #7
"Tim Baur" <tr**********@ARDyahoo.com> schrieb:
I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.


There is no difference between 'As New X()' and 'As X = New X()' in VB.NET
any more. Personally I prefer 'As New' because it makes code more compact.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Mar 15 '06 #8
> "Tim Baur" <tr**********@ARDyahoo.com> schrieb
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general
question about variable declaration. In VB, I've always tried to
avoid using the "As New" construct when declaring a variable
preferring instead to instantiate in the class' or form's initialize
event or as needed. Using "As New" created unnecessary overhead and
resulted in a loss of control over my object's life cycle.

Is this advisable practice in .Net?

The behavior is different. In VB6, "As New" means that the
object is created as soon as the variable is accessed. In VB.Net this
does
not exist anymore. Now it means that the object is created as soon as
the
variable is created. So, if you write
dim bla as new form


Not only that, but in VB6 if you re-referenced a variable which was previously
set to nothing, you would re-instantiate it. This was the main reason to
avoid the Dim x as New foo in VB 6. You no longer need to worry about that.

Jim Wooley
Mar 15 '06 #9
Tim,

This brings up a new question, if I followed the example above, wouldn't a
thousand whatevers result in ds being created a thousand times? A
thousand
sets of variables on the stack, memory reservations, methods registered,
constructors running, etc.

If I instantiate ds outside the loop and reuse the reference, haven't I
saved effort?


That was why I showed it, in all those except the first will the same amount
of ds be instanced. In the first sample is that plus 1. However why bother
you are using managed code that is especially for this.

Cor
Mar 15 '06 #10
"Tim Baur" <tr**********@ARDyahoo.com> wrote in message
news:Xn**********************************@207.46.2 48.16...
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?
TIA
~Tim


The other responses have covered the language-specific concerns and the
difference in language behavior for VB.Net. Part of the reason that you
were following the 'best practice' that you were... was because of a gotcha
in VB that has been addressed in VB.Net.

However, there is also a design question here. Just because we have solved
the language 'gotcha,' this does not mean we should lose sight of a core
'best practice' for OOP: You should seperate creation from use.

The concept goes to the heart of design patterns. You have patterns for
creation that allow entire structures of objects to be created, allowing
configuration files to fundamentally alter the behavior of the system
without the app developer being required, at every step, to check the config
file. Seperately, you have structural and behavioral patterns that are used
to model the seperation of concerns. The goal here is to minimize code
churn when a design change is necessitated by changing requirements.

By seperating creation from use, we can leverage all three pattern classes.

What this looks like in code is another thing altogether. Code that looks
like this:

Sub InterestingModule(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_activity(param1)
End Sub

' Would BE REPLACED BY

Sub InterestingModule(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.CreateFudgeType()
fubar.perform_activity(param1)
End Sub

The change is subtle but VERY important. By having a seperate method
(CreateFudgeType) that creates the 'fudge' object, we can isolate the logic
for creation patterns. This allows an object that is decended from the
fudge type to be returned, instead of the parent object itself. This allows
the fudge type to be an interface only (not possible in the first code
snippet... entirely possible in the second).

This type of factory pattern does not work when you say
Dim fubar as new fudge
because the module with that line is coupled to the concrete 'fudge' class.
This is a form of tight coupling that can be easily avoided.

So, just because we 'can' say Dim fubar as new fudge, that doesn't mean we
'should.' It's bad practice.

This concept has been written about extensively. If you'd like to dig up
some of the opinions of the well known thinkers, try:
-- Java's New Considered Harmful, DDJ 04/2002,
http://www.ddj.com/documents/s=7027/ddj0204a/0204a.htm
-- Lessons from OODesign: Factories, Design Patterns Explained (Chapter 20),
http://www.netobjectives.com/ezines/..._Factories.pdf
-- Perspectives of Use vs. Creation in Object Oriented Design, Netobjectives
e-zine,
http://www.netobjectives.com/ezines/...InOODesign.pdf

You can also find notes on the creation patterns by looking up things like
'abstract factory pattern' and 'factory method pattern'.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://www.netobjectives.com/ezines/....com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Mar 15 '06 #11
I don't think that's what the question was about. The question was whether
to write this:

Dim x As Object
x = New Object

....or, write this...

Dim x As New Object
-Scott
"jvb" <go*****@gmail.com> wrote in message
news:11*********************@p10g2000cwp.googlegro ups.com...
Using New is required except when using shared members of the class.
The new keyword creates a reference to the object that you are using.

Mar 16 '06 #12

Tim Baur wrote:
Hi All,

I'm a VB6er who's recently started using VB2005; I have a general question
about variable declaration. In VB, I've always tried to avoid using the
"As New" construct when declaring a variable preferring instead to
instantiate in the class' or form's initialize event or as needed. Using
"As New" created unnecessary overhead and resulted in a loss of control
over my object's life cycle.

Is this advisable practice in .Net?


The thread has shown you that Dim X As New Thing is OK in VB.NET; one
thing to consider, though, is that if you are still using VB6 on a
day-to-day basis, it's worth explicitly NOT using this syntax even in
VB.NET, lest you inadvertently use it in VB6.

--
Larry Lard
Replies to group please

Mar 16 '06 #13
"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in
news:pL********************@comcast.com:
This type of factory pattern does not work when you say
Dim fubar as new fudge
because the module with that line is coupled to the concrete 'fudge'
class. This is a form of tight coupling that can be easily avoided.

So, just because we 'can' say Dim fubar as new fudge, that doesn't
mean we 'should.' It's bad practice.
...


I have always been in the habit of writing a data class that handles
information flow and using a LoadData method on the object in question.
The caller would look to the data class as a source, and send the
information to the Object. It's a step up from calling each property
individually, but it calls upon the developer to know to use LoadData to
give the instance an identity.

I've used my share of third party libraries that were developed like this.
They can be a challenge to implement if you aren't privy to the internal
code. It also leads to buggy situations in which the class might be
employed before being properly initialized with values.

Thank you for sharing your thoughts, Nick, and for the excellent links. I
will have to try your approach in my current project.
Mar 16 '06 #14
"Larry Lard" <la*******@hotmail.com> wrote in news:1142504076.123444.95700
@j33g2000cwa.googlegroups.com:
The thread has shown you that Dim X As New Thing is OK in VB.NET; one
thing to consider, though, is that if you are still using VB6 on a
day-to-day basis, it's worth explicitly NOT using this syntax even in
VB.NET, lest you inadvertently use it in VB6.


I think that this is what I will probably do, Larry. Besides, the fact
that an object is Nothing is informative. It's like the database concept
of Null.
Mar 16 '06 #15
> By seperating creation from use, we can leverage all three pattern
classes.

What this looks like in code is another thing altogether. Code that
looks like this:

Sub InterestingModule(param1 as Integer)
Dim fubar as new fudge()
fubar.perform_activity(param1)
End Sub
' Would BE REPLACED BY

Sub InterestingModule(param1 as Integer)
Dim fubar as fudge
fubar = FudgeFactory.CreateFudgeType()
fubar.perform_activity(param1)
End Sub


I'm glad MSFT is acknowledging the factory patterns finally. It would be
nice to remove the requirement for a parameterless default constructor on
the business classes for UI binding purposes. Is this something we could
look for in the future?

Jim Wooley
http://www.devauthority.com/blogs/jwooley
MCSD.Net
Mar 16 '06 #16
>So, just because we 'can' say Dim fubar as new fudge, that doesn't mean we
'should.' It's bad practice.


I wouldn't go as far as saying that it's bad practice. Using the
factory pattern makes sense sometimes but using it too much has it's
own set of problems. Just look at how messy some frameworks
(especially in the Java world) are to use because of overuse of
factories. Reminds me of this post

http://discuss.joelonsoftware.com/de...el.3.219431.12

Even the .NET design guidelines recommend using public constructors
over factories unless you have a good reason not to.

http://blogs.msdn.com/kcwalina/archi...11/241027.aspx

So lets not forget the fine YAGNI and KISS principles.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 16 '06 #17
"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:OF**************@TK2MSFTNGP11.phx.gbl...
So, just because we 'can' say Dim fubar as new fudge, that doesn't mean
we
'should.' It's bad practice.


I wouldn't go as far as saying that it's bad practice. Using the
factory pattern makes sense sometimes but using it too much has it's
own set of problems. Just look at how messy some frameworks
(especially in the Java world) are to use because of overuse of
factories. Reminds me of this post

http://discuss.joelonsoftware.com/de...el.3.219431.12

Even the .NET design guidelines recommend using public constructors
over factories unless you have a good reason not to.

http://blogs.msdn.com/kcwalina/archi...11/241027.aspx

So lets not forget the fine YAGNI and KISS principles.


That's something about a forum with a bunch of smart folks... never be too
general!

How about this: Seperating creation from use is good practice.

On the other hand, if you are still learning OO design, it is better, in my
opinion, to err with too many factories than too few.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Mar 17 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Monte | last post by:
It compiles fine in one of my ms2002 databases, but on another db (I inherited from somebody else), I get this compile error: "User-defined type not defined" Is something turned off in this...
3
by: Bart Lateur | last post by:
For some reason, "Database" isn't recognised by Access as a built-in/predefined type, in Access' own VBA. Whenever I try to compile a line like Dim db as Database I get the complaint that...
2
by: Peter Ignarson | last post by:
Hi, simple question Is there a syntax (other than the one below that is invalid) that will let me declare and initialize two variables at the same time (using VS 2003, 1.1) ? Thank you Pete ...
4
by: Vincent Finn | last post by:
Hi, in some code I have there is a variable declared as Dim as String what is the for in this case? I thought it was an array at first but as far as I can tell the variable is just a...
3
by: Tony Bansten | last post by:
Occasionally I saw VBS script where local variables were declared on top with a statement like DIM myvar However most of my own vbs script run without such declaration. When do I need them...
11
by: Anil Gupte/iCinema.com | last post by:
When I use this Dim instance As New Timer I get the error: Error 1 Overload resolution failed because no accessible 'New' accepts this number of arguments. Yet, in the help section for...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.