473,383 Members | 1,861 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,383 software developers and data experts.

Why does string not require a new like other reference types?

I can't believe why I had not noticed this before and why I never asked it
before...

When defining a string why is it not required to use the new keyword? Like:

Dim a As String = New String

You can do it when using the string type with some arguments in the
constructor but it look like there is no empty constructor on the String
class.

Seem odd to me that all the other reference types seem to require a new to
create the instance portion of the type and String does not.

Thanks for any insight...
Jun 27 '08 #1
21 1419
Ray Cassick wrote:
I can't believe why I had not noticed this before and why I never asked it
before...

When defining a string why is it not required to use the new keyword? Like:

Dim a As String = New String

You can do it when using the string type with some arguments in the
constructor but it look like there is no empty constructor on the String
class.

Seem odd to me that all the other reference types seem to require a new to
create the instance portion of the type and String does not.

Thanks for any insight...
If you declare a string without assigning a value to it, you haven't
created any instance of the string class, you have only declared a
reference.

All literal string values are created as constants in the assembly. As
they already exists when the code is started, you don't need to use the
new keyword when assigning them.

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #2
"Ray Cassick" <rc******@enterprocity.comschrieb:
When defining a string why is it not required to use the new keyword?
Like:

Dim a As String = New String
Because it would not make sense. Strings are immutable in .NET. If you
write 'Dim a As String = "Hello World"' you are creating an instance of
'String' containing "Hello World" and assign a reference to it to the
variable 'a'. Each assignment to a 'String' variable changes the reference.
You can do it when using the string type with some arguments in the
constructor but it look like there is no empty constructor on the String
class.
Which value should a string constructed with the parameterless constructor
have?

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

Jun 27 '08 #3

"Herfried K. Wagner [MVP]" <hi***************@gmx.atwrote in message
news:ea**************@TK2MSFTNGP06.phx.gbl...
"Ray Cassick" <rc******@enterprocity.comschrieb:
>When defining a string why is it not required to use the new keyword?
Like:

Dim a As String = New String

Because it would not make sense. Strings are immutable in .NET. If you
write 'Dim a As String = "Hello World"' you are creating an instance of
'String' containing "Hello World" and assign a reference to it to the
variable 'a'. Each assignment to a 'String' variable changes the
reference.
>You can do it when using the string type with some arguments in the
constructor but it look like there is no empty constructor on the String
class.

Which value should a string constructed with the parameterless constructor
have?
Thanks for the response...

So as I understood it (and the way it was actually taught to me) is this.

When you do this:

Dim a As TypeName

The storage is declared on the managed stack. IF the type is a ValueType
then nothing else is needed and the storage is all done on the stack. IF the
type is a reference type then the stack storage ends up just being a pointer
that will end up being an address on the heap somewhere but points to
nowhere just yet.

When you do this:

Dim a As ClassName = New ClassName...

THEN the storage is allocated on the stack AND the storage is allocated on
the heap and the stack points to the proper location on the heap.

So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.

I would expect that doing this:

Dim a As String

would simply point to nothing (as it does) just like doing this:

Dim a As Integer

results in a 0.

I am just curious as to why the String type seems to be inconsistent in
behavior with respect to other reference types.

Jun 27 '08 #4
Ray Cassick wrote:
>
So, I guess my question is.. if String is a reference type why do you
NOT NEED to allocate it using the New keyword every time? Almost
seems like strings are an odd case with respect to this.

I am just curious as to why the String type seems to be inconsistent
in behavior with respect to other reference types.
Although a String is technically a reference type, it has behavior more like a
value type. The actual string of characters is "immutable", making it unlike
most other object classes. A new string is created with every assignment
statement (or the string variable points to a stored literal).

Dim Test As String
' points to nothing

Test = "Hello"
' points to the stored literal "Hello"

Test = Test + ", "
' points to a new string containing "Hello, "

Test = Test + "World"
' points to a new string containing "Hello, World"

Test = Test.ToUpper
' points to a new string containing "HELLO, WORLD"

Jun 27 '08 #5
Ray,

Your replies sounds to me like somebody driving a car once heard that there
was a carburator in it, and now ask why he cannot find it in his current
car.

It is important for a driver, that a car do exactly as it should do? You are
not the one who designs Net and the way it works.

By the way, playing with words does not work here.

Dim a as integer "results" in a 0
Dim b as string "results" in a ""

Both as with all valuetypes with the lowest value possible.

Strange that you did not mention the Struct DateTime which has almost the
same behaviours

Just my idea reading your replies.

Cor

"Ray Cassick" <rc******@enterprocity.comschreef in bericht
news:e1**************@TK2MSFTNGP05.phx.gbl...
>
"Herfried K. Wagner [MVP]" <hi***************@gmx.atwrote in message
news:ea**************@TK2MSFTNGP06.phx.gbl...
>"Ray Cassick" <rc******@enterprocity.comschrieb:
>>When defining a string why is it not required to use the new keyword?
Like:

