Search code examples
c#return-valueconventions

Which style of return should I use?


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:

  1. Use exceptions. I may raise an exception every time Method finds no tile. However, as this situation is not rare, this option is the worst one.
  2. Do it the old fashioned C++ way and return -1 if there is no tile.
  3. Make the tile number a reference parameter and change the return type of method to boolean to show whether there is a tile or not. But this seems a bit complicated to me.

So, what should I do?


Solution

  • 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.