Forcing a (generic) value type to be a reference
-
25-09-2019 - |
Question
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
Solution
If you're trying to be absolutely sure any Value Type is boxed, store it in an object field and use a property to enforce the generic constraint; ie:
struct Example<T>
{
private object obj;
public T Obj
{
get
{
return (T)obj;
}
set
{
this.obj = value;
}
}
}
OTHER TIPS
Define T to be a class.
struct Foo<T> where T : class
{
T field; // Now it's a reference type.
}
You can use Tuple<T1>
to hold your value type variable (Tuples
are classes in the BCL)
struct Foo<T>
{
Tuple<T> field;
}
and if you want it to be an instance:
where T : new()