Reputation:
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
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
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
Reputation: 7595
System.String is a reference type, although it has some characteristics of a value type.
Upvotes: 2