Dim a As String = New String

Because it would not make sense. Strings are immutable in .NET. If you
write 'Dim a As String = "Hello World"' you are creating an instance of
'String' containing "Hello World" and assign a reference to it to the
variable 'a'. Each assignment to a 'String' variable changes the
reference.
>>You can do it when using the string type with some arguments in the
constructor but it look like there is no empty constructor on the String
class.

Which value should a string constructed with the parameterless
constructor have?

Thanks for the response...

So as I understood it (and the way it was actually taught to me) is this.

When you do this:

Dim a As TypeName

The storage is declared on the managed stack. IF the type is a ValueType
then nothing else is needed and the storage is all done on the stack. IF
the type is a reference type then the stack storage ends up just being a
pointer that will end up being an address on the heap somewhere but points
to nowhere just yet.

When you do this:

Dim a As ClassName = New ClassName...

THEN the storage is allocated on the stack AND the storage is allocated on
the heap and the stack points to the proper location on the heap.

So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.

I would expect that doing this:

Dim a As String

would simply point to nothing (as it does) just like doing this:

Dim a As Integer

results in a 0.

I am just curious as to why the String type seems to be inconsistent in
behavior with respect to other reference types.
Jun 27 '08 #6
Cor Ligthert[MVP] wrote:
Ray,

Your replies sounds to me like somebody driving a car once heard that
there was a carburator in it, and now ask why he cannot find it in his
current car.

It is important for a driver, that a car do exactly as it should do? You
are not the one who designs Net and the way it works.

By the way, playing with words does not work here.

Dim a as integer "results" in a 0
Dim b as string "results" in a ""
Not at all. Declaring a string without assigning a value either results
in a null reference (for member variables) or an undefined variable (for
local method variables).
Both as with all valuetypes with the lowest value possible.
String is not a value type, so the default value for string is not an
empty string, it's null.
Strange that you did not mention the Struct DateTime which has almost
the same behaviours

Just my idea reading your replies.

Cor
--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #7

"Göran >>
>Dim a as integer "results" in a 0
Dim b as string "results" in a ""

Not at all. Declaring a string without assigning a value either results in
a null reference (for member variables) or an undefined variable (for
local method variables).
I especially placed the double quotes around the words results.

As a string is declared then the type Is String and the object Is Nothing.
As soon as you use a string then it will create that empty string. Even as
that is If string = nothing

:-)

Cor

Jun 27 '08 #8
Goran,

By the way, are you using often C#, because this misunderstanding is
typically from people only using that?

Cor
Jun 27 '08 #9
On Sun, 8 Jun 2008 19:39:09 -0400, "Ray Cassick"
<rc******@enterprocity.comwrote:
>
So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.

I would expect that doing this:

Dim a As String

would simply point to nothing (as it does) just like doing this:

Dim a As Integer

results in a 0.

I am just curious as to why the String type seems to be inconsistent in
behavior with respect to other reference types.
Strings are an odd case because they are a reference type that is
created by using a language constant. If strings required New, then
every use of a string constant would require New:

Dim a As String = New String("abc") + New String("def")
MessageBox.Show(New String("Some message"))

That's a lot of typing and a lot of clutter for no purpose. Requiring
New provides no functionality over just using the constant by itself.
Jun 27 '08 #10
On Jun 9, 5:40*am, "Cor Ligthert [MVP]" <notmyfirstn...@planet.nl>
wrote:
As a string is declared then the type Is String and the object Is Nothing.
As soon as you use a string then it will create that empty string. Even as
that is If string = nothing

:-)

Cor
That is not a true statement. Consider the following trivial example.

Dim a As String
a.ToString()

The example uses "a" before it is assigned and that generates a
NullReferenceException as you would expect from any reference type.
An empty string did not get created and assigned to "a" at any point.
Jun 27 '08 #11
Brian,

You are right, however I seldom set a string to a string.

This works
Dim a As String
TextBox1.Text = a

Cor
Jun 27 '08 #12
On Jun 9, 11:10*am, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
Brian,

You are right, however I seldom set a string to a string.
I'm not sure what you mean by that.
>
This works
Dim a As String
TextBox1.Text = a

Cor
That works because TextBox.Text checks to see if the value being
assigned is a null reference first and if it is then it creates an
empty string and assigns that instead (I checked using Reflector).
That behavior is specific to TextBox (and perhaps other classes in the
BCL as well) and cannot be generalized to every use of a string.
Jun 27 '08 #13
On Mon, 9 Jun 2008 09:48:11 -0700 (PDT), Brian Gideon
<br*********@yahoo.comwrote:
>On Jun 9, 11:10*am, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
>Brian,

