Friday, April 8, 2011

String a value type part of generics constraint

If string is a value type, which I assume it is, why would the following declaration be legal:

struct Refsample<T> where T : class

RefSameple<string>; //why is it legal?

Taken from the C# in depth, page 75

From stackoverflow
  • System.String is a reference type, although it has some characteristics of a value type.

  • string is immutable reference type.

    Are you trying to say?

    struct Refsample<T> where T : class
    

    struct itself is value type but it can contain reference type.

    Value type variable stored in the memory stack, but reference type variable has a memory address that pointing to the heap.

    e.g.

    struct Refsample<T> where T : class
    {
       // stored in the stack as well.
       public int Age; 
    
       // memory address pointing to the heap stored in the stack, 
       // but the actual object is stored in the heap.
       public string Name;
       // same as string above if T was reference type;
       // otherwise, if value type, same as Age above.
       public T SomeThing; 
    }
    
    Jon Skeet : A value type value is only stored on the stack when it's (directly or indirectly) part of a local variable. See http://pobox.com/~skeet/csharp/memory.html
  • String is really a reference type that acts like a value type. That's why you can test against null for a string and you can't for int, bool, etc. Well, you can, but you will just get the default value 0, false, etc.

  • System.String is a reference type not a value type.

0 comments:

Post a Comment