I’m trying to get a generic interface with implentation for handling my xml:
IXmlService
List<T> Load<T>() where T : class;
XmlService
public List<T> Load<T>() where T : class {
Type type = typeof(T);
if (type == typeof(TicketData)) { return XmlTicketService.LoadInternal(); } // Error: Unable to cast from List<TicketData> to List<T>
And the XmlTicketService.LoadInternal() knows the type and should return to Service
internal static List<TicketData> LoadInternal() {
List<TicketData> result = new List<TicketData>();
ThreadPool.QueueUserWorkItem(
delegate {
try {
XDocument data = XDocument.Load(_xmlPath);
var query = (from element in data.Root.Descendants("Ticket")
select new TicketData() {
Hope u have and advices for me 🙂
Well, in this case you can just cast, going via
object:The
objectcast first basically forces the compiler to treat it as a “normal” cast.… but personally I think that raises a design smell, where you should probably be creating a generic interface with a non-generic method, and implementing
ILoadable<TicketData>or whatever. Basically your method isn’t really generic – it has specific handling for specific types, which should always make you question whether your design is really appropriate.