473,734 Members | 2,798 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1454
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******@enter procity.comschr ieb:
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******** ******@TK2MSFTN GP06.phx.gbl...
"Ray Cassick" <rc******@enter procity.comschr ieb:
>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******@enter procity.comschr eef in bericht
news:e1******** ******@TK2MSFTN GP05.phx.gbl...
>
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.atwrote in message
news:ea******** ******@TK2MSFTN GP06.phx.gbl...
>"Ray Cassick" <rc******@enter procity.comschr ieb:
>>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 misunderstandin g is
typically from people only using that?

Cor
Jun 27 '08 #9
On Sun, 8 Jun 2008 19:39:09 -0400, "Ray Cassick"
<rc******@enter procity.comwrot e:
>
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

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

Similar topics

30
3463
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 I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
8
2558
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 in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
8
5042
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 change the value in that method the modification will not be visible outside the method. However this is not true for classes. In my example I am not using ref keyword. Thanks for feedback.
6
2819
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
1702
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: Column1 bit no nulls Column2 string no nulls Column3 DateTime no nulls
0
5113
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 the wsdl). This complex type is a collection of another complex type(elementType), and the Reference.cs has an array of these rather than the single returnedElementsType. If If I want to be able to obtain these elements from the SOAP response I...
4
6194
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 considered as reference type.... My guess is the struct A is actually a valuetype with a string reference/address. So it acts as if struct A { int ptrStr; } Anyway, the ptrStr is like a
4
1726
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 uiform As Form1, ByRef si As MTCC02.Form1.SiteRunOpts, _ ByVal numitems As Integer) #End Region
5
4608
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 denominator for structs and strings and while looking through the SDK I only noticed the IEquatable<T> interface. So I implemented the class with methods such as the following, but I'm aware that this is not the right approach.
0
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9449
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.