Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Use of unassigned local variable list

Tags:

c#

     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.

like image 803
Script99 Avatar asked Dec 19 '22 17:12

Script99


1 Answers

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.

like image 95
Servy Avatar answered Dec 30 '22 22:12

Servy