Search code examples
c#monogame

C#: How to initialize a record that has a List?


got a question that I hope is easy to answer!

I'm self teaching myself C# right now - I do know JavaScript and PHP so far. One thing I've been struggling with is how to deal with List<>, Dictionary<> etc, with regard to actually initiating these things - if that makes sense.

So for example, I have the record:

 record Beat(string beat, int note, List<int> loc, bool powerup);

but I'm having the hardest of time actually declaring this record. For example, I tried this:

Beat beat = new Beat("00:00", 2, [200,400], true);

or even

Beat beat = new Beat("00:00, 2, new(200,400), true);

which both produce errors and I just can't figure out how i'm supposed to declare this.

So I appreciate any help or pointing in the right direction. I tried to Google it but couldn't formulate the query correctly! :)


Solution

  • For a list, you will need to create a new one, and (optionally) add stuff to it.

    ex:

    Beat beat = new Beat("00:00", 2, new List<int> { 200, 400 }, true);
    

    Alternatively, if you were to change your parameter to an ICollection<int>, you would have a bit more flexibility, and you could use the array syntax, which is a bit less typing

    Beat beat = new Beat("00:00", 2, new [] { 200, 400 }, true);