You are right, however I seldom set a string to a string.

I'm not sure what you mean by that.
>>
This works
Dim a As String
TextBox1.Text = a

Cor

That works because TextBox.Text checks to see if the value being
assigned is a null reference first and if it is then it creates an
empty string and assigns that instead (I checked using Reflector).
That behavior is specific to TextBox (and perhaps other classes in the
BCL as well) and cannot be generalized to every use of a string.
Another oddity of strings is that test for equality with an empty
string doesn't trap if the string reference is Nothing, but any other
use of the reference to Nothing does trap.

Dim a As String = Nothing
If a = "" Then ' This doesn't trap, unlike other reference types
If a.Length 0 Then ' This does trap like other reference types

I'm not sure why it works this way. While this behavior can be
convenient (saving a test for Is Nothing), it only helps when
comparing for the empty string.

It's another example of how String is treated as a cross between
reference and value types.
Jun 27 '08 #14
Jack Jackson wrote:
On Sun, 8 Jun 2008 19:39:09 -0400, "Ray Cassick"
<rc******@enterprocity.comwrote:
>So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.

I would expect that doing this:

Dim a As String

would simply point to nothing (as it does) just like doing this:

Dim a As Integer

results in a 0.

I am just curious as to why the String type seems to be inconsistent in
behavior with respect to other reference types.

Strings are an odd case because they are a reference type that is
created by using a language constant. If strings required New, then
every use of a string constant would require New:

Dim a As String = New String("abc") + New String("def")
MessageBox.Show(New String("Some message"))

That's a lot of typing and a lot of clutter for no purpose. Requiring
New provides no functionality over just using the constant by itself.
Besides, when you use a literal string it's not created when you use it.
It already exists as a constant in the assembly, so if New was requiered
like that, the compiler would actually replace each New call with the
reference to the string constant.

You can verify that using a string literal doesn't create any new object
like this:

Dim x(1) As String
For i As Integer = 0 to 1
x(i) = "asdf"
Next
Console.WriteLine(Object.ReferenceEquals(x(0), x(1)).ToString())

It will write out True, as the code in the loop assigns the reference of
the same string literal to both the items in the array.

You can also verify that string literals are reused like this:

Console.WriteLine(Object.ReferenceEquals("asdf", "asdf").ToString())

It will write out True, as the same string constant is used for both
string literals.

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #15
Cor Ligthert [MVP] wrote:
Goran,

By the way, are you using often C#, because this misunderstanding is
typically from people only using that?

Cor
I am indeed "using often C#", but I have also used a lot of other
languages, inlcuding some flavours of assembly language and machine
code, so I have a pretty good sense for what's really happening to the
code that I write.

Do you use mostly Visual Basic? Misunderstandings like that is typical
for people only using that.

;)

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #16
Jack Jackson wrote:
On Mon, 9 Jun 2008 09:48:11 -0700 (PDT), Brian Gideon
<br*********@yahoo.comwrote:
>On Jun 9, 11:10 am, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
>>Brian,

You are right, however I seldom set a string to a string.
I'm not sure what you mean by that.
>>This works
Dim a As String
TextBox1.Text = a

Cor
That works because TextBox.Text checks to see if the value being
assigned is a null reference first and if it is then it creates an
empty string and assigns that instead (I checked using Reflector).
That behavior is specific to TextBox (and perhaps other classes in the
BCL as well) and cannot be generalized to every use of a string.

Another oddity of strings is that test for equality with an empty
string doesn't trap if the string reference is Nothing, but any other
use of the reference to Nothing does trap.

Dim a As String = Nothing
If a = "" Then ' This doesn't trap, unlike other reference types
If a.Length 0 Then ' This does trap like other reference types

I'm not sure why it works this way. While this behavior can be
convenient (saving a test for Is Nothing), it only helps when
comparing for the empty string.

It's another example of how String is treated as a cross between
reference and value types.
That's simply because the string class overrides the = operator, and the
code that compares strings handles null values.

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #17
Cor Ligthert [MVP] wrote:
"Göran >>
>>Dim a as integer "results" in a 0
Dim b as string "results" in a ""
Not at all. Declaring a string without assigning a value either results in
a null reference (for member variables) or an undefined variable (for
local method variables).

I especially placed the double quotes around the words results.
That doesn't matter. Neither the result or the "result" is a string.
As a string is declared then the type Is String and the object Is Nothing.
As soon as you use a string then it will create that empty string. Even as
that is If string = nothing
No, it doesn't work that way. A string reference does not automatically
change into something else just because you use it. If it would, you
could never get a null reference exception when using a string.

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #18
On Jun 9, 3:09*pm, Jack Jackson <jjack...@cinnovations.netwrote:
Another oddity of strings is that test for equality with an empty
string doesn't trap if the string reference is Nothing, but any other
use of the reference to Nothing does trap.

