public struct Mp3spelerinfo
{
public string ID;
public string Make;
public string Model;
public string MBSize;
public string Price;
};
//AANMAAK MP3SPELERS DMV STRUCT
public static void maakmp3speler()
{
List<Mp3spelerinfo> myArray;
Mp3spelerinfo speler1;
speler1.ID = "1";
speler1.Make = "GET technologies .inc";
speler1.Model = "HF 410";
speler1.MBSize = "4096";
speler1.Price = "129.95";
myArray[0] = speler1;
}
What can I do to prefent this from happening? What im doing is im trying to get a list so that I can use .Add to make things easier. myArray[0] is where the error is at.
You need to actually create a new list before you do anything else:
List<Mp3spelerinfo> myArray = new List<Mp3spelerinfo>();
Next, you need to add the item to the list. If you try to set the first item you'll just get an error that there aren't that many items in the list:
myArray.Add(speler1);
You should also probably avoid calling a list myArray1
. It's not an array, it's a list. The difference is important. It's probably better to just call it myList
, assuming you don't have a more meaningful name.
I would also strongly advise you to change Mp3spelerinfo
to be a class
, rather than a struct
. It doesn't conceptually represent a single value, dealing with mutable structs is a nightmare if you're not very intimately familiar with lots of very nitty gritty details of C#. You have a lot to lose, and nothing really to gain from using a struct
here. When you make that change, you'll then need to explicitly initialize speler1
using new Mp3spelerinfo();
to create an instance of it. Classes are not implicitly initialized the way structs are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With