Whats is the difference between:
List<MyType> myList;
and
myList : List<MyType>
Its obvious that the first one is list and second one is a class. But my question is what's the advantage of second over first one.
The latter gives you the ability to have a function which takes a myList, instead of just a List. This also means that if the type of myList changes (perhaps to a sorted list) you don't have to change your code anywhere. So instead of declaring List<myType> everwhere, and then having to change them, if you had MyList objects everywhere, you're golden.
Its also a syntactic difference. Does myList have a list, or is it a list?
I would lean towards having a MyList : List<MyType> if it is used commonly throughout your program.
List<MyType> myList is an instance of the generic type List that can contain items that are of MyType (or of any types derived from MyType)
var myTypeInstance = new MyType();
var myList = new List<MyType>;
myList.Add(myTypeInstance);
myList : List<MyType> is a new type that inherits from List from which you can then make multiple instances:
var myTypeInstance = new MyType();
var myCollectionVariable = new myList();
myCollectionVariable.Add(myTypeInstance);
The main advantage of the latter over the former is if you wanted to have some methods that act on a List you can put them on your class, rather than storing them in a "helper" or "utility" library, for example:
class myList : List<MyType>
{
public void DoSomethingToAllMyTypesInList()
{
...
...
}
}
Object composition link text
vs.
Class inheritance link text
The latter is a new class that inherits from the base, but is distinct. The most obvious distinction is that it doesn't have the same constructors, but you'll also run into problems streaming it.
Those are the disadvantages. The advantage is that you could add some of your own methods. Even then, I'd consider using containment, with has-a relationship instead of is-a.
I would prefer not to inherit implementation where possible. It has its uses, but if it's not entirely necessary, then it's not worth it.
The major answer to your question is that by inheriting List<T>, you make all its methods public by default. Usually when writing a new class, you want encapsulation. You don't want to let the internals leak out. For example, suppose you wanted to make a thread-safe container. If you inherit from a thread-ignorant container, your clients will be able to use the public interface of the base class to bypass any locking you try to put in.
Another popular mistake comes when you find yourself using a particular container type a lot, it's tempting to try and use inheritance to make a short name for it:
class ShortName : Dictionary<string, List<string>> { };
But that's not what you've done - you've created a completely new type. This means that if you have some other library that can produce the right data structure, it won't be directly usable by your code; you'll have to copy it into a ShortName first. An example is Linq, which can easily build a Dictionary<string, List<string>> from a very readable, functional expression, ending with ToDictionary.
So instead, do this:
using ShortName = Dictionary<string, List<string>>;
Now you have a short snappy alias for the unweildy typename, but you're actually still using the same type.
The Microsoft design guidelines (FxCop and VS Code Analysis) don't recommend inheriting publicly-visible classes from List<T>. Instead you can inherit from Collection<T> as described in this blog post.
These guidelines aren't necessarily relevant for private assemblies or internal classes though.
A couple of reasons why you might want to inherit from Collection<T> or List<T> are:
So you can add custom application-specific members to your collection class.
So you can create a ComVisible collection class (you can't expose a generic List directly to COM, but you can expose a derived class).
By the way the naming guidelines would also recommend you name your derived class with the "Collection" suffix, i.e.
MyTypeCollection : List<MyType> // or : Collection<MyType>, IList<MyType>
rather than
MyList : List<MyType> // or : Collection<MyType>, IList<MyType>
Some people find benefits in abstracting data structures away from their application logic. If you decide that generic list is no longer the best data structure to represent MyList you can change your MyList implementation, and as long as your interface is the same, you don't have to update any other code.
This is over kill in many situations however.
There are also semantic benefits to working with an abstracted data type rather than the original, though the list type blurs the line. It is more obvious when working with a dictionary data structure. If you wrap the dictionary in a custom collection type, and expose keys and values as properties. you can write code that reads more like the business logic you are implementing.
Related
I have a hash table which can contain any number of objects. All of these objects implement some similar methods / properties and some of their own.
For example all objects in the hashtable may have a method called PrintText taking a single parameter of type string. All the objects are however instantiated from different classes.
Is it possible for me to pull out a particular object from the hashtable by its key without knowing its type before runtime, and access all its own methods and properties (not just the common ones)?
Normally I would do something like,
MyClass TheObject = MyHashTable[Key];
But the object being pulled out could be derived from any class so I cannot do that in this instance.
You could define an interface containing the common methods and properties, and implement this interface in all your classes. Then you can easily access these methods and properties.
But to access the specific methods of an object (not contained in the interface), you will need to know the type of the object.
Update:
It's not clear from your question, but when you write about a hashtable, I assume you mean the Hashtable class. In that case, you should have a look at the generic Dictionary class (available since .NET 2.0). This class will make your code typesafe and saves you from a lot of type-casting, e.g:
IMyInterface a = new MyObject();
// with Hashtable
Hashtable ht = new Hashtable();
ht.Add("key", a);
IMyInterface b = (IMyInterface)ht["key"];
// with Dictionary
var dic = new Dictionary<string, IMyInterface>();
dic.Add("key", a);
// no cast required, value objects are of type IMyInterface :
IMyInterface c = dic["key"];
To solve problems with common methods and properties you can solve by making your classes to implement the same interface. However, I don't see how you can access non-common members. You can try to use Reflection.
dynamic in C# 4. Reflection in earlier versions.
EDIT: In some cases, defining a common interface can be both an efficient and clear way of achieving something of the nature you describe. ('inspired' by the accepted answer and/or others mentioning it - can't remember the timeline)
You can say:
object theObject = MyHashTable[Key];
Then you can say:
theObject.GetType()
.GetMethod("PrintText")
.Invoke(theObject, new object[] {"paramvalue"});
This question already has answers here:
In C#, why can't a List<string> object be stored in a List<object> variable
(14 answers)
Closed 8 years ago.
I understand that, if S is a child class of T, then a List<S> is not a child of List<T>. Fine. But interfaces have a different paradigm: if Foo implements IFoo, then why is a List<Foo> not (an example of) a List<IFoo>?
As there can be no actual class IFoo, does this mean that I would always have to cast each element of the list when exposing a List<IFoo>? Or is this simply bad design and I have to define my own collection class ListOfIFoos to be able to work with them? Neither seem reasonable to me...
What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my List<Foo> internally as a List<IFoo>.
Your List<Foo> is not a subclass if List<IFoo> because you cannot store an MyOwnFoo object in it, which also happens to be an IFoo implementation. (Liskov substitution principle)
The idea of storing a List<IFoo> instead of a dedicated List<Foo> is OK. If you need casting the list's contents to it's implementation type, this probably means your interface is not appropriate.
Here's an example of why you can't do it:
// Suppose we could do this...
public List<IDisposable> GetDisposables()
{
return new List<MemoryStream>();
}
// Then we could do this
List<IDisposable> disposables = GetDisposables();
disposables.Add(new Form());
At that point a list which was created to hold MemoryStreams now has a Form in it. Bad!
So basically, this restriction is present to maintain type safety. In C# 4 and .NET 4.0 there will be limited support for this (it's called variance) but it still won't support this particular scenario, for exactly the reasons given above.
In your returning function, you have to make the list a list of interfaces, and when you create the object, make it as an object that implements it. Like this:
function List<IFoo> getList()
{
List<IFoo> r = new List<IFoo>();
for(int i=0;i<100;i++)
r.Add(new Foo(i+15));
return r;
}
MASSIVE EDIT
You'll be able to do it with C# 4.0, but [thanks Jon]
You can get around it using ConvertAll:
public List<IFoo> IFoos()
{
var x = new List<Foo>(); //Foo implements IFoo
/* .. */
return x.ConvertAll<IFoo>(f => f); //thanks Marc
}
The simple answer is that List<Foo> is a different type to List<IFoo>, in the same way that DateTime is different to IPAddress, for example.
However, the fact that you have IFoo implies that collections of IFoo are expected to contain at least two implementations of IFoo (FooA, FooB, etc...) because if you expect there to only ever be one implementation of IFoo, Foo, then the IFoo type is redundant.
So, if there is only ever going to be one derived type of an interface, forget the interface and save on the overhead. If there are two or more derived types of an interface then always use the interface type in collections/generic parameters.
If you find yourself writing thunking code then there's probably a design flaw somewhere.
If, at the time that IList<T> was invented, Microsft had been aware that future versions of .net would support interface covariance and contravariance, it would have been possible and useful to split the interface into IReadableList<out T>, IAppendable<in T>, and IList<T> which would inherit both of the above. Doing so would have imposed a small amount of additional work on vb.net implementers (they would have to define both read-only and read-write versions of the indexed property, since for some reason .net doesn't allow a read-write property to do serve as a read-only property) but would mean that methods which simply need to read items from a list could receive an IReadableList<T> in covariant fashion, and methods which simply need a collection they can append to could receive an IAppendable<T> in contravariant fashion.
Unfortunately, the only way such a thing could be implemented today would be if Microsoft provided a means for new interfaces be substitutable for older ones, with implementations of the old interfaces automatically using default methods supplied by the new ones. I would think such a feature (interface substitutability) would be extremely helpful, but I wouldn't hold my breath waiting for Microsoft to implement it.
Given that there's no way to back-fit IReadableList<T> into IList<T>, an alternative approach would be to define one's own list-related interface. The one difficulty with doing so is that all instances of System.Collections.Generic.List<T> would have to be replaced with some other type, though the difficulty of doing that could be minimized if one were to define a List<T> struct in a different namespace which contained a single System.Collections.Generic.List<T> field and defined widening conversions to and from the system type (using a struct rather than a class would mean that code would avoid the need to create new heap objects when casting in any scenario where the struct wouldn't have to be boxed).
Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity:
public class Cars : List<aCar>
instead of something like:
public class Cars
{
List<aCar> CarList = new List<aCar>();
}
Any thoughts?
The problem with this is that your Cars class will still have the interface it inherits from List, which may allow operations you don't want.
That depends on the final purpose of your class. If it is only going to work as your own implementation of a collection use inheritance. If not, include a a collection as a property. The second option is more versatile:
As you can only inherit from one class, you might need to inherit from another class rather than collection
If you need to see this class as a collection you can include an indexer property.
I misread the question previously.
I would suggest using composition instead of inheritance. If you want to be able to use all the funky LINQ stuff, by all means implement IEnumerable<T> and perhaps even IList<T> - but I wouldn't derive from List<T> directly.
If you do want to get the collection stuff "for free" but still retain control, you could use CollectionBase. That still ties you down in terms of your one shot at inheritance, but at least you get more control over what happens in the collection.
If you want your Cars class to act just like a List and to have the same methods than it isn't that bad. You just derive from it and you're done. Then if you want to add any additional functionality, you can just declare those methods and you're done. However, you're now bound to List and if List changes in any undesirable ways, you're screwed.
When you make it a composite class instead and have the List instantiated inside the class then you only need tp expose the methods of List that you want exposed. But that means that you have to repeat them all too.
If the purpose of the class is to add additional functionality to a standard collection, then I would inherit from the collection. If the collection is just one part of a bigger picture, then that sounds more like a property.
I would, however, consider using Collection<T> instead of List<T> unless you really need the functionality in List<T>.
Is the "Cars" class really required?
Has some added functionality than "List" ? If not, you should use "List" ( or better "IList" ).
If class "Cars" has any added functionality, there is two main scenarios:
This class is "final" class, there is no big possibility, the someone others need extended it. Then is this construction OK.
This class will be probably used as base class. Then I recommend use this construction:
.
public class CarList<T> : List<T> where T : Car {
// some added functionality
}
If you want be more flexible in future, you should use a composition:
public class CarList<T> : IList<T> where T : Car {
private IList<T> innerList;
public CarList() { this.innerList = new List<T>(); }
// implementation of IList<T>
// some added functionality
}
I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?
There are two rules I follow:
Accept the most basic type that will work
Return the richest type your user will need
So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.
On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.
Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.
Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:
public interface IMyApi
{
IList<int> GetReadOnlyValues();
}
public class MyApiImplementation : IMyApi
{
public IList<int> GetReadOnlyValues()
{
List<int> myList = new List<int>();
... populate list
return myList.AsReadOnly();
}
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
public IList<int> GetReadOnlyValues()
{
IList<int> testValues = new int[] { 1, 2, 3 };
return testValues;
}
}
IEnumerable
You should try and use the least specific type that suits your purpose.
IEnumerable is less specific than IList.
You use IEnumerable when you want to loop through the items in a collection.
IList
IList implements IEnumerable.
You should use IList when you need access by index to your collection, add and delete elements, etc...
List
List implements IList.
There's an important thing that people always seem to overlook:
You can pass a plain array to something which accepts an IList<T> parameter, and then you can call IList.Add() and will receive a runtime exception:
Unhandled Exception: System.NotSupportedException: Collection was of a fixed size.
For example, consider the following code:
private void test(IList<int> list)
{
list.Add(1);
}
If you call that as follows, you will get a runtime exception:
int[] array = new int[0];
test(array);
This happens because using plain arrays with IList<T> violates the Liskov substitution principle.
For this reason, if you are calling IList<T>.Add() you may want to consider requiring a List<T> instead of an IList<T>.
I would agree with Lee's advice for taking parameters, but not returning.
If you specify your methods to return an interface that means you are free to change the exact implementation later on without the consuming method ever knowing. I thought I'd never need to change from a List<T> but had to later change to use a custom list library for the extra functionality it provided. Because I'd only returned an IList<T> none of the people that used the library had to change their code.
Of course that only need apply to methods that are externally visible (i.e. public methods). I personally use interfaces even in internal code, but as you are able to change all the code yourself if you make breaking changes it's not strictly necessary.
It's always best to use the lowest base type possible. This gives the implementer of your interface, or consumer of your method, the opportunity to use whatever they like behind the scenes.
For collections you should aim to use IEnumerable where possible. This gives the most flexibility but is not always suited.
If you're working within a single method (or even in a single class or assembly in some cases) and no one outside is going to see what you're doing, use the fullness of a List. But if you're interacting with outside code, like when you're returning a list from a method, then you only want to declare the interface without necessarily tying yourself to a specific implementation, especially if you have no control over who compiles against your code afterward. If you started with a concrete type and you decided to change to another one, even if it uses the same interface, you're going to break someone else's code unless you started off with an interface or abstract base type.
You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.
However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:
ArrayList.Adapter(list).Sort()
I don't think there are hard and fast rules for this type of thing, but I usually go by the guideline of using the lightest possible way until absolutely necessary.
For example, let's say you have a Person class and a Group class. A Group instance has many people, so a List here would make sense. When I declare the list object in Group I will use an IList<Person> and instantiate it as a List.
public class Group {
private IList<Person> people;
public Group() {
this.people = new List<Person>();
}
}
And, if you don't even need everything in IList you can always use IEnumerable too. With modern compilers and processors, I don't think there is really any speed difference, so this is more just a matter of style.
You should use the interface only if you need it, e.g., if your list is casted to an IList implementation other than List. This is true when, for example, you use NHibernate, which casts ILists into an NHibernate bag object when retrieving data.
If List is the only implementation that you will ever use for a certain collection, feel free to declare it as a concrete List implementation.
In situations I usually come across, I rarely use IList directly.
Usually I just use it as an argument to a method
void ProcessArrayData(IList almostAnyTypeOfArray)
{
// Do some stuff with the IList array
}
This will allow me to do generic processing on almost any array in the .NET framework, unless it uses IEnumerable and not IList, which happens sometimes.
It really comes down to the kind of functionality you need. I'd suggest using the List class in most cases. IList is best for when you need to make a custom array that could have some very specific rules that you'd like to encapsulate within a collection so you don't repeat yourself, but still want .NET to recognize it as a list.
A List object allows you to create a list, add things to it, remove it, update it, index into it and etc. List is used whenever you just want a generic list where you specify object type in it and that's it.
IList on the other hand is an Interface. Basically, if you want to create your own custom List, say a list class called BookList, then you can use the Interface to give you basic methods and structure to your new class. IList is for when you want to create your own, special sub-class that implements List.
Another difference is:
IList is an Interface and cannot be instantiated. List is a class and can be instantiated. It means:
IList<string> list1 = new IList<string>(); // this is wrong, and won't compile
IList<string> list2 = new List<string>(); // this will compile
List<string> list3 = new List<string>(); // this will compile
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable
IE:
public class CollectionBase : IEnumerable
and then would derive their Business Object collections from that.
public class BusinessObjectCollection : CollectionBase
Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:
public class BusinessObjectCollection : List<BusinessObject>
I do this because I like to have strongly typed names instead of just passing Lists around.
What is your approach?
I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time.
However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes.
Basically, C# 3.0 allows any class that implements IEnumerable and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax:
var d = new Dictionary<string, int>
{
{"hello", 0},
{"the answer to life the universe and everything is:", 42}
};
The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection:
class c1 : IEnumerable
{
void Add(int x1, int x2, int x3)
{
//...
}
//...
}
it would be possible to initialize it like so:
var x = new c1
{
{1,2,3},
{4,5,6}
}
This can be really useful if you need to create static tables of complex objects. For example, if you were just using List<Customer> and you wanted to create a static list of customer objects you would have to create it like so:
var x = new List<Customer>
{
new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"),
new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"),
new Customer("Michael Scott", "555-555-8769", "Scranton PA"),
new Customer("Ali G", "", "Staines", "UK")
}
However, if you use a customized collection, like this one:
class CustomerList : List<Customer>
{
public void Add(string name, string phoneNumber, string city, string stateOrCountry)
{
Add(new Customer(name, phoneNumber, city, stateOrCounter));
}
}
You could then initialize the collection using this syntax:
var customers = new CustomerList
{
{"Scott Wisniewski", "555-555-5555", "Seattle", "WA"},
{"John Doe", "555-555-1234", "Los Angeles", "CA"},
{"Michael Scott", "555-555-8769", "Scranton PA"},
{"Ali G", "", "Staines", "UK"}
}
This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex.
That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database.
My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List<T> directly.
It's recommended that in public API's not to use List<T>, but to use Collection<T>
If you are inheriting from it though, you should be fine, afaik.
I prefer just to use List<BusinessObject>. Typedefing it just adds unnecessary boilerplate to the code. List<BusinessObject> is a specific type, it's not just any List object, so it's still strongly typed.
More importantly, declaring something List<BusinessObject> makes it easier for everyone reading the code to tell what types they are dealing with, they don't have to search through to figure out what a BusinessObjectCollection is and then remember that it's just a list. By typedefing, you'll have to require a consistent (re)naming convention that everyone has to follow in order for it to make sense.
Use the type List<BusinessObject> where you have to declare a list of them. However,
where you return a list of BusinessObject, consider returning IEnumerable<T>, IList<T> or ReadOnlyCollection<T> - i.e. return the weakest possible contract that satisfies the client.
Where you want to "add custom code" to a list, code extension methods on the list type. Again, attach these methods to the weakest possible contract, e.g.
public static int SomeCount(this IEnumerable<BusinessObject> someList)
Of course, you can't and shouldn't add state with extension methods, so if you need to add a new property and a field behind it, use a subclass or better, a wrapper class to store this.
I've been going back and forth on 2 options:
public class BusinessObjectCollection : List<BusinessObject> {}
or methods that just do the following:
public IEnumerable<BusinessObject> GetBusinessObjects();
The benefits of the first approach is that you can change the underlying data store without having to mess with method signatures. Unfortunately if you inherit from a collection type that removes a method from the previous implementation, then you'll have to deal with those situations throughout your code.
You should probably avoid creating your own collection for that purpose. It's pretty common to want to change the type of data structure a few times during refactorings or when adding new features. With your approach, you would wind up with a separate class for BusinessObjectList, BusinessObjectDictionary, BusinessObjectTree, etc.
I don't really see any value in creating this class just because the classname is more readable. Yeah, the angle bracket syntax is kind of ugly, but it's standard in C++, C# and Java, so even if you don't write code that uses it you're going to run into it all the time.
I generally only derive my own collection classes if I need to "add value". Like, if the collection itself needed to have some "metadata" properties tagging along with it.
I do the exact same thing as you Jonathan... just inherit from List<T>. You get the best of both worlds. But I generally only do it when there is some value to add, like adding a LoadAll() method or whatever.
You can use both. For laziness - I mean productivity - List is a very useful class, it's also "comprehensive" and frankly full of YANGNI members. Coupled with the sensible argument / recommendation put forward by the MSDN article already linked about exposing List as a public member, I prefer the "third" way:
Personally I use the decorator pattern to expose only what I need from List i.e:
public OrderItemCollection : IEnumerable<OrderItem>
{
private readonly List<OrderItem> _orderItems = new List<OrderItem>();
void Add(OrderItem item)
{
_orderItems.Add(item)
}
//implement only the list members, which are required from your domain.
//ie. sum items, calculate weight etc...
private IEnumerator<string> Enumerator() {
return _orderItems.GetEnumerator();
}
public IEnumerator<string> GetEnumerator() {
return Enumerator();
}
}
Further still I'd probably abstract OrderItemCollection into IOrderItemCollection so I can swap my implementation of IOrderItemCollection over in the future in (I may prefer to use a different inner enumerable object such as Collection or more likley for perf use a Key Value Pair collection or Set.
I use generic lists for almost all scenarios. The only time that I would consider using a derived collection anymore is if I add collection specific members. However, the advent of LINQ has lessened the need for even that.
6 of 1, half dozen of another
Either way its the same thing. I only do it when I have reason to add custom code into the BusinessObjectCollection.
With out it having load methods return a list allows me to write more code in a common generic class and have it just work. Such as a Load method.
As someone else pointed out, it is recommended not to expose List publicly, and FxCop will whinge if you do so. This includes inheriting from List as in:
public MyTypeCollection : List<MyType>
In most cases public APIs will expose IList (or ICollection or IEnumerable) as appropriate.
In cases where you want your own custom collection, you can keep FxCop quiet by inheriting from Collection instead of List.
If you choose to create your own collection class you should check out the types in System.Collections.ObjectModel Namespace.
The namespace defines base classes thare are ment to make it easier for implementers to create a custom collections.
I tend to do it with my own collection if I want to shield the access to the actual list. When you are writing business objects, chance is that you need a hook to know if your object is being added/removed, in such sense I think BOCollection is better idea. Of coz if that is not required, List is more lightweight. Also you might want to check using IList to provide additional abstraction interface if you need some kind of proxying (e.g. a fake collection triggers lazy load from database)
But... why not consider Castle ActiveRecord or any other mature ORM framework? :)
At the most of the time I simply go with the List way, as it gives me all the functionality I need at the 90% of the time, and when something 'extra' is needed, I inherit from it, and code that extra bit.
I would do this:
using BusinessObjectCollection = List<BusinessObject>;
This just creates an alias rather than a completely new type. I prefer it to using List<BusinessObject> directly because it leaves me free to change the underlying structure of the collection at some point in the future without changing code that uses it (as long as I provide the same properties and methods).
try out this:
System.Collections.ObjectModel.Collection<BusinessObject>
it makes unnecessary to implement basic method like CollectionBase do
this is the way:
return arrays, accept IEnumerable<T>
=)