Does Krzysztof’s recommendation apply to constructors? If so, how do you implement it properly?
We recommend using Collection, ReadOnlyCollection, or KeyedCollection for outputs and properties and interfaces IEnumerable, ICollection, IList for inputs.
For example,
public ClassA { private Collection<String> strings; public Collection<String> Strings { get { return strings; } } public ClassA(IEnumerable<String> strings) { this.strings = strings; // this does not compile this.strings = strings as Collection<String>; // compiles (and usually runs?) } }
You should avoid downcasting; in your example I’d suggest that the type of your contructor parameter should match (should be the same as) the type of your member data (i.e. either
Collection<String>orIEnumerable<String>).Or there’s Marc’s solution, which is different: because Marc’s solution means that your member data isn’t only a different type, it’s also a different instance (i.e. if you modify the member data, then you’re modifying a copy of the original collection, not editing the original collection itself; similarly if the original collection is modified after you make the copy, your local copy/member data doesn’t include this subsequent change to the original collection).