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

Why, oh why.

I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery?
Regards
Nov 17 '05 #1
25 1499
Some use it for better readability.

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery?
Regards
Nov 17 '05 #2
Frank,

It's OOP snobbery, and I whole-heartedly subscribe to it =)
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery?
Regards

Nov 17 '05 #3

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery?
Regards


Why use it? Well, sometimes it's a little more difficult to read "'""'"
than it is to read "'" & String.Empty & "'". That's just one reason...there
are others...but if you go along these lines, then for consistency,
String.Empty would be the way to go as well :)

Is it snobbery? Sure can be...I know I use it for that
reason...snobbery...what a word :)

Mythran

Nov 17 '05 #4
Frank,
When I use it, I use it for "consistency" with other types. A "Empty
Pattern" if you will (would the "Empty Pattern" be OOP snobbery?)

Such as:

String.Empty

CounterSample.Empty
XmlQualifiedName.Empty
EventArgs.Empty
Color.Empty
Guid.Empty
Rectangle.Empty
Point.Empty
AttributeCollection.Empty

....

A search for Empty on MSDN returns a plethora of other Types that have Empty
fields or properties.

NOTE: I'm not totally consistent with using String.Empty vs. "".

Hope this helps
Jay

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
| I've seen recently some programmers using
|
| string s = String.Empty;
|
| instead of traditional
|
| string s = "";
|
| Is there any logical reason for this or just OOP snobbery?
| Regards
Nov 17 '05 #5
Jay B. Harlow [MVP - Outlook] wrote:
Frank,
When I use it, I use it for "consistency" with other types. A "Empty
Pattern" if you will (would the "Empty Pattern" be OOP snobbery?)

Such as:

String.Empty

CounterSample.Empty
XmlQualifiedName.Empty
EventArgs.Empty
Color.Empty
Guid.Empty
Rectangle.Empty
Point.Empty
AttributeCollection.Empty
Ah, the string type is a different league than color, guid, point,
etc... String is a fundamental type, while the others are not. You can
write very complex software and not use Point or Guild or
AttributeCollection ones. Try and do that without the string data type.

I am very productivity driven. I always seek out ways to type less, so
String.Empty makes no sene to me. I view String.Empty vs "" the same
way I view the term Refactoring: a 10 dollar word which five years ago
simply meant moving your code around a bit.

....

A search for Empty on MSDN returns a plethora of other Types that have Empty
fields or properties.

NOTE: I'm not totally consistent with using String.Empty vs. "".

Hope this helps
Jay

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
| I've seen recently some programmers using
|
| string s = String.Empty;
|
| instead of traditional
|
| string s = "";
|
| Is there any logical reason for this or just OOP snobbery?
| Regards

Nov 17 '05 #6
Frank,
| Ah, the string type is a different league than color, guid, point,
| etc... String is a fundamental type, while the others are not.
Yes its a fundamental type, however my statement is questions if it should
it be treated as such? Considering there is potentially an "Empty Pattern"
lurking in the framework?

| You can
| write very complex software and not use Point or Guild or
| AttributeCollection ones. Try and do that without the string data type.
OK. How does that apply to a potential "Empty Pattern" usage or not?

My point is, at a certain level using String.Empty and Point.Empty or simply
the "Empty Pattern", avoids an "Oddball Solution", where using "" to mean
empty for some types & using .Empty to mean "empty" for other types is
potentially an Oddball Solution. Note Empty here does not mean Nothing!

Hope this helps
Jay

