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