473,769 Members | 7,646 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exposing Generic Lists

We have a class that has a public property that is of type List<T>. FXCop
generates a DoNotExposeGene ricLists error, indicating

"System.Collect ions.Generic.Li st<Tis a generic collection designed for
performance not inheritance and, therefore, does not contain any virtual
members. The following generic collections are designed for inheritance and
should be exposed instead of System.Collecti ons.Generic.Lis t<T>.

* System.Collecti ons.ObjectModel .Collection<T>
* System.Collecti ons.ObjectModel .ReadOnlyCollec tion<T>
* System.Collecti ons.ObjectModel .KeyedCollectio n<TKey, TItem"

Our property is not "virtual" and thus cannot be overridden. We used
List<Tbecasue we wanted a generic array. A collection is unordered and
thus not as good a match, even if it is better designed for inheritance.

Can anyone explain in more depth why having a non-virtual, List<tproperty
is bad? Why should I care is List<Thas any virtual members when I am
simply using an instance of and _not_ inheriting from List<T>?

Thanks,
--BJ
Feb 19 '07 #1
4 7568
We have a class that has a public property that is of type List<T>.
FXCop generates a DoNotExposeGene ricLists error, indicating

"System.Collect ions.Generic.Li st<Tis a generic collection designed
for performance not inheritance and, therefore, does not contain any
virtual members. The following generic collections are designed for
inheritance and should be exposed instead of
System.Collecti ons.Generic.Lis t<T>.

* System.Collecti ons.ObjectModel .Collection<T>
* System.Collecti ons.ObjectModel .ReadOnlyCollec tion<T>
* System.Collecti ons.ObjectModel .KeyedCollectio n<TKey, TItem"
Our property is not "virtual" and thus cannot be overridden. We used
List<Tbecasue we wanted a generic array. A collection is unordered
and thus not as good a match, even if it is better designed for
inheritance.

Can anyone explain in more depth why having a non-virtual, List<t>
property is bad? Why should I care is List<Thas any virtual members
when I am simply using an instance of and _not_ inheriting from
List<T>?
List<Tis intended to be a workhorse class used in implementation. By exposing
a List<Tin the interface of your class, you are breaking encapsulation
by giving client code access to an implementation detail of your class--especially
if your property provides direct access to the internal List<T>. For example,
this breaks encapsulation:

public class EmployeeCensus
{
private List<Employeem_ Employees;

public EmployeeCensus( IEnumerable<Emp loyeeemployees)
{
m_Employees = new List<Employee>( employees);
}

public List<EmployeeEm ployees { get { return m_Employees; } }
}

Any client code of the EmployeeCensus class could easily corrupt its state
by calling methods on the List<Employeeex posed by the Employees property.
And, if client code is responsible for maintaining the state of the EmployeeCensus
class, there's a design issue.

Proper encapsulation is to *not* expose the List<Tbut to expose a Collection<T>,
ReadOnlyCollect ion<Tor KeyedCollection <TKey, TItemlike this:

public class EmployeeCensus
{
private List<Employeem_ Employees;

public EmployeeCensus( IEnumerable<Emp loyeeemployees)
{
m_Employees = new List<Employee>( employees);
}

public ReadOnlyCollect ion<EmployeeEmp loyees { get { return m_Employees.AsR eadOnly();
} }
}

It's a shame that these classes were included in a different namespace (System.Collect ions.ObjectMode l)
because many developers haven't discovered them yet or realize that they
should be using them.

Best Regards,
Dustin Campbell
Developer Express Inc.
Feb 19 '07 #2


"BJ Safdie" <MS***********@ nospam.nospamwr ote in message
news:1D******** *************** ***********@mic rosoft.com...
We have a class that has a public property that is of type List<T>. FXCop
generates a DoNotExposeGene ricLists error, indicating

"System.Collect ions.Generic.Li st<Tis a generic collection designed for
performance not inheritance and, therefore, does not contain any virtual
members. The following generic collections are designed for inheritance
and
should be exposed instead of System.Collecti ons.Generic.Lis t<T>.

