2

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.

Community
  • 1
  • 1
milnuts
  • 407
  • 2
  • 7
  • 16
  • 8
    *Seems like I might to create a new struct with the values I want and then add that to the List.*: **yes** – xanatos Mar 07 '17 at 15:17
  • 1
    Think about this: what is `eFails.bus.Add("bus0");` supposed to do? where would _bus0_ be added? – Pikoh Mar 07 '17 at 15:18
  • 4
    Please note that [mutable structs are evil](http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil), if you feel the need to create one you should expose read only properties and set the properties in a constructor. – juharr Mar 07 '17 at 15:23
  • 2
    You've already answered your question and you are correct. eFails.Add(new EraseFailures() { bus = "bus0" }); – Michael Puckett II Mar 07 '17 at 15:23
  • Possible duplicate of [Storing data into list with class](http://stackoverflow.com/questions/8391885/storing-data-into-list-with-class) – JHBonarius Mar 07 '17 at 15:44

1 Answers1

5

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);
Nino
  • 6,931
  • 2
  • 27
  • 42
  • Yeah, I thought this was what I needed. Just needed smarter folks than myself to confirm. Thanks. – milnuts Mar 07 '17 at 16:24
  • Glad I helped you. And I am not necessarily smarter, just have a bit more experience. Good luck with your project. – Nino Mar 07 '17 at 16:30