Sasha
Sasha

Reputation:

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

Upvotes: 1

Views: 234

Answers (4)

Ray Lu
Ray Lu

Reputation: 26648

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; 
}

Upvotes: 2

JaredPar
JaredPar

Reputation: 754585

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

Upvotes: 1

Charles Graham
Charles Graham

Reputation: 24835

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.

Upvotes: 1

baretta
baretta

Reputation: 7595

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

Upvotes: 2

Related Questions