I'm working in C# and XNA.
I have a class:
class Quad
{
public Texture2D Texture;
public VertexPositionTexture[] Vertices = new VertexPositionTexture[4];
}
And I'm trying to create a new instance of said class:
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices[0].Position = new Vector3(0, 100, 0),
Vertices[0].Color = Color.Red
};
Which will then be added to a list of "Quad"s
QuadList.Add(tempQuad);
I keep either getting an error:
"Cannot implement type with a collection initializer because it does not implement 'System.Collections.IEnumerable'"
Or I get told that
Vertices does not exist in the current context.
Is there a reason I can't create class like this? Am I being dumb? Do I have to do it like this?:
Quad tempQuad = new Quad();
tempQuad.Vertices[0].Position = new Vector3(0, 100, 0);
tempQuad.Color = Color.Red;
QuadList.Add(tempQuad);
Is there a way around this at all? Any help would be greatly appreciated.
The object initialize syntax is expecting assignment to properties on the object you're initializing, but by attempting to assign to Vertices[0]
you're trying to assign to properties of an index of a property on the object you're initializing(!).
You can use the object initialization syntax so long as you assign Vertices
directly:
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices = new VertexPositionTexture[]
{
new VertexPositionTexture
{
Position = new Vector3(0, 100, 0),
Color = Color.Red
},
// ... define other vertices here
}
};
As you can see, this gets pretty messy pretty quickly, so you'd probably be better off initializing the array outside of the object initialization:
var vertices = new VertexPositionTexture[]
{
new VertexPositionTexture
{
Position = new Vector3(0, 100, 0),
Color = Color.Red
},
// ... define other vertices here
};
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices = vertices
};