milnuts
milnuts

Reputation: 427

C# Array without a specified size

I've got a question about creating an array in C# when I don't know the exact number of elements. I've found multiple questions that are similar, like this one. The recommendation there is to use a List instead of an Array. In that example and in all others I've seen its to instantiate a List of 'string's. Can I do the same with a struct?

For example, I have the following struct that I use to store failure information, but I have no idea at the start of test how many failures will occur. It could be 0, it could be hundreds.

    public struct EraseFailures
    {
        public string timestamp;
        public string bus;
        public string channel;
        public string die;
        public string block;
    }

So can I create a List of these as well?

    List<EraseFailures> eFails = new List<EraseFailures>();

It compiles just fine, but I want to make sure this is the best way of doing this. And if it is, what is the syntax for adding values to my List? Because the following doesn't seem correct...

     eFails.bus.Add("bus0");

Seems like I might have to create a new struct with the values I want and then add that to the List.

Upvotes: 2

Views: 15665

Answers (1)

Nino
Nino

Reputation: 7095

If I did understand you correctly, you're asking how to use typed List... Use it like this:

//init list
List<EraseFailures> fails = new List<EraseFailures>();

//make instance of EraseFailuers struct
EraseFailures f = new EraseFailures();
//add data
f.bus = "bus01";
f.channel = "somechannel";
//etc
fails.Add(f);

Upvotes: 5

Related Questions