473,761 Members | 4,407 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
21 1459
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
NullReferenceEx ception 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*********@ya hoo.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.Tex t = 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******@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.
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.WriteLi ne(Object.Refer enceEquals(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.WriteLi ne(Object.Refer enceEquals("asd f", "asdf").ToStrin g())

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 misunderstandin g 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? Misunderstandin gs 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*********@ya hoo.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.Te xt = 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...@cinno vations.netwrot e:
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.Visua lBasic.Compiler Services.Operat ors.CompareStri ng. 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******@enter procity.comschr ieb:
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

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

Similar topics

30
3476
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
2559
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
5043
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
2822
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
1703
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
5115
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
6195
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
4611
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
9531
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
9345
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
10115
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...
1
9905
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
8780
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
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3456
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2752
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.