I'm using an API where I'm implementing an interface that has a method returning an IEnumerable
.
I'm building the collection in my implementation as a List
, because I need the .Add()
method.
Can I then convert this to IEnumerable?
I'm using an API where I'm implementing an interface that has a method returning an IEnumerable
.
I'm building the collection in my implementation as a List
, because I need the .Add()
method.
Can I then convert this to IEnumerable?
Since List<T>
implements both IEnumerable<T>
and IEnumerable
, if you just need it as a return value of a method, you can just return it, e.g:
public IEnumerable<string> GetData()
{
List<string> myList = new List<string>{" data"};
return myList; //works
}
what you get on the other side, when you call the method, will be an IEnumerable<T>
reference that points to a List<T>
object.
That means that the user can use the result wherever he can use an IEnumerable<T>
, but also that a simple cast can expose the inner List<T>
thus allowing modifications of the data. e.g:
IEnumerable<string> result = GetData();
Console.Write(result.First()); // " data";
List<string> resultAsList = (result as List<string>);
resultAsList.Insert(0, "other data");
Console.Write(result.First()); // "other data";
If you want the result not to be changed, you can use the .AsReadOnly
method, to return a ReadOnlyCollection<T>
that is still an IEnumerable<T>
, like this:
public IEnumerable<string> GetData()
{
List<string> myList = new List<string>{" data"};
return myList.AsReadOnly();
}
As Sweko mentioned you can simply return list but in case you don't want the list to be modified from outside, you can call AsEnumerable on your list to expose IEnumerable
outside.
public IEnumerable<string> GetData()
{
List<string> yourList = new List<string>();
return yourlist.AsEnumerable();
}