I'm new to C#, and I created a struct (MyMeshFace
) and initialized an array consisting of some 40.000 of those structs, like so:
MyMeshFace[] m_meshFaces = new MyMeshFace[mesh.Faces.Count]; // ~40.000 faces
I then populate the array with data in a for-loop, debugging it all with breakpoints so that I can see with my own eyes that field objects are instantiated with empty values (i.e. edge = new Line();
etc) and after this initialization, seeing also that values are properly assigned to fields and object fields (like Line.From = Point;
& Line.To = AnotherPoint;
etc).
Problem: But, when I run through this list of m_meshFaces a second time, this time calling a function embedded in the struct in order to make the struct update its internal data, then the objects (Lines
) no longer has any values!
The Line objects in the structs really are instantiated, and thus they're valid objects and so they don't throw exceptions when accessed, but their values (X,Y,X) are zeroed (although I could via breakpoints see that the Lines
were originally assigned with values in the first loop when they were initialized). And I have no idea why this is happening.
The code is straightforward:
public struct MyMeshFace
{
public Line edgeAB;
public Line edgeBC;
...
public int facesABC[];
public Point3d[] pointsABC;
...
public void Init(Mesh m, int index)
{
edgeAB = new Line();
edgeBC = new Line();
...
}
public void SetFaceData(Mesh m)
{
// UPDATE 3: Face corner indexes (to points) from mesh:
var face = m.Faces[faceIndex];
facesABC[xA] = face.A;
facesABC[xB] = face.B;
pointsABC[xA] = m.Vertices[facesABC[0]];
pointsABC[xB] = m.Vertices[facesABC[1]];
...
edgeAB.From = pointsABC[xA];
edgeAB.To = pointsABC[xB];
...
}
public bool DoSomething()
{
if (edgeAB.From.X == 0 && edgeAB.From.Y == 0 && edgeAB.From.Z == 0)
return false; /* Fail ! */
//
// Execution never makes it here :(
//
return true;
}
...
}
Main method (Update 2: Added call to Init and SetFaceData)
public void Main()
{
MyMeshFace[] m_meshFaces = new MyMeshFace[m_mesh.Faces.Count];
for (var f = 0; f < m_meshFaces.GetLength(0); f++)
{
var face = m_meshFaces[f];
face.Init(m_mesh, f);
face.SetFaceData(m_mesh);
}
for (var x = 0; x < m_meshFaces.GetLength(0); x++)
{
var face = m_meshFaces[x];
if (face.DoSomething())
Print("Did something!"); # <-- This never happens
}
}
I tried reading on Microsofts pages about structs, but no clue there. What am I doing wrong?
Edit FIX: This code works, according to anwers below:
public void Main()
{
MyMeshFace[] m_meshFaces = new MyMeshFace[m_mesh.Faces.Count];
for (var f = 0; f < m_meshFaces.GetLength(0); f++)
{
// var face = m_meshFaces[f]; // <-- No no!
// face.Init(m_mesh, f); // <-- No no!
// face.SetFaceData(m_mesh); // <-- No no!
m_meshFaces[f].Init(m_mesh, f); // <-- OK!
m_meshFaces[f].SetFaceData(m_mesh); // <-- OK
}
for (var x = 0; x < m_meshFaces.GetLength(0); x++)
{
if (m_meshFaces[x].DoSomething())
Print("Did something!"); // OK!
}
}
// Rolf