简体   繁体   中英

C# Object reference not set to an instance of an object

I am getting this NullReferenceException in the second execution of the while loop of the changeColors function.

public class myClass {
    Tuple<int,int>[] theArray = new Tuple<int, int>[100];
}

public myClass() {
    theArray = null;
}

public Tuple<int,int>[] findRedPixels(){
    Tuple<int,int>[] myArray = new Tuple<int, int>[100];
    int k = 0;
    for (int i=0; i<n; i++) {   
        for (int j=0; j<n; j++) {
            if (graph.pixelMap [i, j].color == "red") {
                myArray[k]= new Tuple<int,int>(i,j);
                k++;
            }
        }
    }

    return myArray;
}

public void changeColors(){  
    while (true) {
        theArray = findRedPixels();
        foreach (var item in theArray) {

            //error appears here in the second time it executes the while loop
            Console.WriteLine (item.Item1 ); 
        }
    }                
}

You should not return array from function findRedPixels as you have done because that array will already be initialized with 100 elements, try using List as it provide you flexibility and you can increase decrease size on fly may be something like this

public  Tuple<int,int>[]  findRedPixels(){
            List<Tuple<int,int>> myArray = new List<Tuple<int, int>>();
            int k = 0;
            for (int i=0; i<n; i++) {   
                for (int j=0; j<n; j++) {
                    if( graph.pixelMap [i, j].color=="red"){
                         myArray.Add( new Tuple<int,int>(i,j));
                        k++;
                    }
                }
            }
            return myArray.ToArray();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM