I'm working on a library written in .NET 2.0 that has a static method which returns an object of type list.
During unit testing I ran into a sneaky little bug whereby an exception was being thrown on a line that had nothing to do with the error. Eventually I discovered it was the result of this list returning null.
To prevent this type of situation, I see that the recommended way to return this type of collection is to use Enumerable.Empty<TResult>
. However, that requires Linq (.NET 3.5 +).
Enumerable.Empty<T>()
.NET 2 (non-Linq) equivalent?Here is my attempt to use @EagleBeak's suggestion:
namespace MethodReturnEmptyCollection
{
public partial class Form1 : Form
{
private static List<ExampleItem> MyCustomList = null;
public Form1()
{
InitializeComponent();
MyCustomList = CreateEmptyListOfExampleItems();
}
private static List<ExampleItem> CreateEmptyListOfExampleItems()
{
// Throws an invalid cast exception...
return (List<ExampleItem>)GetEmptyEnumerable<List<ExampleItem>>();
}
public static IEnumerable<T> GetEmptyEnumerable<T>()
{
return new T[0];
}
}
public class ExampleItem
{
// item properties...
}
}
When executed, the following exception is generated:
An unhandled exception of type 'System.InvalidCastException' occurred in MethodReturnEmptyCollection.exe
{"Unable to cast object of type
'System.Collections.Generic.List'1[MethodReturnEmptyCollection.ExampleItem][]' to type 'System.Collections.Generic.List'1[MethodReturnEmptyCollection.ExampleItem]'."}
After EagleBeak's input, I found this question which answers mine and is quite interesting:
Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?
Found this too:
According to Jon Skeet, you can also use yield break
to do the same thing.
Just throw away the two private methods and initialize your list in the constructor like this:
MyCustomList = new List<ExampleItem>()
;
PS: Enumerable.Empty<T>
wouldn't work for you anyway. List<T>
implements IEnumerable<T>
, not the other way round.