0

Sorry advance for such a simple question ( I have googled but I am stumped, new to programming)

sample code below

  public Point GetRandomWalkableLocationInRoom(Rectangle room)
    {
        if (DoesRoomHaveWalkableSpace(room))
        {
            for (int i = 0; i < 100; i++)
            {
                int x = Game.Random.Next(1, room.Width - 2) + room.X;
                int y = Game.Random.Next(1, room.Height - 2) + room.Y;
                if (IsWalkable(x, y))
                {
                    return new Point(x, y);
                }
            }
        }


        return null;
    }
Muzzasa
  • 5
  • 1
  • 4
  • 1
    Possible duplicate of [Making a Non-nullable value type nullable](https://stackoverflow.com/questions/596003/making-a-non-nullable-value-type-nullable) – Heretic Monkey Feb 13 '19 at 18:35
  • 2
    Just change the return type of your method to `Point?`. Read more about it [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/). – Tobias Tengler Feb 13 '19 at 18:39
  • You can't return null from this method. Error is here : return null; You should always return new Point(); or throw exception in case of error. But you can't return null because there is no way to convert null to Point() – Vlad Feb 13 '19 at 18:50
  • Thanks, I have entered new Point(); that has done the trick! stupid me! – Muzzasa Feb 13 '19 at 18:55
  • 1
    It seems like returning `new Point();` will introduce a bug. Is it really valid to return 0, 0 if you can't find a walkable point? – Chris Dunaway Feb 13 '19 at 19:00
  • @Muzzasa be careful, it made your code able to build, but it doesn't necessarily mean that it is fixed – Daniel Brughera Feb 13 '19 at 19:39

1 Answers1

4

In the case where DoesRoomHaveWalkableSpace(room) is false, either throw an exception (if that fits your implementation), or return some default value, like 'new Point(double.NaN, double.NaN)' or 'new Point(null, null)'.

Nanna
  • 515
  • 1
  • 9
  • 25