0

Which is better return null or empty object?

var entity = GetFromDB();
if (entity != null)
{
    var price = entity.Price != null 
        ? PriceDecorator.Decorate(entity.Price) 
        : null;
}

    public class PriceDecorator
 {
     public static string Decorate(decimal? price)
     {
         if (price == null || price == 0)
             return String.Empty;

         return String.Format(CultureInfo.CurrentCulture , "{0:C}", price);
     }
 }

In the above code, sometimes I return null and sometimes I return Sting.Empty, I don't know what to return to indicate 'no data'.

Any advice?

Thanks in advance

Rana
  • 1,170
  • 3
  • 14
  • 28

1 Answers1

4

It depends:

  • When I return string.Empty on a property of an object, it means that the entity does exist, but the object doesn't have a property or the property is in fact a string with no characters.

  • When I return null instead of string.Empty it means that the entry/entity doesn't exists, in other words, there is no data

Enrique Zavaleta
  • 2,098
  • 3
  • 21
  • 29