2

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! :)

sylargaf
  • 346
  • 1
  • 6
  • 19

2 Answers2

3

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);
ESG
  • 8,988
  • 3
  • 35
  • 52
  • In this situation, methinks `IReadOnlyCollection` is preferable to `ICollection`, especially as it's covariant whereas `ICollection` is invariant. – Dai Nov 12 '22 at 02:37
  • Thank you all so much. Your answer works! ... and made me realize that maybe this isn't the best way of storing data I want too? Essentially charting out a beat map for a song. – sylargaf Nov 12 '22 at 02:40
  • 1
    @sylargaf tbh I don't know enough about that domain to be able to help you regarding data structure. Depends on what you'll end up doing with it in the end. – ESG Nov 12 '22 at 02:49
1

In C#, you can initialize with curly brackets, and specify the property names; like this:

    Beat b = new Beat { beat = "xxx", note = 100, loc = new List<int>() { 1, 2, 5 }, powerup = false };
qwerty13579
  • 156
  • 4