2 ways to initialize, what's the difference?

  • Thread starter Thread starter Zytan
  • Start date Start date
Z

Zytan

What is the difference between these two lines?

Dim args As Object() = New Object() {strText}
Dim args As Object() = {strText}

args seems usuable from either, say, like so:

Me.Invoke(delegate, args)

Zytan
 
What is the difference between these two lines?

Dim args As Object() = New Object() {strText}
Dim args As Object() = {strText}

args seems usuable from either, say, like so:

Me.Invoke(delegate, args)

Zytan

There is no difference.
 
Interesting. Another foible where both are valid.

The brackets are used to populate an array so it appears that, for the form
'Dim args As Object() = {strText}', the compiler second guesses you and
assumes you actually mean 'Dim args As Object() = New Object() {strText}'.

If you compile the following and have a look at the result with Lutz
Roeder's Relector you will find that both forms of the statement emit
identical IL.

Public Class Form1

Private strText As String

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles Button1.Click

Dim args As Object() = New Object() {strText}

End Sub

Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles Button2.Click

Dim args As Object() = {strText}

End Sub

End Class
 
Zytan said:
What is the difference between these two lines?

Dim args As Object() = New Object() {strText}
Dim args As Object() = {strText}

No difference (except that I'd write 'Dim Args() As Object = {strText}'
;-)).
 
Zytan said:
What is the difference between these two lines?

Dim args As Object() = New Object() {strText}
Dim args As Object() = {strText}

args seems usuable from either, say, like so:

Me.Invoke(delegate, args)

Zytan

There is no difference. The second is just a short form for the first
one that is available when you are declaring the variable and assigning
a value to it in the same statement.

If you first declare the variable and then assign a value to it, you
have to specify the type of the value:

Dim args as Object()
args = New Object() { strtext }

' this would produce a compiler error
' args = { strtext }
 
Interesting. Another foible where both are valid.

So the fact that code like this can exist is kind of frowned upon?
Which is the 'better' code?
The brackets are used to populate an array so it appears that, for the form
'Dim args As Object() = {strText}', the compiler second guesses you and
assumes you actually mean 'Dim args As Object() = New Object() {strText}'.

Aha, so the compiler is putting a "New" in there. You see, my issue
is that one has "New" and the other doesn't. "New" means it is making
an new object. Too many times ive seen in VB that "New" is optional
(with other things), and both ways make the same code. So, im left to
wonder, well, they both cant be the same, since "New" appears only on
one, so is one wasting memory?

I hope you can repsect the perspective of a newcomer.
If you compile the following and have a look at the result with Lutz
Roeder's Relector you will find that both forms of the statement emit
identical IL.

I have no doubt about this, since 4 of you have told me the code is
identical. Thank you all for that.

But i am not satisifed, as i would like to know why it is identical.
you gave your 'guess', so i assume that version of the code is the one
that is not recommended, since it hides what is going on?

Zytan
 
There is no difference. The second is just a short form for the first
one that is available when you are declaring the variable and assigning
a value to it in the same statement.

Is this done to torture newbies? :)

I just dont follow how an acceptable way of shortening code allows the
removal of the "New" keyword. Am i the only one who is bothered by
this? Is there any other meaningful way i can think of this style of
code that *makes sense*, in that i can think that "New" really is
there? I just can't wrap my mind around it. for example I can see
how this:

Dim x As Control = New Control

it shortened to this:

Dim x As New Control

But, for:

Dim args As Object() = New Object() {strText}

shortened to this:

Dim args As Object() = {strText}

doesn't flow. What am i not seeing?
If you first declare the variable and then assign a value to it, you
have to specify the type of the value:

Dim args as Object()
args = New Object() { strtext }

' this would produce a compiler error
' args = { strtext }

yes, ok. thanks.

And this strengthens my perspecitve in that the shortening doesn't
'flow'. It doesn't seem as though it should work. Do you follow what
i'm saying?

Zytan
 
So the fact that code like this can exist is kind of frowned upon?
Which is the 'better' code?


Aha, so the compiler is putting a "New" in there. You see, my issue
is that one has "New" and the other doesn't. "New" means it is making
an new object. Too many times ive seen in VB that "New" is optional
(with other things), and both ways make the same code. So, im left to
wonder, well, they both cant be the same, since "New" appears only on
one, so is one wasting memory?

I hope you can repsect the perspective of a newcomer.


I have no doubt about this, since 4 of you have told me the code is
identical. Thank you all for that.

But i am not satisifed, as i would like to know why it is identical.
you gave your 'guess', so i assume that version of the code is the one
that is not recommended, since it hides what is going on?

