Given the following code and the suggestions given in this question, I\'ve decided to modify this original method and ask if there are any values in the IEnumarable return i
I think the simplest way would be
return new Friend[0];
The requirements of the return are merely that the method return an object which implements IEnumerable<Friend>
. The fact that under different circumstances you return two different kinds of objects is irrelevant, as long as both implement IEnumerable.
public IEnumerable<Friend> FindFriends()
{
return userExists ? doc.Descendants("user").Select(user => new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}): new List<Friend>();
}
You could return Enumerable.Empty<T>().
As for me, most elegant way is yield break
That's of course only a matter of personal preference, but I'd write this function using yield return:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//http://stackoverflow.com/users/67/rex-m
if (userExists)
{
foreach(var user in doc.Descendants("user"))
{
yield return new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}
}
}
}
You can use list ?? Enumerable.Empty<Friend>()
, or have FindFriends
return Enumerable.Empty<Friend>()