This is related to conventions used in C#.
I've got a method that has two parameters (X and Y coordinates). These coordinates represent the position at which a "tile" may reside. If a tile resides at these coordinates, the method returns its number. If no tile resides at these coordinates, I'm wondering how the method should behave.
I see three options:
So, what should I do?
Return -1.
This is not just a C++ convention, it's also common in the .NET Framework - e.g. methods like String.IndexOf or properties like SelectedIndex for controls that represent lists.
EDIT
Just to elaborate, of the three options in your question (Exception, return -1, out parameter), returning -1 is the way to go. Exceptions are for exceptional situations, and the Microsoft coding guidelines recommends avoiding out parameters where possible.
In my view returning -1 (provided it's always going to be an invalid value), returning a nullable int, or returning a Tile object are all acceptable solutions, and you should choose whichever is most consistent with the rest of your app. I can't imagine any developer would have the slightest difficulty with any of the following:
int tileNumber = GetTile(x,y);
if (tileNumber != -1)
{
... use tileNumber ...
}
int? result = GetTile(x,y);
if (result.HasValue)
{
int tileNumber = result.Value;
... use tileNumber ...
}
Tile tile = GetTile(x,y);
if (tile != null)
{
... use tile ...
}
I'm not sure I understand Peter Ruderman's comment about using an int being "much more efficient than returning a nullable type". I'd have thought any difference would be negligible.