Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a (generic) value type to be a reference

I have a struct with some fields. One of the fields is of a generic type. The generic type could be either a reference type or a value type.

I want to force that it is stored as a reference internally, to avoid that the struct gets too large.

struct Foo<T>
{
  T field; // should be a reference
}

I know I could use object or T[], but both is awkward. Isn't there something like a generic Reference type?

struct Foo<T>
{
  Reference<T> field;
}

Yes, sure, I could write my own. But I'm trying to avoid that

like image 482
Stefan Steinegger Avatar asked Aug 31 '10 08:08

Stefan Steinegger


2 Answers

Define T to be a class.

struct Foo<T> where T : class
{
  T field; // Now it's a reference type.
}
like image 50
this. __curious_geek Avatar answered Sep 20 '22 23:09

this. __curious_geek


You can use Tuple<T1> to hold your value type variable (Tuples are classes in the BCL)

struct Foo<T>
{
    Tuple<T> field;
}
like image 41
thecoop Avatar answered Sep 19 '22 23:09

thecoop