Generic Lists are All You Will Ever Need

Generic lists have reduced the amount of code we have to write for our n-tier applications dramatically. Where they have been most uselful is in the definition of our Strongly Typed Object Collections.

Previously we would have created a class that inherited from CollectionBase and then implemented all of the usual functionality.

An example is shown below :-

[Serializable]
public class AddressCollection:CollectionBase
    {
        public Address this[int index]
        {
            get {return ((Address)List[index]);}
            set {List[index] = value;}
        }

        public int Add(Address value) 
        {
            return (List.Add(value));
        }
    
        public int IndexOf(Address value)
        {
            return (List.IndexOf(value));
        }
    
        public void Insert (int index, Address value)
        {
            List.Insert(index, value);
        }

        public void Remove(Address value)
        {
            List.Remove(value);
        }

    
        public bool Contains (Address value)
        {
                return (List.Contains(value));
        }

        protected override void OnInsert(int index, object value)
        {
            if (value.GetType() != Type.GetType("Entities.Address"))
                throw new ArgumentException("value must be of type Address""value");
        }

        protected override void OnRemove(int index, object value)
        {
            if(value.GetType() != Type.GetType("Entities.Address"))
                throw new ArgumentException("value must be of type Address.""value");
        }

        protected override void OnSet(int index, object oldValue, object newValue)
        {
            if(newValue.GetType() != Type.GetType("Entities.Address"))
                throw new ArgumentException("newValue must be of type Address.""newValue");
        }

        protected override void OnValidate(object value)
        {
            if(value.GetType() != Type.GetType("Entities.Address"))
                throw new ArgumentException("value must be of type Address.");
        }

But now this has all been replaced with

 List<Entities.Address> AddressCollection = new List<Entities.AddressCollection>();

As you can see a massive code reduction with no loss of functionality, making it simplier to use and easier to maintain.

Author Greg Duffield

Greg has too many years experience in developement from VB for DOS all the way through to Windows Workflow and LINQ while covering pretty much every technology in between. A complete MS evangelist he is now Director of the only MS Gold Partner IT services company in Norfolk. Wehere they are producing Web 2 Applications for various sectors, and are currently entering the Haulage industry with their latest product.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.