Answer the question
In order to leave comments, you need to log in
What to return, Empty collection or null?
Actually the question itself, what is considered the best practice, return Enumerable.Empty() or null? And specify the return type List or IEnumerable?
For example, there is a method that returns a list of addresses, which option would be correct?
public IEnumerable<Adresses> GetAdresses()
{
try
{
return dbContext.Adresses.ToList();
}
catch (Exception)
{
return Enumerable.Empty<Adresses>();
}
}
public List<Adresses> GetAdresses()
{
try
{
return dbContext.Adresses.ToList();
}
catch (Exception)
{
return null;//или что-нибудь вроде new List<Adresses>
}
}
Answer the question
In order to leave comments, you need to log in
It's better to return an empty list. Business logic, as a rule, checks the collection for the presence of at least some elements (Count/Length>0) or on the basis of (Where().Count/Length>0). Returning NULL will precede these additional checks. checking for NULL. Personally, for what reasons do you want to return NULL?
UPD: There is an alternative - to constantly catch NullReferenceException, but you can use the goto statement with the same success.
Of course, an empty collection .. you even have a signature about this. In the case of Null, you cannot pass the result further (to the function that takes List<Addresses>) without additional checks. In general, a lot depends on the requirement and context, in the latter case, for example, you can throw the appropriate exception (talking about an empty list), which will be processed further. But, it seems to me more logical to return an empty collection of a given type.
It's better to return OperationResult in both cases, like this:
public class OperationResult<T>
{
T Result { get; set; }
string Message { get; set; }
bool IsSuccessful { get; set; } // можно заменить на enum с бОльшим количеством вариантов
}
Good afternoon!
The correct option would be:
public IEnumerable<Adresses> GetAdresses()
{
try
{
return dbContext.Adresses.ToList();
}
catch (Exception ex)
{
// Логируем ошибку - что-то вроде:
//_loggerService.Error(ex);
throw;
}
}
public ActionResult Addresses()
{
try
{
var addressList = _dataService.GetAdresses();
return View("_Addresses", addressList);
}
catch (Exception ex)
{
TempData["Error"] = "Не удалось загрузить список адресов. Попробуйте позже."
return View("_Addresses");
}
}
<div>
@if(Model != null && Model.Any())
{
<div>
@foreach(var address in Model)
{
@*Здесь вывод Ваших адресов*@
}
</div>
}
else
{
<div>
@TempData["Error"]
</div>
}
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question