I can't append an object to an array after a foreach loop. The object is okay, it contains all the right values which I found out through debugging.
In the end I want to have a custom Exercise object which contains a user-chosen number of custom ExerciseAnswer objects also. The array of ExerciseAnswer objects is the problem.
Here is the interesting part of my method:
static void CreateNewExerciseTest()
{
string? exerciseName = "Test Exercise";
string? exerciseTopic = "Test";
string exerciseQuestion = "Does it work?";
int numberOfAnswers = 2;
int numberOfApplicableAnswers = 0;
ExerciseAnswer[] exerciseAnswers = new ExerciseAnswer[2];
foreach (ExerciseAnswer answer in exerciseAnswers)
{
int exerciseAnswerId = GenerateId();
Console.WriteLine("\nEnter a name for this Exercise answer: ");
string? exerciseAnswerName = Console.ReadLine();
Console.WriteLine("Enter this answer for the Exercise: ");
string exerciseAnswerContent = Console.ReadLine();
Console.WriteLine("Enter y (yes) if this Exercise answer is applicable,
otherwise press n (no) or any other key: ");
char applicableAnswer = Console.ReadKey().KeyChar;
bool applicable = ExerciseAnswer.EvaluateExerciseAnswer(applicableAnswer);
if (applicable == true)
{
numberOfApplicableAnswers++;
}
ExerciseAnswer exerciseAnswer = new ExerciseAnswer(exerciseAnswerId,
exerciseAnswerName, exerciseAnswerContent, applicable);
exerciseAnswers.Append(exerciseAnswer);
// ...
}
}
This the GenerateId method:
static int GenerateId()
{
return ++id;
}
The array exerciseAnswers does not contain the ExerciseAnswer elements it should while the exerciseAnswer object in the line above does. Maybe the problem is related to the declaration and initialization of exerciseAnswers and the foreach loop.
Has somebody have an idea?
Thank you!
Appendmethod come from? You cannot append to an array in C#. You can to a List or similar datastructure but arrays are fixed-size. This shouldn't even compile.