Dim a As String = Nothing
If a = "" Then *' This doesn't trap, unlike other reference types
If a.Length 0 Then ' This does trap like other reference types

I'm not sure why it works this way. *While this behavior can be
convenient (saving a test for Is Nothing), it only helps when
comparing for the empty string.

It's another example of how String is treated as a cross between
reference and value types
The first example demonstrates how the VB compiler injects a call to
Microsoft.VisualBasic.CompilerServices.Operators.C ompareString. That
method treats null strings the same as empty strings. It is
interesting to note that the C# equivalent of that example results in
a completely different outcome.
Jun 27 '08 #19
"Ray Cassick" <rc******@enterprocity.comschrieb:
So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.

I would expect that doing this:

Dim a As String

would simply point to nothing (as it does) just like doing this:

Dim a As Integer

results in a 0.
Well, 'Integer' is a value type, 'String' is a reference type. Thus the
value of 'a' in the sample above is a 'Nothing' reference.

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

Jun 27 '08 #20
I am asking because I wanted to explain the difference between these two
types to someone else and could not come up with a real reason (other than -
it just works that way with strings) for them. Right, I'm not the designer
but that does not stop me form being curious :)

Inconsistencies bug me. It just seemed like something that would pop up in a
Microsoft document somewhere and I have had no luck in locating it. Another
thing that bugs me.

Now that I had the discussion I am ok. Seems more like it was a mixture of
how strings are inherently immutable and how it better to make them work
like ValueTypes in these cases.
"Cor Ligthert[MVP]" <no************@planet.nlwrote in message
news:1A**********************************@microsof t.com...
Ray,

Your replies sounds to me like somebody driving a car once heard that
there was a carburator in it, and now ask why he cannot find it in his
current car.

It is important for a driver, that a car do exactly as it should do? You
are not the one who designs Net and the way it works.

By the way, playing with words does not work here.

Dim a as integer "results" in a 0
Dim b as string "results" in a ""

Both as with all valuetypes with the lowest value possible.

Strange that you did not mention the Struct DateTime which has almost the
same behaviours

Just my idea reading your replies.



Jun 27 '08 #21
In article <e1**************@TK2MSFTNGP05.phx.gbl>,
Ray Cassick <rc******@enterprocity.comwrote:
The storage is declared on the managed stack. IF the type is a ValueType
then nothing else is needed and the storage is all done on the stack. IF the
type is a reference type then the stack storage ends up just being a pointer
that will end up being an address on the heap somewhere but points to
nowhere just yet.
Pretty much, there are exceptions...
When you do this:

Dim a As ClassName = New ClassName...

THEN the storage is allocated on the stack AND the storage is allocated on
the heap and the stack points to the proper location on the heap.

So, I guess my question is.. if String is a reference type why do you NOT
NEED to allocate it using the New keyword every time? Almost seems like
strings are an odd case with respect to this.
Nope.

This is one of the exceptions to the stack/heap storage option. String
constants results in a reference that points to the code. Just as you'd
do if you were programming in assembly and were assigning a pointer to
a string constant.

So, string constants are pointers to code, and the implementation of
the + and & operators create a new reference and then return that.

--
J.B. Moreno
Jun 27 '08 #22

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

Similar topics

30
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then...
8
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined...
8
by: Nader | last post by:
Hello all, In C# string is a reference type but I learned that string is different from other reference types such as class. For example, if you pass a string argument to a method and then...
6
by: Chris Simmons | last post by:
I know that a String is immutable, but I don't understand why this piece of code fails in nUnit: // BEGIN CODE using System; class Test { public static void Main( String args )
6
by: Bob Day | last post by:
VS 2003 The documentation says " Nothing keyword represents the default value of any data type" this is simply not true and causing a lot of problems. 1) Consider an SQL table of 3 columns: ...
0
by: Richard Gregory | last post by:
Hi, I have the wsdl below, for an Axis web service, and when I select Add Web Refernce in Visual Studio the proxy is missing a class representing the returnedElementsType (see reference.cs below...
4
by: haitao.song | last post by:
Hi, As it is always stated that value type is allocated on stack, while reference types are on managed heap. How about the struct with string members? stuct A { string str; } String type is...
4
by: eBob.com | last post by:
In my class which contains the code for my worker thread I have ... Public MustInherit Class Base_Miner #Region " Delegates for accessing main UI form " Delegate Sub DelegAddProgressBar(ByVal...
5
by: Anders Borum | last post by:
Hi! While implementing a property manager (that supports key / value pairs), I was wondering how to constrain T to a struct or string type. Basically, I guess what I'm looking for is the common...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
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...

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.