Enumerable.Empty to List

If I, for example, have this method:

IEnumerable<int> GetRandomNumbers()
{
    // {Codes that generate numbers as List<int>}
    if(generationFails == true)
    {
        return Enumberable.Empty<int>(); // I do this to signal that we have an error
    }
    return numbers;
}

In the calling method, I do:

IEnumerable<int> AddNumber(int number)
{
    var random = GetRandomNumbers();
    var randomList = random  as IList<int> ?? random.ToList(); // Run ToList only if needed
    randomList.Add(number); 
    return randomList;
}

and when the generation fails, I get the exception "[NotSupportedException: Collection has a fixed size.]".

This is because Enumerable empty is an IList, so .ToList () does not start, and then I try to add Enumnable.Empty to a fixed one. I am mistaken in thinking that this is a bad design, an object that inherits IList (where Add is defined) must support Add?

Did I have to do var randomList = random.ToList()or stop using Enumberable.Empty? Is there a better way?

Update: , . ( ) , . " , , ", , , , .

, , , . , , IList.

+4
3

Enumerable.Empty , NotSupportedException Array.IList.Add. .

IList?

null , " ". - .

if(generationFails == true)
{
    return null; // I do this to signal that we have an error
}

:

IEnumerable<int> random = GetRandomNumbers();
IList<int> randomList = random == null ? new List<int>() : random.ToList();

, . , , size. - 0 , . .

, new List<int> Enumerable.Empty<int>.

+2

- null . , (, ).

, , , .

"null" , ?

, , . , .

, , .

+5

yield break:

IEnumerable<int> GetRandomNumbers()
{
    if (generationFails)
        yield break;

    foreach (var element in numbers)
    {
        yield return element;
    }
}

This will result in your IEnumerable<int>lazily returning each of the random numbers.

Please note that this will not result in a calling code error. If it generationFailsshould contain an error while executing the code, you should definitely indicate an exception, as others have indicated.

+2
source

Source: https://habr.com/ru/post/1613321/


All Articles