.NET
string length
C#
programming
memory management
Maximum length of a C# / .NET string
Codemia Knowledge Hub ·
A .NET string can hold about 1,073,741,823 characters in theory. The limit comes from the CLR's maximum size for a single object, roughly 2 GB (2,147,483,647 bytes), and each char in a string takes 2 bytes because strings use UTF-16.
Where the limit comes from
A string is an immutable sequence of char values, so its maximum length is bounded by the memory the runtime allows for one object:
- The maximum size of a
stringobject is tied to the maximum size of a single object in the CLR (Common Language Runtime), approximately 2 GB (2,147,483,647 bytes). - Strings use UTF-16 encoding, with each character consuming 2 bytes.
- So the maximum number of characters is in theory around 1,073,741,823 (
2 GB / 2 bytes per character).
Why real limits are much lower
- .NET allocates large objects, such as big strings, on the Large Object Heap (LOH), which is collected less frequently than the regular heap. This can waste memory through fragmentation.
- Very large strings hurt performance: concatenation, copying and searching all cost more.
- Available physical memory and CPU usually impose limits far below the theoretical one.
Handling large text
- Use
StringBuilderfor string manipulation to reduce overhead and fragmentation. - Keep an eye on the memory footprint when handling large volumes of text.
- Monitor and optimize memory used by large strings with the profiling tools in Visual Studio or other .NET performance suites.
Related reading
- What is the maximum sum of squares of two non-attacking rooks placed on a matrix?
- what is the meaning of O1, On, Onn memory?
- What is the meaning of O polylogn ? In particular, how is polylogn defined?
- what is the meaning of restrict in the function signature?
- What is the most efficient way to save a byte array as a file on disk in C?
- What is the Mutex and semaphore In c? where we need to implement?
- What is the memory consumption of an object in Java?
- What is the minimum cost to connect all the islands?

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.