Zytan

Zytan,

They are the same because the compiler infers what you want to do, and inserts
the new for you. I personally think it is bad form not to specify the new,
but there is a certain amount of BASIC tradition that spills over into VB.NET
;)

Anyway, what is recommended is what you feel is best or that your boss tells
you is best :)
 
As you are finding, VB.NET has a number of foibles, that don't, at face
value, seem logical. Mostly, it is a matter of choice/preference/style,
(call it what you will), as to which form of the syntax you use.

When one first comes across a foible it tends to be a bit annoying but once
one figures out what is actually happening then using the syntax of choice
tends to become habit.

You will find 'purists' who will argue till the cows come home that one form
is correct and the other isn't or that one form is is better and the other
isn't but if both forms compile to identical IL then the argument is purely
acedemic and it is up to you to use the form that you feel most comfortable
with.

If the compiled IL is different and/or the execution of one form is
implemented differently then that is a completely different matter. (The use
of Control.Select() over Control.Focus() fits into this category.)
 
It isn't intended to torture but rather it is the result of having to
conform new language features into a system not originally designed to
accomodate such things. There is a bit of "VB-ism" concern but consider the
challenge.

The following (not withstanding my belief that "dim" as a keyword is
outdated (somebody will surely defend it I'm certain)) 1) declares the
scope of the variable, 2) defines it's datatype and 3) assigns a value (the
object reference.)

Dim x as Control = New Control()

While the following works it is generally a syntactical shortcut and I
recommend you avoid it. As always my recommendation is to avoid
language-specific items and to embrace language-agnostic solutions (when it
is possible and practical to do so). Those intent on arguing please re-read
the stuff in parens :-)

Dim x As New Control

Part of the reason is that it doesn't follow that you want a "control"
reference just because you instantiate a control object. The following
works as well because an ArrayList is in fact an object. The shortcut
version cannot do this.

Dim obj As Object
obj = New ArrayList()

So now consider how does one assign contant values? The following works:

Dim arg As String
arg = "test"

Note also that you aren't particularly bothered by the lack of a New keyword
in this instance, right? I'll suggest you've grown accustomed to thinking
of strings as some sort of natural computer data type but they aren't. :-)

So what would the syntax be to assign constant array values? An array
requires the New keyword and that means you have to include the class name
and only then can you tack on the values you want. So you end up with
something like the following:

Dim args As String()
args = New String() {"test"}

Here it is as an array of Integers:

Dim arr As Integer()
arr = New Integer() {1, 2, 3}

So what's left is the example you saw originally, the declaration and
assignment of an array of Objects.

Dim args as Object()
args = New Object() { strtext }

And that's why we have that syntax. What else could the syntax be and do
you think another one would be more clear?

Tom
 
You will find 'purists' who will argue till the cows come home that one
form is correct and the other isn't or that one form is is better and the
other isn't but if both forms compile to identical IL then the argument is
purely acedemic and it is up to you to use the form that you feel most
comfortable with.

If the compiled IL is different and/or the execution of one form is
implemented differently then that is a completely different matter. (The
use of Control.Select() over Control.Focus() fits into this category.)

Hi Stephany glad to see you're back. I'll agree that it can be academic but
I'm not sure I'd characterize it as purely a matter of personal choice. In
the extreme case one might argue that spelling doesn't matter and it's the
idea that counts yet a resume' filled with spelling errors isn't likely to
receive the same attention as one with no spelling errors. The rational
(rightly or wrongly) is probably that; if the person can't bother to spell
correctly what else can't they bother to do?

If nothing else one's choice should be consistent. I'd rather read code
using a style that I don't like (but consistently) than code written using
every known (and some unknown) style. Differences within a project (or
worse a single file) look to me like I'm viewing somebody's experiment (the
code finally worked) rather than their solution. If Control.Select() and
Control.Focus() are interchangeable I'd consider which one was used in other
..Net languages, which one was likely to be used more often and finally which
(if either) was found in other languages (notably C++, Java, et. al.)

Rather than describe the process as "academic" I prefer the word "finesse."
Any boob can produce code these days... if they can't write it on their own
they can cut & paste it from the Internet or use a code generator. What
they can't do by borrowing chunks of code or using a wizard however is craft
something elegant.

Tom
 
Thanks Tom. I was quite busy for a while rolling out 500 Vista desktops, but
that's out of the way now and Im back with a vengance :)

I'm certainly not advocating the use of a mish-mash of styles, nor will I
permit my staff using a mish-mash of style. You're absolutely correct that
consistency is the key.
 
