Sasha
Sasha

Reputation:

C# Generics: Reference types vs. Value Types

I've faced a lot of confusion with regards to differences between generic reference types vs. generic value types whilst writing my API.

What are the differences with regards to constraints and functionalities (most important/easily overlooked) between the two?

class ReferenceGeneric <T> where ???
{

}

and

struct ValueGeneric <T>: where ???
{

}

Edit #1 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 value types (and vice 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?

Upvotes: 8

Views: 12334

Answers (2)

C. Ross
C. Ross

Reputation: 31848

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

Upvotes: 11

Jon Skeet
Jon Skeet

Reputation: 1500185

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

Upvotes: 15

Related Questions