1

I'm not so experienced in C#, I'm used to work in java. I've already asked for something before and some people advised me this. link to my old topic here But I have new problem with this code. The Visual Studio says that "I cannot have instance filed initializers in struct" - so there is some problem but I really don't understand this thing so is somehow possible make this work?? I just need anchors type Vector3 which is matrix or array of arrays - whatever 4x4 In java I'll probably write it public Vector3[][] = new Vector3[4][4];

This is my problematic code:

  [StructLayout(LayoutKind.Sequential)]
    struct BPatch
    {
        public Vector3[][] anchors = new Vector3[][] {new Vector3[4],new Vector3[4],new Vector3[4],new Vector3[4]};
        public uint dlBPatch;// Display list
        public uint texture;// Texture
    }
1

1 Answer 1

1

By the time you've got 5 arrays, you might as well just make it a class. It will behave more sensibly:

class BPatch
{
    private readonly Vector3[][] anchors = new Vector3[][] {new Vector3[4],new Vector3[4],new Vector3[4],new Vector3[4]};
    public Vector3[][] Anchors { get { return anchors; } }
    public uint DlBPatch {get;set;}
    public uint Texture {get;set;}
}

If you have good reason to micro-optimize, a "fixed" array (rather than a jagged array) might be interesting.

Sign up to request clarification or add additional context in comments.

4 Comments

And if I also need to set the anchors?? Why you used readonly?? I really don't much uderstand difference between fixed and jagged array. I found out that jagged array is array of array - thats only I know.
@user1097772 fixed sized arrays (fixed buffers) are an advanced technique in structs using "unsafe" code to embed a buffer directly in a struct. Hardcore stuff. You could make the outer array read-write. But in most cases that is an error; the intent is usually to change the contents, not to reassign the array. It is your type - do as you will. I should also add: most times, when someone new to c# uses a struct, they use it both inappropriately and incorrectly. Just saying...
Thx. I just need to do this: Bpatch bpatch = new Bpatch(); bpatch.anchors[0][1] = new Vector3(-0.75f,-0.75f,-0.5f); bpatch.anchors[0][2] = new Vector3(-0.25f,-0.75f,0.0f); etc.. Is that possible with readonly qualifier? My first intent was have anchors as matrix 4x4
@user1097772 yes; that doesn't reassign the array - should work fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.