Silverlight Student
Silverlight Student

Reputation: 4118

Static objects are pinned and cannot be reallocated by GC?

I have a static variable in my class, when I look at this object via windbg/sos, it shows this object as Pinned. I assume that this mean GC cannot allocate this object anywhere else. Any ideas why static variables are treated as pinned?

Here is the declaration of this variable in my class

namespace ConsoleApplication1
{  
    class Program  
    {  
        static string Name = "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";  
    }  
}  

and here is the output form windbg

0:004> !do 0231bb70   
Name:        System.String  
MethodTable: 6c97f92c  
EEClass:     6c6b8ba0  
Size:        418(0x1a2) bytes  
File:        C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll  
String:        Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa    
Fields:    
      MT    Field   Offset                 Type VT     Attr    Value Name  
6c9828f8  4000103        4         System.Int32  1 instance      202 m_stringLength  
6c981d48  4000104        8          System.Char  1 instance       41 m_firstChar  
6c97f92c  4000105        8        System.String  0   shared   static Empty  
    >> Domain:Value  004f6588:02311228 <<  
0:004> !gcroot 0231bb70   
Scan Thread 0 OSTHread 2824  
Scan Thread 2 OSTHread 1ae0  
DOMAIN(004F6588):HANDLE(Pinned):1613f4:Root:  03312020(System.Object[])->
  0231bb70(System.String)  
DOMAIN(004F6588):HANDLE(Pinned):1613fc:Root:  03311010(System.Object[])->
  0231bb70(System.String)  

See in the output of !gcroot this is displayed as HANDLE(PINNED). Am I misreading this output?

Upvotes: 3

Views: 633

Answers (1)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The reason the string is pinned is not because you have a static reference, but because you have a string literal. String literals are interned by default, and thus you'll see them as pinned. Please see this question as well.

Upvotes: 4

Related Questions