"Frank Rizzo" <no**@none.com> wrote in message
news:ux**************@TK2MSFTNGP10.phx.gbl...
| Jay B. Harlow [MVP - Outlook] wrote:
| > Frank,
| > When I use it, I use it for "consistency" with other types. A "Empty
| > Pattern" if you will (would the "Empty Pattern" be OOP snobbery?)
| >
| > Such as:
| >
| > String.Empty
| >
| > CounterSample.Empty
| > XmlQualifiedName.Empty
| > EventArgs.Empty
| > Color.Empty
| > Guid.Empty
| > Rectangle.Empty
| > Point.Empty
| > AttributeCollection.Empty
|
| Ah, the string type is a different league than color, guid, point,
| etc... String is a fundamental type, while the others are not. You can
| write very complex software and not use Point or Guild or
| AttributeCollection ones. Try and do that without the string data type.
|
| I am very productivity driven. I always seek out ways to type less, so
| String.Empty makes no sene to me. I view String.Empty vs "" the same
| way I view the term Refactoring: a 10 dollar word which five years ago
| simply meant moving your code around a bit.
|
| >
| > ....
| >
| > A search for Empty on MSDN returns a plethora of other Types that have
Empty
| > fields or properties.
| >
| > NOTE: I'm not totally consistent with using String.Empty vs. "".
| >
| > Hope this helps
| > Jay
| >
| > "Frank Rizzo" <no**@none.com> wrote in message
| > news:OB**************@TK2MSFTNGP15.phx.gbl...
| > | I've seen recently some programmers using
| > |
| > | string s = String.Empty;
| > |
| > | instead of traditional
| > |
| > | string s = "";
| > |
| > | Is there any logical reason for this or just OOP snobbery?
| > | Regards
| >
| >
Nov 17 '05 #7

"Frank Rizzo" <no**@none.com> wrote in message
news:ux**************@TK2MSFTNGP10.phx.gbl...
Ah, the string type is a different league than color, guid, point, etc...
String is a fundamental type, while the others are not. You can write
very complex software and not use Point or Guild or AttributeCollection
ones. Try and do that without the string data type.

I am very productivity driven. I always seek out ways to type less, so
String.Empty makes no sene to me.


I Agree
- Michael S
Nov 17 '05 #8

"Frank Rizzo" <no**@none.com> wrote in message
news:OB**************@TK2MSFTNGP15.phx.gbl...
I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery?
Regards


It's snobbery that will fight you.
As a string is a reference-type an instance can be null or empty.
Hence you often need to check for both. You often see code like

if ((myStr != null) && (myStr != String.Empty)) //.C# 1.1
if (myStr != String.NullOrEnpty) //.C# 2.0

I tend to avoid that crap by always setting my own allocated strings to ""
and never let them be null.
Then I can code more C-stylish by just checking for the former

if (myString != "")

Saves a lot of time. However, one must be very careful with strings you get
from .NET framework.
In our shop we have written a StringUtil.AsString(string str) that never
returns null. Saves a lot of headaches.

That strings can be null sucks. Why didn't Hjelsberg do it the Delphi way
and let "" be equal to null. Bet he tried but couldn't convince the .NET
team to do it that way. But I consider this a design-flaw as bad as Visual
Basic 6 four magic constants of the apocalypse (Verity Stob) - Nothing,
Null, Empty and Error idioticy.

Mina 2 öre
- Michael S

Nov 17 '05 #9

System.String.Empty is a static readonly public field. When you call it from
any part of your application, there is no extra allocation of a new string
since there is only one protected copy that is shared among everyone. Every
time you use "" you are allocating a new string instead of using System.String.Empty.
Even though string are classes, they are imutables so everytime you reasing
the "" it is creating a new copy.
Empty, MinValue, MaxValue...etc are not only good ways to keep a standard
of your default values but also to "reuse" them without extra memory allocation.

Erick Sgarbi
I've seen recently some programmers using

string s = String.Empty;

instead of traditional

string s = "";

Is there any logical reason for this or just OOP snobbery? Regards

Nov 17 '05 #10
Erick,
| Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
String literals are interned. Every time you use "" you are receiving the
exact same string instance as String.Empty!

Try the following code:

object s1 = String.Empty;
object s2 = "";
object s3 = new string('\0', 0);
Debug.WriteLine(s1 == s2, "s1 == s2");
Debug.WriteLine(s1 == s3, "s1 == s3");
s1 == s2 as they are the same instance, while s1 != s3 as they are different
instances. Using object variables forces the compiler to use object
references instead of the String overloaded operators.

Hope this helps
Jay

<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
|
| System.String.Empty is a static readonly public field. When you call it
from
| any part of your application, there is no extra allocation of a new string
| since there is only one protected copy that is shared among everyone.
Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
| Even though string are classes, they are imutables so everytime you
reasing
| the "" it is creating a new copy.
| Empty, MinValue, MaxValue...etc are not only good ways to keep a standard
| of your default values but also to "reuse" them without extra memory
allocation.
|
| Erick Sgarbi
|
| > I've seen recently some programmers using
| >
| > string s = String.Empty;
| >
| > instead of traditional
| >
| > string s = "";
| >
| > Is there any logical reason for this or just OOP snobbery? Regards
| >
|
|
Nov 17 '05 #11
Michael S <a@b.c> wrote:

