MatthewMcGovern
MatthewMcGovern

Reputation: 3496

Is there anyway to specify the possible types for a generic class?

I'm trying to write some code for XNA to have my own drawing modules that I can use to cache/draw static vertices/indices.

Here's the class, the line in question that is giving me trouble is line 51.

_vertexBuffer.SetData(_vertices.ToArray());

It has the error: The type 'T' must be a non-nullable value type in order to use it as parameter 'T'

It doesn't seem to like it as SetData usually expects an array of Vertices that matches the VertexDeclaration used in the VertexBuffers constructor, whilst my definition of the list/class says that it can be any type.

Is there anyway to specify the <T> as vertices?

Upvotes: 0

Views: 132

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65077

They are called generic type constraints. Whatever the VertexBuffer type is, it has this on that method:

void SetData<T>(...) where T : struct

This is what is causing your error.

In fact, MSDN says that this is the method signature:

public void SetData<T> (
     T[] data
) where T : ValueType

Which is essentially the same.

So, to fix this, you'll have to pass in an array of items that are value types, not reference types. That is, your instantiation of DrawModule<T> must be DrawModule<ValueTypeHere>.

Upvotes: 2

Related Questions