0

Possible Duplicates:
How to initialize array of struct?
Initializing an Array of Structs in C#

C#, Visual studio 2010

I want declare an array of struct and initialize it on the same time but can not get it right How do i write to default initialize an array consisting of structs ?

The following wont go through the compiler but show the idea of what I want to archive

    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    }

    private PrgStrTrans_t[] PrgStrTrans = { {1, "hello", "there"}, {2, "Fun", thisone"}}

Is it possible at all ?

0

2 Answers 2

1

Add a constructor to your struct, and put new PrgStrTrans(...), on each line of the array.

Like this:

private struct PrgStrTrans_t
{
    public int id;
    public string name;
    public string fname;

    public PrgStrTrans_t(int i, string n, string f)
    {
        id = i;
        name = n;
        fname = f;
    }
}

private PrgStrTrans_t[] PrgStrTrans = {
                                          new PrgStrTrans_t(4, "test", "something"),
                                          new PrgStrTrans_t(2, "abcd", "1234")
                                      }
Sign up to request clarification or add additional context in comments.

Comments

0
private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};

It would be better if you made a constructor, that would avoid typing the property names.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.