Skip to content

Instantly share code, notes, and snippets.

@odalet
Created July 22, 2015 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odalet/6fbad1949f3b61ff76c6 to your computer and use it in GitHub Desktop.
Save odalet/6fbad1949f3b61ff76c6 to your computer and use it in GitHub Desktop.
Demonstrates compile-time string constants are interned in C#, and side-effects when using direct memory access to those strings.
using System;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var s1 = "Immutable String";
var s2 = "Immutable String";
var s3 = s1;
var s4 = s2;
unsafe
{
fixed (char* ptr = s1)
{
*(ptr + 1) = '_';
*(ptr + 2) = '_';
}
}
Console.WriteLine("S1 = " + s1); // Prints I__utable String
Console.WriteLine("S2 = " + s2); // Prints I__utable String too!
Console.WriteLine("S3 = " + s3); // Prints I__utable String too!
Console.WriteLine("S4 = " + s4); // Prints I__utable String too!
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment