1

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);
    }
}
Khan
  • 17,904
  • 5
  • 47
  • 59
Pritesh
  • 1,938
  • 7
  • 32
  • 46

1 Answers1

12

Nothing odd about that. You're seeing interning. If you write:

Console.WriteLine(object.ReferenceEquals(greet, x));

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:

Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator appear in the same program, these string literals refer to the same string instance.

Oh, and I hope that in real code you're not actually modifying strings using unsafe operations...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • but i created 2 instances.. strange. – Pritesh Apr 19 '12 at 14:58
  • 3
    @Pritesh: No you didn't. You declared two variables, and used the same string literal for both, which means you have two variables which both refer to the same string object. – Jon Skeet Apr 19 '12 at 14:59
  • 6
    @Pritesh: No, I've shown that it's specified behaviour. The "glitch" is you modifying string objects, which are normally assumed to be immutable. – Jon Skeet Apr 19 '12 at 15:05
  • was trying conme up our own "stringbuilder" kind of class.. seems need to think solution in safe context... I was wondering if string are immutable how .net compiler/run time allowed me to modify it??? – Pritesh Apr 19 '12 at 15:10