The maximum string length in C# is 2^31 characters. That's because String. Length is a 32-bit integer.
Environment String Length. There is a maximum of 32768 characters for any environment string used as a command-line argument.
The maximum length of the query string, in number of characters. The default is 2048.
The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine.
This is one of those situations where "If you have to ask, you're probably doing something wrong."
Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).
UPDATE:
After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException
at 1,000,000,000 characters.
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
int i = 100000000;
try
{
for (i = i; i <= int.MaxValue; i += 5000)
{
string value = new string('x', i);
//WL(i);
}
}
catch (Exception exc)
{
WL(i);
WL(exc);
}
WL(i);
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
Since the Length
property of System.String
is an Int32
, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32
size). If it allowed longer you couldn't check the Length since that would fail.
For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…
The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.
The problem with s += "stuff"
is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff"
is extremely costly.
If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:
StringBuilder sb = new StringBuilder(5000);
for (; ; )
{
sb.Append("stuff");
}
StringBuilder
will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With