System ACCEPTS my solution but I don't understand why

In the task HackedDroid, it is asked the following: Broadcast a special message to break all neighbour droids.

My solution is:
using System;

namespace Null

{

class Droid

{

    private Droid[] _neighbours;

    public Droid()

    {

    }

    public Droid(Droid[] neighbours)

    {

        _neighbours = neighbours;

    }

    public void BroadcastMessage(string message)

    {

        for (int i = 0; i < _neighbours.Length; i++)

        {

            _neighbours[i].ReceiveMessage(message);

        }

    }

    public void ReceiveMessage(string message)

    {

        if (message.Length < 255)

            Console.WriteLine(message);

        else

            Console.WriteLine("Message is too long to display");

    }

}

class DestroyThemAll

{

    public static void Main()

    {

        var droid1 = new Droid();

        var droid2 = new Droid();

        var droid3 = new Droid();

        var droid4 = new Droid();

        var droid5 = new Droid();

        var neighbours = new[] { droid1, droid2, droid3, droid4, droid5 };

        var hackedDroid = new Droid(neighbours);

        hackedDroid.BroadcastMessage(null);

    }

}

}

The system accepts my solution but but have the following error in the console:
System.NullReferenceException: Object reference not set to an instance of an object.
at Null.Droid.ReceiveMessage(String message)
at Null.Droid.BroadcastMessage(String message)
at Null.DestroyThemAll.Main()

I need some insight for this issue.
Thank you beforehand for the hand

1 Like

Hi @kamibenli ,

The point of this assignment is to destroy other droids be broadcasting an invalid message. You did it successfully, and you see the error message that those drones produced - you broke them!
From a programming perspective this assignment shows you that you need to make checks before you call methods on values that can be null. The code above performs this check:
if (message.Length < 255)
and if the message is null - it horribly breaks. This is what you see in the output.
Hope this helps!

1 Like