Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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

Upvotes: 8

Views: 3285

Answers (4)

TheXenocide
TheXenocide

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

thecoop
thecoop

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

Nissim
Nissim

Reputation: 6553

and if you want it to be an instance:

where T : new()

Upvotes: -1

this. __curious_geek
this. __curious_geek

Reputation: 43207

Define T to be a class.

struct Foo<T> where T : class
{
  T field; // Now it's a reference type.
}

Upvotes: 11

Related Questions