I’m trying to create a small proof-of-concept application for my boss, however the code I’ve created that simulates what he’s trying to pull off isn’t working.
for (int i = 0; i < 5000; i++)
{
((IList<string>) obj2.Stuff).Add("Iteration " + i.ToString());
}
I’m trying to pull this off all in one line because this is what his code looked like the other day in the framework we’re working on. Anywho when the code above executes, I get a runtime error saying “Collection was of a fixed-size”. And when I try casting to a List instead of an IList, I get an InvalidCastException saying “Unable to cast object of type ‘System.String[]’ to type ‘System.Collections.Generic.List`1[System.String]’.”
Anybody have any ideas on how I can pull off a single-line cast to add an item to the IEnumerable or help me figure out a way around the two errors I keep getting? Thanks in advance.
EDIT (4/19/2011 10:49AM EST)
I’m adding more code to help people out — probably should’ve done this earlier. Sorry.
Program.cs:
#region Cast Test
Class1 obj2 = new Class1();
obj2.Stuff = Enumerable.Empty<string>();
Console.WriteLine("Cast - Start Time: " + 0 + "ms");
Stopwatch stopwatch2 = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 5000; i++)
{
((IList<string>) obj2.Stuff).Add("Iteration " + i.ToString());
}
stopwatch2.Stop();
Console.WriteLine("Cast - Stop Time: " + stopwatch2.ElapsedMilliseconds.ToString() + "ms");
#endregion
Class1.cs:
public class Class1
{
private IEnumerable<string> stuff;
public IEnumerable<string> Stuff
{
get { return stuff; }
set { stuff = value; }
}
}
In comments on one of the answers above you say “I’m trying to avoid copying the list.”
You are trying to add data to an object whose underlying type is
IEnumerable<T>. But anIEnumerableobject is not an actual container, it’s an interface. You can’t add stuff to an interface. But you can assign another object that implements that interface to it.So to use foson’s example above, you could just do:
Note that when this code executes, nothing actually happens. No objects will be created until something actually iterates over
obj2.Stuff. When that happens, the methods in LINQ will be called that create objects one at a time and return them to the iterator loop.But there’s no actual storage device involved here. You can iterate over
obj2.Stuffand unless you consequently added each integer to something else, they would be gone at the next iteration.The fundamental point here is you can’t store things in
IEnumerable, rather,IEnumerableis a way to return objects in sequence, and that could be from a list construct, or from a function that generates a sequence.