locked
Method parameter memory question RRS feed

  • Question

  • Hi,

    Suppose I have this method:

    public void DoSomethingWith(string secret)
    {
       secret = null;
       // Does the stack contain my secret here?   
    }
    

    When positioned right after setting "secret=null": Is the value of my secret still in memory/stack? Or only as null?

    --
    Werner

    Thursday, October 3, 2013 1:52 PM

Answers

  • Strings are Reference Types.  Instances of Reference Types stored on a heap, not on the stack, and they managed by the Garbage Collector.  Method arguments for Reference Types are passed by value, but they are references.  So that method gets a copy of a reference to an object on the heap.  When you set "secret=null" it has no effect on the string on the heap, and no effect on other references to that string.

    At some point in the future when GC runs and discovers that there are no more references to the string, then it will clean it up.

    David


    David http://blogs.msdn.com/b/dbrowne/


    Thursday, October 3, 2013 2:03 PM