What is the reason for OOM when creating a new line
Because you are running out of memory - or at least the CLR cannot allocate an object with the requested size. It's really that simple. If you want to avoid errors, do not try to create strings that do not fit into memory. Note that even if you have a lot of memory, and even if you use the 64-bit CLR, there are limits on the size of objects that you can create.
and why doesn't it throw OOM while writing to a file?
Because you have more disk space than memory.
I'm sure the code is not quite the way you describe. This line will not be able to compile:
sw.write(SB.ToString());
... because the method is Write , not Write . And if you actually call SB.ToString() , then this is as strong as str = SB.ToString() .
It seems more likely that you are actually writing the file in streaming mode, for example.
using (var writer = File.CreateText(...)) { for (int i = 0; i < 5000; i++) { writer.Write(mytext); } }
Thus, you never need to have a huge amount of text in memory - it just writes it to disk, as it is, perhaps with some buffering, but not enough for memory problems.
Jon skeet
source share