C# Generics: Reference types vs. Value Types

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).


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

Tags:

C#

Generics