Forcing a (universal) value type is a reference

I have a structure with some fields. One of the fields has a common type. A type of a generic type can be either a reference type or a value type .

I want it to be saved as a link inside to avoid too big a structure.

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

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

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

Yes, of course, I could write mine. But I try to avoid it.

+7
reference c # value-type
source share
4 answers

If you are trying to absolutely make sure that any type of value is marked in a square, save it in the object field and use the property to enforce the general constraint; i.e:

 struct Example<T> { private object obj; public T Obj { get { return (T)obj; } set { this.obj = value; } } } 
+2
source share

Define T as a class.

 struct Foo<T> where T : class { T field; // Now it a reference type. } 
+9
source share

You can use Tuple<T1> to store a value type variable ( Tuples are classes in BCL)

 struct Foo<T> { Tuple<T> field; } 
+3
source share

and if you want this to be an instance:

 where T : new() 
-one
source share

All Articles