0

I am new to C# and I am working on a pretty extensive school project. For the project, I have to create a bus simulator that would allow the user to add a passenger by inputing their name and age, and many otheroptions. One of the options is that the user can find passengers of a specific age group. For the code of this part, I keep on getting a system.nullreferenceexception by Visual Studio. I don't know what I did wrong.

public void find_age()
    {
        //Visa alla positioner med passagerare med en viss ålder
        //Man kan också söka efter åldersgränser - exempelvis 55 till 67
        //Betyg C
        //Beskrivs i läroboken på sidan 147 och framåt (kodexempel på sidan 149)

        Console.Clear();
        Console.WriteLine("===> Passengers within an age group <===");
        Console.WriteLine("");

            Console.Write("Enter top age limit of the passengers to be found: ");
            int maxKey = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter bottom age limit of the passengers to be found: ");
            int minKey = Convert.ToInt32(Console.ReadLine());
            for (int i = 0; i < passengers.Length; i++)
            {
                if (passengers[i].Age >= minKey && passengers[i].Age <= maxKey) //This is where I get the System.NullReferenceException
                {
                    Console.WriteLine("Name of passenger who matches the age: " + passengers[i].Name);
                }
                else
                {
                Console.WriteLine("No matches found");
                }
            }
  • A `NullReferenceException` pretty much always means the same thing. The code assumes that an object exists (is not `null`) and tries to reference a property/method on that object. This is a good opportunity to start familiarizing yourself with the use of a debugger to step through the code and observe its runtime behavior. On the line which throws the exception, at least one of those objects is `null`. You'll need to identify what's `null`, why it's assumed that it shouldn't be `null`, and either change that assumption or correct whatever should be initializing that object. – David Jun 09 '21 at 11:33

0 Answers0