Using Generics

A while ago on StackOverflow I asked a question about what problems could be solved using generics. I had read a lot about generics and use Lists a lot but I personally for a good long while hadn’t used them.

Recently I started looking at http://valueinjecter.codeplex.com/ to use for DataMapping and ended up developing the following service to help me in my code. This is a fairly good use of generics I feel. What the service is doing is taking two objects: a target and a source. It then copies the values from the target into the source.

using System.Collections.Generic;
using Omu.ValueInjecter;

//Uses http://valueinjecter.codeplex.com/ to do the mapping

namespace MyVee24.Services {

    public interface IDataMappingService<T, K> where T : class
                                                                                  where K : new() {
         K Map(T storeDept);
         List<K> MapList(List<T> dataStoreDepts);
    }

    public class DataMappingService<T, K> : IDataMappingService<T, K> where T : class
                                                                                                                                   where K : new() {

        public K Map(T source) {
K target = new K();
target.InjectFrom(source);
return target;
}

        public List<K> MapList(List<T> sourceList) {
List<K> targetList = new List<K>();
foreach (T item in sourceList) {
targetList.Add(Map(item));
}

            return targetList;
        }
    }
}

I’m posting this as a handy reference, mainly for myself.

P.S: Apologies for the lousy formatting. I’ll try and find time to learn how to format code samples nicely in WordPress

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s