* System.Collecti ons.ObjectModel .Collection<T>
* System.Collecti ons.ObjectModel .ReadOnlyCollec tion<T>
* System.Collecti ons.ObjectModel .KeyedCollectio n<TKey, TItem"

Our property is not "virtual" and thus cannot be overridden. We used
List<Tbecasue we wanted a generic array. A collection is unordered and
thus not as good a match, even if it is better designed for inheritance.

Can anyone explain in more depth why having a non-virtual, List<t>
property
is bad? Why should I care is List<Thas any virtual members when I am
simply using an instance of and _not_ inheriting from List<T>?
List<Tis a particular concrete type, and as you rev your library you will
never be able to replace the return value with another type without breaking
your clients. The basic problem is that you are exposing too much internal
detail in the public contract of your class.

I would simply change the return value from List<Tto IList<T>.

David

Feb 19 '07 #3
Dustin,

This makes little sense to me. Are you really improving encapsulation by
exposing this list as a Collection<Tins tead of List<T>? I can buy the
arguement for a read only version, but we know that many things within the
framework (like databinding) would want to get to the AddNew() methods.

If you really want to hide the implementation, I would say an argument could
be made for declare your property as IList<T instead of the concrete
List<T>.

-Casey

"Dustin Campbell" wrote:
We have a class that has a public property that is of type List<T>.
FXCop generates a DoNotExposeGene ricLists error, indicating

"System.Collect ions.Generic.Li st<Tis a generic collection designed
for performance not inheritance and, therefore, does not contain any
virtual members. The following generic collections are designed for
inheritance and should be exposed instead of
System.Collecti ons.Generic.Lis t<T>.

* System.Collecti ons.ObjectModel .Collection<T>
* System.Collecti ons.ObjectModel .ReadOnlyCollec tion<T>
* System.Collecti ons.ObjectModel .KeyedCollectio n<TKey, TItem"
Our property is not "virtual" and thus cannot be overridden. We used
List<Tbecasue we wanted a generic array. A collection is unordered
and thus not as good a match, even if it is better designed for
inheritance.

Can anyone explain in more depth why having a non-virtual, List<t>
property is bad? Why should I care is List<Thas any virtual members
when I am simply using an instance of and _not_ inheriting from
List<T>?

List<Tis intended to be a workhorse class used in implementation. By exposing
a List<Tin the interface of your class, you are breaking encapsulation
by giving client code access to an implementation detail of your class--especially
if your property provides direct access to the internal List<T>. For example,
this breaks encapsulation:

public class EmployeeCensus
{
private List<Employeem_ Employees;

public EmployeeCensus( IEnumerable<Emp loyeeemployees)
{
m_Employees = new List<Employee>( employees);
}

public List<EmployeeEm ployees { get { return m_Employees; } }
}

Any client code of the EmployeeCensus class could easily corrupt its state
by calling methods on the List<Employeeex posed by the Employees property.
And, if client code is responsible for maintaining the state of the EmployeeCensus
class, there's a design issue.

Proper encapsulation is to *not* expose the List<Tbut to expose a Collection<T>,
ReadOnlyCollect ion<Tor KeyedCollection <TKey, TItemlike this:

public class EmployeeCensus
{
private List<Employeem_ Employees;

public EmployeeCensus( IEnumerable<Emp loyeeemployees)
{
m_Employees = new List<Employee>( employees);
}

public ReadOnlyCollect ion<EmployeeEmp loyees { get { return m_Employees.AsR eadOnly();
} }
}

It's a shame that these classes were included in a different namespace (System.Collect ions.ObjectMode l)
because many developers haven't discovered them yet or realize that they
should be using them.

Best Regards,
Dustin Campbell
Developer Express Inc.
Feb 19 '07 #4
This makes little sense to me. Are you really improving encapsulation
by exposing this list as a Collection<Tins tead of List<T>? I can
buy the arguement for a read only version, but we know that many
things within the framework (like databinding) would want to get to
the AddNew() methods.

