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 generation fails I get an exception "[NotSupportedException: Collection was of a fixed size.]".
This is due to the fact that the Enumerable empty is an IList so the .ToList() is not run and I am then trying to add to a fixed Enumberable.Empty. Am I wrong in thinking that this is bad design, an object that inherits IList (where Add is defined) should support Add?
Am I forced to do var randomList = random.ToList()
or stop using Enumberable.Empty
? Is there some better way?
Update: I think I was unclear in my example. I wish to swallow (or log) the error but allow operation to continue without crashing. My comment "I do this to signal that we have an error" was meant to tell other developers reading the code that this is an abnormal behavior.
The answer to the question Tim linked was what I was getting at. Seems that we just don't have an interface for constant collections so IList
is used.