MsCorEE

JeffGonzalez : IScalable

Anonymous methods, generics and bears...Oh my

I stumbled across an interesting conversation on Jeff's(I am not speaking in the third person, this Jeff) blog.  Like any other time, I have plenty to say on the matter....

Microsoft (via FxCop) suggests that you don't expose List<T> via public members.  I think the reasons I have heard mentioned in the past are around versioning your collections and the API for List<T> being too large for public APIs.

While I don't agree with Ramon's random "suggestions" about language fluency, I do think he makes a good point about losing the flexibility of generic types by making a class directly inherit from List<T>.  With the current example (I realize this may or may not be contrived), following that route would require you to create a collection class for each class in your project. 

I suppose you could do 1 of 2 things (if you were so inclined):

Create a generic type that inherits from list<T>, which is pretty close to what you have.  Only a slight modification need be made:

public class GenericList<T> : List<T>
{
}

Or you could create a generic type that implements List<T> as an inner list and expose only the stuff you need from List<T>. 

public class GenericList<T>
{
    private List<T> _innerList;

    public MyListTwo()
    {
        _innerList = new List<T>();
    }

    public void Add(T obj)
    {
        _innerList.Add(obj);
    }

    public T Find(Predicate<T> pred)
    {
        return _innerList.Find(pred);
    }
}
(This one has my vote).

Either of these would accomplish the same thing, but without the loss of flexibility.

As for the complexity of the anonymous methods, I don't think it is bad looking at all for very simple things, most of the time you are just wanting to get an item or a series of items based on a particular property.  I do think for complex things, you should go ahead and make a method that encapsulates all of the logic for the particular predicate.

Comments

Udi Dahan - The Software Simplist said:

The idea is to expose such members as IList<T>.

# March 25, 2007 11:27 PM

likwid said:

What does using an interface there buy me?  It is easier to version a base class than it is an interface in my opinion.

You can hide certain implementation details in a base class and tweak them if necessary.  I understand it is necessary to use interfaces sometimes, even preferred in some cases.  I am just not sure it is such a hard and fast rule.

This is some information on not using generic lists:

http://blogs.msdn.com/fxcop/archive/2006/04/27/585476.aspx

# March 26, 2007 9:02 AM

Jeff said:

I wish I could find the link to that class library that does all kinds of things with generics to keep them, uh, generic.

# March 26, 2007 2:42 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)