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);
}
}