Reputation: 64628
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
Upvotes: 8
Views: 3285
Reputation: 1149
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;
}
}
}
Upvotes: 2
Reputation: 46098
You can use Tuple<T1>
to hold your value type variable (Tuples
are classes in the BCL)
struct Foo<T>
{
Tuple<T> field;
}
Upvotes: 3
Reputation: 43207
Define T to be a class.
struct Foo<T> where T : class
{
T field; // Now it's a reference type.
}
Upvotes: 11