.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 string object 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 StringBuilder for 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.

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 course
Data 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.

Practice algorithms