Answer the question
In order to leave comments, you need to log in
Signature of a method that takes/returns a list/array as a parameter?
I sometimes have a question - how best to write:
System.Collections.IList Get()
{
return new object[] { };
}
System.Collections.ICollection Get()
{
return new object[] { };
}
System.Collections.IEnumerable Get()
{
return new object[] { };
}
object[] Get()
{
return new object[] { };
}
Answer the question
In order to leave comments, you need to log in
Good day.
You need to choose the return type you really need. There are some subtleties with IEnumerable that you need to be aware of and always keep in mind. I highly recommend both articles, some more information about the collections is here . I will try to fit in a couple of lines the basic rules.
IEnumerable(T) should only be returned in cases where the client is willing to accept an iterator, potentially infinite! In fact, this interface should almost never be used.
IReadOnlyCollection(T)must be returned (and passed to methods) in cases where the client uses these collections, but should not modify them. In most cases, this is exactly the case, we can say that IReadOnlyCollection is used more often than others.
IList(T) and ICollection(T)are returned in case the client might need to modify the collection by adding or removing elements. Such situations are extremely rare. The difference is that in the case of IList(T), the client can access the element by index. As for passing these interfaces as a method argument, this may be needed when the method modifies the collection, such as removing duplicate elements or clearing the collection of old data. There is a choice between explicitly working with the collection or passing IReadOnlyCollection(T) and returning a result of the same type. Depends on the task.
I'd say that IReadOnlyCollection(T) is the most preferred return parameter because it keeps the code structured in this way - you can be sure that the returned collection is not modified further down the code.
ps Ah yes, finally. You have examples of untyped collections that are slower than their generic counterparts due to boxing-unboxing . They should be used only in extreme cases, an example of which I will not even hastily give.
For argument - IEnumerable if you don't need any specific methods. All containers implement it. If there is such a need, then it is better to take the most "wide" type that suits you.
And it is better to return the most "narrow" type of what you need in order to avoid explicit downcasts in the client code.
In general, enjoy all the benefits of covariance and contravariance, if the target platform allows it (contravariance - with C # 4.0 and .Net Framework 4, covariance - initially).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question