views:

195

answers:

4

The FxCop says in a rule that generic List should not be exposed to the outside world.

But I do not understand why and what is the replacement for the generice List?

Reference : http://msdn.microsoft.com/en-in/library/ms182142%28en-us%29.aspx

+2  A: 

Always expose the lowest base class/interface in the object hierarchy that will be suitable for your scenario. For example if consumers of this property are going to only iterate over it use IEnumerable(Of T). By exposing a List<T> you are breaking encapsulation by giving client code access to an implementation detail of your class.

Darin Dimitrov
+1  A: 

A generic list is a .NET construct, however web services are often intended to be interoperable with other frameworks.

cxfx
You didn't explain why.
Robert Harvey
Why? *"web services are often intended to be interoperable with other frameworks."* Read please. Not the best explanation, but it does answer why.
Matthew Scharley
No, I didn't, would you like me to?
cxfx
The question asks why.
Robert Harvey
Web services are often designed to be interoperable for use as a loosely-coupled RPC mechanism when integrating heterogeneous systems.
cxfx
+1 Had to think about it awhile, but I get what you are saying.
Robert Harvey
But the list will just be send as a list of strings by soap, rehargles of witch collection class/interface the webmethod uses.
Ian Ringrose
+10  A: 

The reason is that the use of a concrete List<T> is meant to be an implementation detail, and you're meant to expose something more abstract, such as IEnumerable<T> or ICollection<T>, that represents only the functionality you want to expose (such as being enumerable, mutable and/or indexable). This gives you flexibility to change the implementation later on.

In practice, this warning is often resolved by returning IList<T> instead of List<T>, but the idea is to prompt you to think about "what functionality do I actually need to guarantee my callers?" E.g. maybe I should be returning IEnumerable<T> or ReadOnlyCollection<T> because I don't want my callers messing with the returned collection.

itowlson
+1 Nicely explained :)
Andrew Hare
+1 yes. Got it in one.
Jeremy McGee
Love the explanation
SoMoS