Re: newbie trouble making array of instances
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Mon, 30 Jul 2007 18:51:52 +0100
G.Doten <gdoten@xxxxxxxxx> wrote:
static void Main(string[] args)
{
string x = new string(new char[]{});
string y = new string(new char[]{});
Console.WriteLine(object.ReferenceEquals(x,y));
I believe that these instances are the same because of this comment in
the documentation for the char[] constructor: "If value is a null
reference or contains no element, an Empty instance is initialized." So
your code is the same as doing this:
string x = string.Empty;
string y = string.Empty;
Well, that just says it's documented - it doesn't explain *how* it
happens. Calling a constructor should logically (and even according to
the C# spec) create a new object. You certainly can't create a C# class
which has this behaviour, for instance.
The references didn't wind up equal. Particularly surprising was that
"" is not reference equal to string.Empty. I wasn't really all that
surprised that str1 didn't wind up equal to anything else, but I was
surprised that str2 and str3 weren't equal references.
I believe that whenever you use '""' in a C# program, the compiler emits
a new instance for each of those quote pairs. Since string.Empty is
itself an instance of the string class then string.Empty does not refer
to the same instance as "".
C# guarantees that all uses of the same string constant within an
assembly use the same object.
Strings are immutable so when you did this:
str1 = str1.Remove(0, str1.Length);
The old instance of str1 was replaced with a whole new instance.
Well, the value of str1 was replaced with a reference to a different
instance. The string itself wasn't being replaced.
However String.Remove certainly *could* detect that the result was
going to be an empty string, and return string.Empty instead of
creating a new empty string.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: newbie trouble making array of instances
- From: G.Doten
- Re: newbie trouble making array of instances
- References:
- newbie trouble making array of instances
- From: luke
- Re: newbie trouble making array of instances
- From: Alberto Poblacion
- Re: newbie trouble making array of instances
- From: Göran Andersson
- Re: newbie trouble making array of instances
- From: Jon Skeet [C# MVP]
- Re: newbie trouble making array of instances
- From: Peter Duniho
- Re: newbie trouble making array of instances
- From: G.Doten
- newbie trouble making array of instances
- Prev by Date: Re: Controls Added To TabPages In Designer - How Do You Access?
- Next by Date: Re: The type or namespace name 'UpdateProduct' could not be found (are you missing a
- Previous by thread: Re: newbie trouble making array of instances
- Next by thread: Re: newbie trouble making array of instances
- Index(es):
Relevant Pages
|
Loading