© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•13mo ago•
6 replies
spot

Roslyn String Allocation

I'm interested in seeing exactly how Roslyn allocates strings. I looked through the GitHub a bit, but I couldn't find anything related to my question (Don't know where to look).
First, please help me clear any misconceptions that I may have.

For the following lines of code
string x = "test";
x = x.ToUpper() + "2";
string x = "test";
x = x.ToUpper() + "2";

What I think I know:
- The C# compiler, Roslyn, will allocate memory for all initialized data.. We are given a memory address for the variable x and the contiguous memory is filled with the UTF character codes for "test".
- x.ToUpper() is (allocated somewhere new? because strings are immutable), "2" is concatenated to the end of it, and then the contents from the new address is copied to the original address of x.

Assuming I used the Debugger to monitor string x or placed in an additional variable to print its address
unsafe{
string x = "test";
string* strPtr1 = &x;
x = x.ToUpper() + "2";
string* strPtr2 = &x;
C.WL(strPtr1);
C.WL(strPtr2);
}
unsafe{
string x = "test";
string* strPtr1 = &x;
x = x.ToUpper() + "2";
string* strPtr2 = &x;
C.WL(strPtr1);
C.WL(strPtr2);
}


Would the memory address for x stay the same? (Unless there was not enough contiguous memory to support increasing its length?)

Where can I find the details of this?

Would something like this change between versions of C#? Or is this something that would be decided early on and be relatively consistent through the C# life-cycle? Would this change between different operating systems?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ ✅ Splitting string without allocation
C#CC# / help
3y ago
❔ CSharpCompilation using Roslyn
C#CC# / help
3y ago
❔ Roslyn compiler magic?
C#CC# / help
4y ago
❔ Matrix dynamic allocation
C#CC# / help
3y ago