I don't know about everybody else but if you have a quick "review" of Vista
I'd be interested to hear it. I'm going to upgrade eventually but I figured
I'd wait a patch or two :-)

Tom
 
Zytan,

It are all string operations; whatever you try to do with a string as part,
it will always create a new string. With one exception, that written in one
line a string will created as one line.

Example of the last

"a" & "b" & "c" written in one line will result direct in "abc" in more
lines that will be "ab" & "c".

Although this is not about that behaviour, it will be that, in any case
with the lightest change in your program.

Cor
 
I'd like to hear, too. I also heard the first patch is being (or just has
been)released.

Robin S.
--------------------------------
 
Zytan wrote:

I just dont follow how an acceptable way of shortening code allows the
removal of the "New" keyword. Am i the only one who is bothered by
this? Is there any other meaningful way i can think of this style of
code that *makes sense*, in that i can think that "New" really is
there?

It's part of an idiom. If you don't want to use the idiom, then don't
(but, as others have said, consistency matters, so be consistent in
not using it).

As Tom pointed out in another post, no one seems to have a problem
with ...

Dim A As String = "xyzzy"

Or ...

Dim A As String
A = "abracadabra"

.... even though there's an implicit New somewhere (during
initialization).

Personaly, I'd prefer a broader notion of constants in VB.Net
(Structure and array constants, for example).
I just can't wrap my mind around it. for example I can see
how this:

Dim x As Control = New Control

it shortened to this:

Dim x As New Control

This is an interesting example, because it touches the notion that
VB.Net is idiosyncractic because of its many hystorical VB'isms.
Ironicaly, to a seasoned VB.Classic programmer, the "Dim X As New Y"
construct would be a very definitive *no*, because of the way it used
to work previously to VB.Net and the kind of code it generated. Yet,
in VB.Net it's a popular idiom and one that I -- even being a
"seasoned" VB programmer -- recommend, because there's *no* semantic
ambiguity in the short circuit. Personally I'd even recommend you not
using the "complete" syntax, due to verbosity.
But, for:

Dim args As Object() = New Object() {strText}

shortened to this:

Dim args As Object() = {strText}

doesn't flow. What am i not seeing?

I, personaly, really *abhor* the "New X() { ... }" syntax... *sigh*
(of course, no one has to condone my personal grievances).

The short circuit syntax seems perfectly clear to me and I am glad
it's clear to the compiler also. What I think is inconsistent is that
this short circuit can't be used outside a Dim (just as with strings):

Dim Args() As Integer
Args = {...}

And this strengthens my perspecitve in that the shortening doesn't
'flow'. It doesn't seem as though it should work. Do you follow what
i'm saying?

In technicolor. But I see it from the other way around. To me, the
syntax "Dim A() As B: A={...}" should definitely be valid! =))

I suggest you experiment with the short circuit in some of the next
snippets you'll have to produce. Or in the next project you'll start.
After using the short circuit in some real situations you'll be able
to decide if it's part of your vocabulary or not.


Regards,

Branco.
 
They are the same because the compiler infers what you want to do, and inserts
the new for you. I personally think it is bad form not to specify the new,
but there is a certain amount of BASIC tradition that spills over into VB.NET
;)

I agree completely. Thanks. No wonder it is so confusing.

Zytan
 
As you are finding, VB.NET has a number of foibles, that don't, at face
value, seem logical.

Yes, I am.
Mostly, it is a matter of choice/preference/style,
(call it what you will), as to which form of the syntax you use.

Yes. I personally prefer the ones that are clear what is happening.
When one first comes across a foible it tends to be a bit annoying but once
one figures out what is actually happening then using the syntax of choice
tends to become habit.

Yes, I agree. Luckily habit kicks in, for all languages, not just
VB. But that doesn't imply the foible is 'good' in any of those
cases. So, if I can avoid them, I will.
You will find 'purists' who will argue till the cows come home that one form
is correct and the other isn't or that one form is is better and the other
isn't but if both forms compile to identical IL then the argument is purely
acedemic and it is up to you to use the form that you feel most comfortable
with.

I don't agree here. If the ends if the same, but the means is
different, but one mean shows precisely what will occur, and the other
hides it, the purists have a good argument why the one that is more
'truthful' is better. I agree. Maybe that makes me a purist. (But,
I am not complaining about all of the designer code VB makes behind
the scenes, so I dont think I am a purist. I just want proper code
that does what it says it will do -- isnt that the main point of VB
over the C languages? However, I would guess that this is a matter of
VB NET being restricted to support earlier VB versions, and it is
unfortunate that all evils can not be fixed as they could with C#
being a new language from scratch.)

