I have a weird problem. :(
I get an enumerable object from my database and want to convert the objects either to a list of base class objects or to a list of fully blown derived class objects . In some situations I want to cut of attributes I do not need - so standard polymorphism is not the way for me. This function resides in an web service and I have to optimize traffic.
Therefore I wrote a generic function for casting the whole list to the type I want. But in the case of the derived type I get an cast error. But I don't understand the message because the source object has not the type, the message is telling me.
Any ideas what is going wrong? Thx in advance!
using System;
using System.Collections.Generic;
using System.Linq;
class DBClass {
public string id { get; set; }
public string name { get; set; }
public DBClass() { id = Guid.NewGuid().ToString(); }
}
class BaseClass {
public Guid ID { get; set; }
public static explicit operator BaseClass(DBClass x) {
return new BaseClass() {
ID = new Guid(x.id)
};
}
}
class DerivedClass : BaseClass {
public string Name { get; set; }
public static explicit operator DerivedClass(DBClass x) {
return new DerivedClass() {
ID = new Guid(x.id),
Name = x.name
};
}
}
class Program
{
static List<BaseClass> convertToList<T>(IEnumerable<DBClass> xx) where T : BaseClass
{
// solution from Jeroen Mostert (see comments):
return xx.Select(obj => (BaseClass) (T) (dynamic) obj).ToList();
// original code with error
var l = xx.Select( obj => (T) obj);
// T == BaseClass: everything is fine
// T == DerivedClass: Unable to cast object of type 'BaseClass' to type 'DerivedClass'.
// but obj is of type DBClass!
return l.ToList() as List<BaseClass>;
}
static void Main(string[] args)
{
List < DBClass > dbValues = new List<DBClass>();
dbValues.Add(new DBClass());
dbValues.Add(new DBClass());
dbValues.Add(new DBClass());
convertToList<BaseClass>(dbValues); // ok
convertToList<DerivedClass>(dbValues); // KO
}
}