If you really want to hide the implementation, I would say an argument
could be made for declare your property as IList<T instead of the
concrete List<T>.
Yes, you can improve encapsulation by exposing a Collection<T>. Collection<T>
is designed for inheritance. It provides virtual methods that can be overridden
to have complete control over what will happen when items are added and removed.
Because of that, it *can* be safe to expose. If there is a need to expose
a list-type data structure that a client can manipulate (e.g. add and remove
items from), a Collection<Tdes cendent is probably the way to go. Granted,
I think the need to do that is extremely rare so I would normally opt for
a ReadOnlyCollect ion<T>. Besides, there's methods on List<Tand Array to
produce a ReadOnlyCollect ion<Tso it's easy.

As for IList<T>, if you expose that, you are really only protecting one thing:
the type of data structure that you used internally. While it's true that
you could change the type of data structure that you are using later, you
have exposed an interface that allows clients to manipulate the state of
your class in a way that the class doesn't have any control over it. IList<T>
has Add and Remove methods that won't notify your class when called. So,
you're still breaking encapsulation by giving clients direct access to your
class's private parts. Just because you use an interface doesn't mean it's
OK.

Best Regards,
Dustin Campbell
Developer Express Inc.
Feb 20 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1353
by: tascien | last post by:
Hi guys, I have a class object I want to expose in a webservice class... How can I make sure that all objects including subclasses are exposed in WSDL. here is an example: Public Class Lists '< - class for all lists.. Public Class List ' <- class for a single list contained in Lists class... ' Member vars...
11
14518
by: ZenRhapsody | last post by:
Has anyone done any performance testing between new generic Lists and single dimensional arrays? I really like the code flexibility the List provides since I don't know how many items I will have in the list. With my array approach, I have to manage re-sizing the array myself. So, is using List<myClass> x as fast as MyClass x ?
2
1978
by: Greg Buchholz | last post by:
/* I've been experimenting with some generic/polytypic programs, and I've stumbled on to a problem that I can't quite figure out. In the program below, I'm trying to define a generic version of "transform" which works not only on lists, but lists of list, lists of lists of lists, etc. I'm calling it "fmap" and it passes around actual lists instead of iterators (for now). In order to get it to work, I thought I'd have one templated...
0
6854
by: Wiktor Zychla [C# MVP] | last post by:
We do have generic classes, methods and delegates. My question is: what reason prevents us from having generic properties and indexers? // impossible public List<T> GetList<T> { get { ... }
5
2939
by: Andrew Ducker | last post by:
I have something I'm trying to make work with generics, and it seems like it should, but I can't quite get there. I have a subclass of List<Tthat I want to populate automatically. Each different T is populated with a different set of data. Some sample code is given below - which clearly doesn't work, because you can't translate back and forth between the types. Can anyone tell me the right way to solve this kind of problem?
3
2261
by: Seth Gecko | last post by:
Hi I am working with generic lists of various objects and a control dealing with these lists. For instance: A parent form holds: dim Walls as List(Of wall) dim Segments as List(Of segment) The parent form have a custom control, which have a public sub looking
1
2785
by: Suds | last post by:
Hi, I'm having an issue with invoking a Generic method that takes Generic Arguments. My method signature is public void GenericMethodWithGenericArguments<E, V>(List<EtheFirstList, List<VtheSecondList); I pass the name of the method, the arguments for the "GenericMethodWithGenericArguments" to another method, which is supposed to invoke this method using the Invoke method in the MethodInfo class. My process of invocation is as follows
1
2844
by: Jeff | last post by:
..NET 2.0 Is generic lists faster then tradional lists when sending over a collection of objects (value by reference) in .NET remoting. Lets say if a list of object should be sent from a server to the client. Whould it be better to use generic lists? Jeff
0
1051
by: jappenzeller | last post by:
I've got a coding standard question for generic lists and .NET 2.0. I have created some custom strongly typed lists like, MyClassList:List<MyClass>. We did this because we wanted to reuse some helper methods that are at the list level, for instance, maybe we need to get some type of Average of MyClass's in the list so I have a method Average in the MyClassList class. One of the problems with this is if I use something like Find or FindAll...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10048
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3963
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.