I have written a function Reverse to reverse a string in .net using pointers in unsafe context.
I do like this.
I allocate “greet” and “x” same value.
I reverse greet to my surprise x also gets reversed.
using System;
class Test{
private unsafe static void Reverse(string text){
fixed(char* pStr = text){
char* pBegin = pStr;
char* pEnd = pStr + text.Length - 1;
while(pBegin < pEnd){
char t = *pBegin;
*pBegin++ = *pEnd;
*pEnd-- = t;
}
}
}
public static void Main(){
string greet = "Hello World";
string x = "Hello World";
Reverse(greet);
Console.WriteLine(greet);
Console.WriteLine(x);
}
}
Nothing odd about that. You’re seeing interning. If you write:
immediately after the declaration, you’ll see that you’ve only got one string object. Both your variables refer to the same object, so obviously if you make a modification to the object via one variable, you’ll see the same change when you access it later through the other variable.
From the C# 4 spec, section 2.4.4.5:
Oh, and I hope that in real code you’re not actually modifying strings using unsafe operations…