<snip>
That strings can be null sucks.


On the contrary. I find it really, really useful to be able to
distinguish between a variable which has been set to an empty string,
and one which has been set to a null value. They can often be
semantically *very* different.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #12
Jon Skeet [C# MVP] wrote:
Michael S <a@b.c> wrote:

<snip>
That strings can be null sucks.

On the contrary. I find it really, really useful to be able to
distinguish between a variable which has been set to an empty string,
and one which has been set to a null value. They can often be
semantically *very* different.


I agree with your reasoning, however, cases where string needs to be
null are very few and far in between. Perhaps there should have been a
nullable string class NullableString and leave the System.String as
non-nullable.
Nov 17 '05 #13
Frank Rizzo <no**@none.com> wrote:
On the contrary. I find it really, really useful to be able to
distinguish between a variable which has been set to an empty string,
and one which has been set to a null value. They can often be
semantically *very* different.


I agree with your reasoning, however, cases where string needs to be
null are very few and far in between. Perhaps there should have been a
nullable string class NullableString and leave the System.String as
non-nullable.


I find I need a nullable string more often than I need nulls of most
other types - Forms, Streams, Encodings etc. Personally, I don't find
it a problem at all that strings can be null - just like other
parameters etc, you need to check them in appropriate places if only
certain values are valid.

Of course, this is where something like Spec# comes in handy...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Frank Rizzo <no**@none.com> wrote:
> On the contrary. I find it really, really useful to be able to
> distinguish between a variable which has been set to an empty string,
> and one which has been set to a null value. They can often be
> semantically *very* different.
I agree with your reasoning, however, cases where string needs to be
null are very few and far in between. Perhaps there should have been a
nullable string class NullableString and leave the System.String as
non-nullable.


I find I need a nullable string more often than I need nulls of most
other types - Forms, Streams, Encodings etc. Personally, I don't find
it a problem at all that strings can be null - just like other
parameters etc, you need to check them in appropriate places if only
certain values are valid.

Of course, this is where something like Spec# comes in handy...


Well, I mostly do web applications and 99% of the strings I allocate is for
HTML output.
I think most asp.net devs are quite sick and tired of all them null pointer
exceptions you always get when fast-coding.

I also do a lot of import/export using XML. It's a nightmare. if a node is
missing on a xpath-expression you get the darn null again. It is so useless.
Of course we made our own XML-wrapper that never yeilds a null. Problem
solved ugly.

I agree theer are cases where you could find it useful for a nullable
string. But those cases are way far inbetween your regular use of strings.
For most applications, all them if-statements and util-methods gives bloated
code and lesser performance.

In Delphi, you have primitives, records, classes and strings. String being a
magic (and pretty smart) special type.

In .NET they wanted a simple system of value-types and reference-types and
had to cram the string in either two. Strings then wind up naturally as a
reference-type. But I think this was the wrong thing to do. I'd rather see
value-types, reference-types and magic-types. The simple dualistic approach
we got now is a pain in the arse.

Too bad they didn't come up with nullable types from scratch. That would
have saved the day. Then we could have string and string?. a cast between a
null string? to string would yeild "". That would have been pretty neat.

Guess it's too late for that now...

Happy Nulling
- Michael S

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #15
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
Every > time you use "" you are allocating a new string instead of using
System.String.Empty.


This is simply not true.

if you read the specs on C# you may think this is so. Even if you read the
specs for CIL you may still believe this is what would happen. But it's not.
The CLR and the JITter could care no less about C# and CIL specs.

The CLR holds a VERY global Hashtable for all constants in the runtime. This
table are manged by CLR and hence have priviliged acess to cross application
domains. So if your application have a

myStr = myStr1 + "QWERTY" + myStr2;

and my application has

aStr = "QWERTY" + anyStr;

the CLR would have only one single copy of QWERTY in memory and the Jitter
would perform a lookup when compiling and map straight to that adress. Our
applications would share the same QWERTY.

As there are plenty of "" in most applications, the address of this empty
string would be one of the first constant to load and also combat well for a
place in hardware-cache.

Anyways, calling String.Empty does not give less performance. C# may call
that a static property getter, CIL may call it a static getter method, but
the JITter don't care, but knows CIL and the FCL all too well and will
optimize. Hence it will simply compare to "".

What you read as C# is not what's happening in the runtime.

Regards
- Michael S

Nov 17 '05 #16
> I agree theer are cases where you could find it useful for a nullable
string. But those cases are way far inbetween your regular use of strings.


Not if you're reading them from databases, they aren't. As well, you
provided your own example: XML with missing nodes. A null string means
"missing". An empty string means "present and empty". They're two
different things. For database handling, I did the same thing you did
for the XML: wrote a method that reads strings and supplies a default
if missing (usually the empty string, but sometimes null). However, I
think that simply eliminating the difference would be a bad idea.

As for String.Empty, I agree with Frank, although I wouldn't use the
word "snobbery." "Pedantic," maybe. I don't care much about typing
extra characters, but it's harder to read... all to satisfy some sense
of O-O "purity." I have better things to do with my time. :)