Please note that in my desire to understand what this was:
Dim args As Object() = New Object() {strText}
I made the new version without "New" to see if it worked, and it did,
and thus, it did nothing to help me understand what
Dim args As Object() = New Object() {strText}
was, it just confused the matter.
If the compiled IL is different and/or the execution of one form is
implemented differently then that is a completely different matter. (The use
of Control.Select() over Control.Focus() fits into this category.)

I agree, it is a different matter.

Zytan
 
No difference (except that I'd write 'Dim Args() As Object = {strText}'

Ok, so, now im totally confused. :) These are all the same code:
Dim args As Object() = New Object() {strText}
Dim args As Object() = {strText}
Dim args() As Object = {strText}

I need to find a tutorial that explains this. Just knowing they make
the same IL is not good enough.

Zytan
 
Tom, thanks for your indepth reply.
The following (not withstanding my belief that "dim" as a keyword is
outdated (somebody will surely defend it I'm certain)) 1) declares the
scope of the variable, 2) defines it's datatype and 3) assigns a value (the
object reference.)

Dim x as Control = New Control()

Ok. (I also believe Dim is outdated. It's like using LET in older
BASICs, but we were all glad we didnt have to use it, so no one did.)
While the following works it is generally a syntactical shortcut and I
recommend you avoid it. As always my recommendation is to avoid
language-specific items and to embrace language-agnostic solutions (when it
is possible and practical to do so). Those intent on arguing please re-read
the stuff in parens :-)

Dim x As New Control

I prefer to avoid this shortcut, too. But i have been using it to get
used to other people's code.
Part of the reason is that it doesn't follow that you want a "control"
reference just because you instantiate a control object. The following
works as well because an ArrayList is in fact an object. The shortcut
version cannot do this.

Dim obj As Object
obj = New ArrayList()

I see. Since the following makes obj2 an ArrayList, not an Object:
Dim obj2 As New ArrayList()
So now consider how does one assign contant values? The following works:

Dim arg As String
arg = "test"

Note also that you aren't particularly bothered by the lack of a New keyword
in this instance, right? I'll suggest you've grown accustomed to thinking
of strings as some sort of natural computer data type but they aren't. :-)

No. I do think of strings as classes, unlike integers and floating
point types that are natural types. You can make a string (or any
class) without "New"ing it. It just becomes a variable on the stack,
rather than dynamically allocated. So, i don't miss the lack of "New"
here.

I notice that this works:
Dim arg2 As String = "test"
but this doesn't:
Dim arg3 As New String = "test"

This is confusing. Why can't i "New" that class if i want to? I
obviously have no idea how the "New" keyword is used. I was thinking
it would be similar to what it means in C++. (Does C# share these
same issues? No, it looks like you have to use "New" in C#. Maybe I
should use C# instead.)
So what would the syntax be to assign constant array values? An array
requires the New keyword and that means you have to include the class name
and only then can you tack on the values you want. So you end up with
something like the following:

Dim args As String()
args = New String() {"test"}

No, you can use this without the "New" keyword, as well:
Dim arg5 As String() = {"test", "2nd"}

Is this the same issue I was having with Object()? Let's see. Yes,
it is. Ok, so let's ignore Object() for now, since that was confusing
me. Let's deal with just String or Integer, since the above is the
same problem.
Here it is as an array of Integers:

Dim arr As Integer()
arr = New Integer() {1, 2, 3}

And the same can be done without "New", which normally is:
Dim i2 As Integer() = {4, 5, 6}
So what's left is the example you saw originally, the declaration and
assignment of an array of Objects.

Dim args as Object()
args = New Object() { strtext }

And that's why we have that syntax. What else could the syntax be and do
you think another one would be more clear?

The above is exactly what I expect. args is an array of objects.
Then we 'new' an array of Objects initialized with { strtext}, and set
args to be that. The shortcut is what I didn't understand.

Ok, i think i am more clear about all of this. I was used to:

Dim i2 As Integer() = {4, 5, 6}

when this is the same as:

Dim i1 As Integer()
i1 = New Integer() {1, 2, 3}

so, you really are using "New" on each array, but its normally
hidden. And here i thought these variables would just be local stack
variables, not dynamically allocated. I think this was the source of
confusion. Nobody wanted to type "New" all the time, so they made a
shortcut that looks like it isnt being dynamically allocated, which
screws up some C++ programmers like me.

Thanks for all of your input

Zytan
 
Back
Top