I have in instance of class foo and i want to return it as IEnumerable. Can i do it without creating a new list etc..
Perhaps something like the following:
Options:
ReadOnlyCollection<T>
wrapper around such a collection though.Enumerable.Repeat(item, 1)
from LINQ, if you're using .NET 3.5.The best answer here depends on the usage. If you only need this to call another method which uses a sequence, and you know it won't be modified, I'd probably use an array. For example, in order to call Concat
on some other sequence, you might want:
var wholeList = regularList.Concat(new[] { finalValue });
I have confidence that Concat
isn't going to mutate the array, and nothing else will ever see the reference to the array itself.
If you need to return the sequence to some other code, and you don't know what it might do with it, I'd probably use Enumerable.Repeat.
IENumerable is supposed to be used for something that you can enumerate through, so using it for a single instance seems quite strange. If you really need to, you can get it done like this. It might be a better way, but this should get the job done:
List<foo> myList = new List<foo>();
myList.Add( myInstanceOfFoo );
IEnumerable myEnumerable = myList.AsEnumerable();
Regardless of how you see this, you are actually trying to make a list of one element, and then it's really no reason to make it a list.
you could do this:
public IEnumerable<Foo> GetSingleFooAsEnumerable() {
yield return singleFoo;
}
The best idiomatic way to do this is something like new[] { foo }
which just creates a 1-element array of whatever type foo
is declared to be.
The one possible downside to this is that arrays aren't immutable, so somebody can cast your IEnumerable<T>
to a T[]
and change the value in there. This is fairly unlikely, though, so I don't worry about it.