Maximum length of a String?

  • Thread starter =?ISO-8859-15?Q?Martin_P=F6pping?=
  • Start date
?

=?ISO-8859-15?Q?Martin_P=F6pping?=

Hello,

does a String in C# have a maximum length?

I tried to write a ToString Method of my class containing a hashtable.
At the beginning of the method i defined a String "ret".

In every iteration of my hashtable I add the content with ret += "...".

After some time my programm crashes.

If i use Console.Writeln in every iteration instead of ret += ...,
then everything works fine.

So I guess it has something to do with a possible maximum length of a
string?


Regards,

Martin
 
M

Morten Wennevik

Hi Martin,

The string itself should handle lengths well above your future memory
limits, but massive string concatenations won't work well if the hashtable
is large.

Instead of ret += "..." use StringBuilder.Append
 
G

Greg Young

John ...

If I remember correctly A few of the upper bits of the length (I believe 3
but don't quote me) are used as flags for other information .. so I believe
this limits it in the MS implementation to 28 bits in length which is
substantially shorter ... of course you are quite unlikely to hit this as
the limit will tend to be the largest contiguous area of memory available.

Cheers,

Greg
 
A

Allan Ebdrup

Greg Young said:
John ...

If I remember correctly A few of the upper bits of the length (I believe 3
but don't quote me) are used as flags for other information .. so I
believe this limits it in the MS implementation to 28 bits in length which
is substantially shorter ... of course you are quite unlikely to hit this
as the limit will tend to be the largest contiguous area of memory
available.

Won't virtual memory let you have a string that is larger than the largest
contiguous area of memory available.
 
W

Willy Denoyette [MVP]

| | > John ...
| >
| > If I remember correctly A few of the upper bits of the length (I believe
3
| > but don't quote me) are used as flags for other information .. so I
| > believe this limits it in the MS implementation to 28 bits in length
which
| > is substantially shorter ... of course you are quite unlikely to hit
this
| > as the limit will tend to be the largest contiguous area of memory
| > available.
|
| Won't virtual memory let you have a string that is larger than the largest
| contiguous area of memory available.
|
|

No, the current CLR versions (both 32 and 64bit) limits the object size to a
maximum of 2GB. As, a System.String instance is just an array of unicode
bytes, it means that the string is limited to 1GB characters. Note that on a
32 OS, you will never be able to allocate that object size from the heap,
here the max. size of a string will be much less tha 1GB.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top