So I came across a need to create a base class that accepted two generics one would be a concrete class and the other would be the interface to that class. The reason for the need to include both as generics is that I was delegating my concrete implementation to Windows Azure.
So, Azure will use my concrete class to store my data and I will retrieve it and pop it into my interface. A problem came up where I could not convert a list of one generic type (concrete) to another (interface).
However I have just discovered a way to convert between two generic lists. What this means is that I can tell azure about my concrete class and it will go ahead and persist my data to the cloud. At the same time I can also expose only the Interface of my concrete implementation to the rest of the system. This means that I can keep all of my instantiation safe and sound in factories where they belong, and also in Azure. :)
Anyway, If you want to Convert One Generic List to Another Generic List using c# then I hope the following code will give you somewhere to begin.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericListCastingTest
{
class GenericBoxClass<T, I> where T:I
{
private List<T> listT;
public IList<I> getSome() {
IList<I> list = listT.ConvertAll(x => (I)x);
return list;
}
public void setSome(List<T> value) {
this.listT = value;
}
}
}
If you want to play around with the source code for my tests on this code please check out http://compilr.com/IDE/32145








Leave a Comment