I have a linq query that is currently doing an object instantiation based on a generic type parameter. I actually need to instantiate a more specific subclass of the generic parameter. Is there a way to do the instantiation with a derived type? I’m open to using reflection or even direct IL emit if necessary, though I’d like to try and keep type checking on the base class’s properties if possible.
So the code I have is like this:
IQueryable<TType> myObjects = from blah in blahblah
select new TType
{
PropertyA = someValue;
PropertyB = someOtherValue;
}
But I need the objects in the IQueryable to actually be a derived class from TType. I don’t know in advance which derived class they will be, just that they will all be the same derived type based on some other logic.
Sounds like you need a Factory pattern:
The
BaseTypeFactorywould then do whatever it needs to do to spit out the correct derivedBaseTypeinstances.If (as your comments say)
TTypeis constrained to a particular base type, the Factory could look something like:(assuming
TTypeis constrained bywhere TType : BaseType)