Nov 17 '05 #17
Michael S <a@b.c> wrote:
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
Every > time you use "" you are allocating a new string instead of using
System.String.Empty.


This is simply not true.

if you read the specs on C# you may think this is so.


You certainly shouldn't. From the C# spec:

<quote>
When two or more string literals that are equivalent according to the
string equality operator (§14.9.7), appear in the same assembly, these
string literals refer to the same string instance.
</quote>

It doesn't say whether the intern pool is per assembly, per AppDomain
or per host (I believe it's per AppDomain), only specifying that it
must be at *worst* per assembly, but it does at least specify that
much.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #18
Michael S <a@b.c> wrote:
I find I need a nullable string more often than I need nulls of most
other types - Forms, Streams, Encodings etc. Personally, I don't find
it a problem at all that strings can be null - just like other
parameters etc, you need to check them in appropriate places if only
certain values are valid.

Of course, this is where something like Spec# comes in handy...
Well, I mostly do web applications and 99% of the strings I allocate is for
HTML output.
I think most asp.net devs are quite sick and tired of all them null pointer
exceptions you always get when fast-coding.


And do you really believe that *all* the places you get
NullReferenceExceptions, you would actually want an empty string?
Removing null strings in favour of always having empty strings instead
just means you defer finding those bugs until you check whether or not
you *really, really* meant to get an empty string.
I also do a lot of import/export using XML. It's a nightmare. if a node is
missing on a xpath-expression you get the darn null again.


And you'd rather see an empty string *every* time? Again, I'd rather
find the bug early...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #19

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael S <a@b.c> wrote:
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
Every > time you use "" you are allocating a new string instead of using
System.String.Empty.


This is simply not true.

if you read the specs on C# you may think this is so.


You certainly shouldn't. From the C# spec:

<quote>
When two or more string literals that are equivalent according to the
string equality operator (§14.9.7), appear in the same assembly, these
string literals refer to the same string instance.
</quote>

It doesn't say whether the intern pool is per assembly, per AppDomain
or per host (I believe it's per AppDomain), only specifying that it
must be at *worst* per assembly, but it does at least specify that
much.

In V1.x when you load an assembly, all string literals are intern'ed, The
interning buffer is per AppDomain, but they can be intern'ed accross
AppDomains when assemblies are loaded domain neutral.
Note that v2.0 makes it possible to opt-in or opt-out of this behavior by
marking an assembly as not requiring string literal interning (see
CompilationRelaxationsAttribute NoStringInterning).

Willy.
Nov 17 '05 #20

Michael S wrote:
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
Every > time you use "" you are allocating a new string instead of using
System.String.Empty.
This is simply not true.

if you read the specs on C# you may think this is so. Even if you read the
specs for CIL you may still believe this is what would happen. But it's not.
The CLR and the JITter could care no less about C# and CIL specs.


It is.

In the String class the the field is declared:

public static readonly string Empty;
and the static constructor is:

static String()
{
string.Empty = "";
string.WhitespaceChars = new char[0x15] {
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000',
'\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007',
'\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
} ;
}

The CLR holds a VERY global Hashtable for all constants in the runtime. This
table are manged by CLR and hence have priviliged acess to cross application
domains. So if your application have a

myStr = myStr1 + "QWERTY" + myStr2;

and my application has

aStr = "QWERTY" + anyStr;

the CLR would have only one single copy of QWERTY in memory and the Jitter
would perform a lookup when compiling and map straight to that adress. Our
applications would share the same QWERTY.

As there are plenty of "" in most applications, the address of this empty
string would be one of the first constant to load and also combat well for a
place in hardware-cache.

Anyways, calling String.Empty does not give less performance. C# may call
that a static property getter, CIL may call it a static getter method, but
the JITter don't care, but knows CIL and the FCL all too well and will
optimize. Hence it will simply compare to "".

What you read as C# is not what's happening in the runtime.

Regards
- Michael S


Nov 17 '05 #21

Michael S wrote:
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
Every > time you use "" you are allocating a new string instead of using
System.String.Empty.
This is simply not true.

if you read the specs on C# you may think this is so. Even if you read the
specs for CIL you may still believe this is what would happen. But it's not.
The CLR and the JITter could care no less about C# and CIL specs.


It is.

In the String class the the field is declared:

public static readonly string Empty;
and the static constructor is:

static String()
{
string.Empty = "";
string.WhitespaceChars = new char[0x15] {
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000',
'\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007',
'\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
} ;
}

The CLR holds a VERY global Hashtable for all constants in the runtime. This
table are manged by CLR and hence have priviliged acess to cross application
domains. So if your application have a

myStr = myStr1 + "QWERTY" + myStr2;

and my application has

aStr = "QWERTY" + anyStr;

the CLR would have only one single copy of QWERTY in memory and the Jitter
would perform a lookup when compiling and map straight to that adress. Our
applications would share the same QWERTY.

As there are plenty of "" in most applications, the address of this empty
string would be one of the first constant to load and also combat well for a
place in hardware-cache.

Anyways, calling String.Empty does not give less performance. C# may call
that a static property getter, CIL may call it a static getter method, but
the JITter don't care, but knows CIL and the FCL all too well and will
optimize. Hence it will simply compare to "".

What you read as C# is not what's happening in the runtime.

Regards
- Michael S


Nov 17 '05 #22

I am not sure if Brad Adams is talking about v1 or pre service pack (if it
matters anyway) but he is also implying the same arguments as mine:

http://blogs.msdn.com/brada/archive/.../22/49997.aspx

| Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
String literals are interned. Every time you use "" you are receiving
the
exact same string instance as String.Empty!

I see your point, and i also went to the extent of pinning both with a GCHandle
"" and Empty and got the same address of pinned object for both... so Brad
may be wrong after all... I really dont know.

The discurssion started because someone said that using String.Empty as snobbery,
but IMHO I believe it is a good idea cause at least it becomes easier to
read .
As far as memory reuse and allocation it still a good aproach for value types
that you need to use all the time such as System.Drawing.Point.Empty, or
your own value type MyType.Empty (MinValue, MaxValue, etc...) since you can
not default them to null.
Erick Sgarbi
www.blog.csharpbox.com
Erick,
| Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
String literals are interned. Every time you use "" you are receiving
the
exact same string instance as String.Empty!
Try the following code:

object s1 = String.Empty;
object s2 = "";
object s3 = new string('\0', 0);
Debug.WriteLine(s1 == s2, "s1 == s2");
Debug.WriteLine(s1 == s3, "s1 == s3");
s1 == s2 as they are the same instance, while s1 != s3 as they are
different instances. Using object variables forces the compiler to use
object references instead of the String overloaded operators.

Hope this helps
Jay
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
|
| System.String.Empty is a static readonly public field. When you call
it
from
| any part of your application, there is no extra allocation of a new
string
| since there is only one protected copy that is shared among
everyone.
Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
| Even though string are classes, they are imutables so everytime you
reasing
| the "" it is creating a new copy.
| Empty, MinValue, MaxValue...etc are not only good ways to keep a
standard
| of your default values but also to "reuse" them without extra memory
allocation.
|
| Erick Sgarbi
|
| > I've seen recently some programmers using
| >
| > string s = String.Empty;
| >
| > instead of traditional
| >
| > string s = "";
| >
| > Is there any logical reason for this or just OOP snobbery? Regards
| >
|
|

Nov 17 '05 #23
I am not sure if Brad Adams is talking about v1 or pre service pack (if it
matters anyway) but he is also implying the same arguments as mine:

http://blogs.msdn.com/brada/archive/.../22/49997.aspx

| Every
| time you use "" you are allocating a new string instead of using System.String.Empty.
String literals are interned. Every time you use "" you are receiving
the
exact same string instance as String.Empty!

I see your point, and i also went to the extent of pinning both with a GCHandle
"" and Empty and got the same address of pinned object for both... so Brad
may be wrong after all... I really dont know.

The discurssion started because someone said that using String.Empty as snobbery,
but IMHO I believe it is a good idea cause at least it becomes easier to
read .

As far as memory reuse and allocation it still a good aproach for value types
that you need to use all the time such as System.Drawing.Point.Empty, or
your own value type MyType.Empty (MinValue, MaxValue, etc...) since you can
not default them to null.
Erick Sgarbi
www.blog.csharpbox.com
Erick,
| Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
String literals are interned. Every time you use "" you are receiving
the
exact same string instance as String.Empty!
Try the following code:

object s1 = String.Empty;
object s2 = "";
object s3 = new string('\0', 0);
Debug.WriteLine(s1 == s2, "s1 == s2");
Debug.WriteLine(s1 == s3, "s1 == s3");
s1 == s2 as they are the same instance, while s1 != s3 as they are
different instances. Using object variables forces the compiler to use
object references instead of the String overloaded operators.

Hope this helps
Jay
<er***@csharpbox.com> wrote in message
news:9d************************@msnews.microsoft.c om...
|
| System.String.Empty is a static readonly public field. When you call
it
from
| any part of your application, there is no extra allocation of a new
string
| since there is only one protected copy that is shared among
everyone.
Every
| time you use "" you are allocating a new string instead of using
System.String.Empty.
| Even though string are classes, they are imutables so everytime you
reasing
| the "" it is creating a new copy.
| Empty, MinValue, MaxValue...etc are not only good ways to keep a
standard
| of your default values but also to "reuse" them without extra memory
allocation.
|
| Erick Sgarbi
|
| > I've seen recently some programmers using
| >
| > string s = String.Empty;
| >
| > instead of traditional
| >
| > string s = "";
| >
| > Is there any logical reason for this or just OOP snobbery? Regards
| >
|

Nov 17 '05 #24
<no***********@csharpbox.com> wrote:
I am not sure if Brad Adams is talking about v1 or pre service pack (if it
matters anyway) but he is also implying the same arguments as mine:

http://blogs.msdn.com/brada/archive/.../22/49997.aspx


No, he's not. He doesn't say *every* time you use "" like you did.
Specifically, he says:

<quote>
it will likely be pulled out of the string intern pool
</quote>

And indeed it's guaranteed to be pulled out of the string intern pool
when you use it for the second time in the same assembly.

There's a very big difference between "it might create one more object
per assembly" (not that it does, I belive) and "it creates a new object
every time you use it".

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #25
I put together a quick test case instantiating both types and looked at
the modules through ILDasm. The only difference is how the strings are
retrieved.

“string sEmpty = "";” is equivalent to “IL_0000: ldstr ""” // pushes a
string object for the metadata string token mdToken

“string sEmpty = string.Empty;” is equivalent to “IL_0000: ldsfld string
[mscorlib]System.String::Empty” // push the value of field on the stack

The important note here is: “The common language infrastructure (CLI)
guarantees that the results of two ldstr instructions referring to two
metadata tokens that have the same sequence of characters return
precisely the same string object (a process known as “string
interning”).”

So... the next question you might consider is: What's the performance
implication of “string interning?” I'm assuming it goes through some
kind of hash table to ensure that “the same sequence of characters
return precisely the same string object” which means that it's not
instantaneous.

According to Roman Batoukov “string interning” incurs some additional
cost. “Specifically, the memory used to store interned strings is not
freed until the AppDomain is shutdown, and extra time is required to
intern the string (even if the string is already interned).” Note that
this article refers to the .NET Compact Framework version 2.0 but I'm
sure the same “additional cost“ applies elsewhere.
Conclusion, if you care... use String.Empty.

The embedded links are in this post:
http://blog.radovici.com/eldar/archi...8/19/2435.aspx

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #26

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

Similar topics

3
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
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: 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: 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:
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...
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,...
0
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...

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.