Emmet B
Emmet B

Reputation: 5531

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 ); 
        }
    }                
}

Upvotes: 0

Views: 383

Answers (1)

Deepak Bhatia
Deepak Bhatia

Reputation: 6276

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();
        }

Upvotes: 1

Related Questions