3

Possible Duplicate:
C# string reference type?

Say, I have a string called

string sample = "Initial value";

After passing to a method test()

public static void Test(string testString)
{
    testString = "Modified Value";
}

If i print 'sample' after passing Test(sample), I except it should print "Modified Value".

But its printing "Initial Value". Why is that case if string is reference type?

But the same (expected logic), working for object. can someone please clear me?

Community
  • 1
  • 1
VIRA
  • 1,454
  • 1
  • 16
  • 25
  • sorry Raj, your question does not make any sense, provide more code or add some details to your question – Karel Frajták Sep 04 '12 at 09:09
  • Darren Davies, Habib, SMK, - Sorry to give you answer in one shot. I have already read all those questions but possibly i'm unable to get any answer to it. Thats why raised it again across million of users may be those questions raised less that number of users now. – VIRA Sep 04 '12 at 09:20

2 Answers2

6

This has nothing to do with string being a reference type. This is because the parameter is passed by value, not by reference.

If you modify your method like this, so that the parameter is passed by reference:

public static void Test(ref string testString)
{
    testString = "Modified Value";
}

Then sample will be modified.

See this article for more details about parameter passing.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
2

That's because of way how CLR passes the params to method.

Put simply:

string sample = "Initial value";  

Here sample variable refers to "Initial value" string instance stored in heap.

public static void Test(string testString) 
{ 
    testString = "Modified Value"; 
}

In the method you modify testString variable(copy of sample variable) making it references to "Modified Value" string in a heap, leaving original sample variable no affected.

alex.b
  • 4,547
  • 1
  • 31
  • 52