views:

117

answers:

3

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

+9  A: 

Define T to be a class.

struct Foo<T> where T : class
{
  T field; // Now it's a reference type.
}
this. __curious_geek
Smart and Quick..
Dienekes
no, I don't want to force that T is a class. When T is a value type, I want that it is stored as reference.
Stefan Steinegger
I rephrased the question to make this clear.
Stefan Steinegger
you could simply box `field` into an object type [which is the only gud solution that comes to my mind]. what exactly are you trying to do ?
this. __curious_geek
I don't want that the struct becomes to big. structs should be small in memory usage. There are other fields in this struct and it is already on the upper limit. If T would be a Guid or an even bigger value type, the resulting struct would be to big.
Stefan Steinegger
A: 

and if you want it to be an instance:

where T : new()
Nissim
It will always be an instance or null ref. you use new() if the object of type T needs instantiation via default constructor of type T at runtime.
this. __curious_geek
+1  A: 

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

struct Foo<T>
{
    Tuple<T> field;
}
thecoop