tags:

views:

1456

answers:

2

I've faced alot of confusion in regard to difference of generic reference type vs. generic value type during my API coding.

Guys, the question is what are differences in regard to constraints and functionalities (most important/easily overlooked ones)between these two beasts:

class ReferenceGeneric <T> where ???
{

}

and

struct ValueGeneric <T>: where ???
{


}

Edit Just to clarify the question and what I am after: I want to know what you can do with Generic reference types AND cannot do with generic values types... and visa versa

Edit#2 Further clarifications: How can T be constrained if generic type is reference or value type -- are there differences as to how each type can be constrained?

+9  A: 

Be aware that anything declared as a struct is always a value type, and anything declared as a class is always a reference type. In other words, List<int> is still a reference type, and if you had:

struct Foo<T>
{
    T value;
}

then Foo<string> would still be a value type.

As for what you can do with the generic types - they really just follow the normal rules for value types and reference types; as for what you can do with an value of type T within the type, that depends on whether/how T is constrained. It doesn't vary based on whether the generic type itself is a struct or a class though.

EDIT: Sasha mentions Nullable<T> in the comments. I'm not sure what "exception" is meant here - other than Nullable<T> doesn't satisfy either the "where T : struct" or "where T : class" constraint. It's still a value type though (which is part of the point).

Jon Skeet
Jon, there is an exception if the struct type is Nullable. Would you elaborate on that as well? thx
thanks for elaboration...
" anything declared as a class is always a value type" typo?
ShuggyCoUk
Jon: Fixed your typo to avoid confusion :)
configurator
@configurator: Thanks :)
Jon Skeet
+1  A: 

In response to Edit2: You can limit the types allowed to reference or value by the following:

Reference:

class ReferenceGeneric <T> where T: class
{

}

Value:

struct ValueGeneric <T> where T: struct 
{


}

From the following page on MSDN http://msdn.microsoft.com/en-us/library/d5x73970.aspx

C. Ross
Can you constrain struct by class: struct ValueGeneric <T> where T: class {}