0

I am working on a program to solve a Rubiks Cube for school and there is one error I can't fix: I have a property (Array) with get and set accessor. To avoid possible errors early I check every single Object before it's added to the Array. For that I use two foreach loops: One for every single object and one for all the objects that have already been added (to check whether an object is added twice, which is not allowed). The problem is that even though I check the Length of the Array that's given I get a NullRefernceException saying the current object which is chosen by the foreach loop was null. How is that even possible?

Here is the property:

private cCubePart[] permutation;
public cCubePart[] Permutation
        {
        get { return permutation; }
        set
        {
            if (value.Length == 27)                                                                            
            {
                bool valid = true;                                     
                List<string> id = new List<string>();
                foreach (cCubePart cp in value)                                                                 
                {
                    foreach (string s in id)                                                                    
                    {
                        if (s == cp.StringID)
                        {
                            valid = false;
                        }
                    }
                    if (valid)
                    {
                        id.Add(cp.StringID); //That's where the Exception is thrown; cp is null
                    }
                }
                if (valid)
                {
                    permutation = value;
                }
                else
                {
                    throw new Exception("The Permutation you were trying to set contains cCubePart objects with the same id!");
                }
            }
            else
            {
                throw new Exception("The Permutation you were trying to set doesn't fit the requirements!");
            }
        }
    }
  • More code needed, where do you create the array ? – Jimbot Jun 18 '17 at 10:16
  • This is due to null in `cp`. It's true that `Length` indicates that the collection is not empty, but "not being empty" does not guarantee much. Since the array's element is `cCubePart`, apparently a class, then each of the array's elements can also be NULL. So, you array may look like `[ item1, item2, null, item4, null, ...]` and your code will throw NRE at any time that the loop hits such null (because in that case it read `cp.StringId` with null in `cp`..). Analyze the outer code and ensure that all items are set and that there are no nulls in the array. OR, add `if(cp!=null)` in the loop. – quetzalcoatl Jun 18 '17 at 10:17
  • Thank you, I didn't realize that! – Viktor Relda Jun 21 '17 at 16:10

0 Answers0