0

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 ); 
        }
    }                
}
4
  • 1
    what is changeColor? can you update the question with code? Commented Dec 5, 2013 at 5:55
  • updated the question with a simpler version Commented Dec 5, 2013 at 6:00
  • 1
    what is findPairsWithCost ? can you paste the code Commented Dec 5, 2013 at 6:02
  • may be Item1 is null, have you debug and check the application? Commented Dec 5, 2013 at 6:02

1 Answer 1

1

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();
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.