What is the maximum possible length of a .NET string?

后端 未结 8 1815
梦毁少年i
梦毁少年i 2020-11-22 02:48

What is the longest string that can be created in .NET? The docs for the String class are silent on this question as far as I can see, so an authoritative answe

8条回答
  •  礼貌的吻别
    2020-11-22 03:29

    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
    }
    

提交回复
热议问题