0

I'm not sure this is possible with reflection, but thought I'd ask. I'm using a data access class that relies on generics to determine the 'row type' which we're querying against.

A couple of examples will show what I mean better than anything:

int count1 = connection.Count<PersonRow>("i.FirstName ='David'");
int count2 = connection.Count<CarRow>("i.CarModel = 'Chevrolet'"); 

Both PersonRow and CarRow inherit from an abstract Row class.

As you can see, the type of Row we're querying against dictates what our query structure will be.

I'd like to store a bunch of these queries as strings in a database or configuration file, rather than hard-code them. That way we can let users write their own queries as they like, and the code loops over the configuration and runs them one at a time.

Trouble is, I don't know if I can pull this off given the Generic requirement above?

I'd love for the configuration to store the kind of row (as a string) along with a string for the query itself, then use reflection to supply the row class in the Count<> method.

I've been playing with Type.GetType() and Type.MakeGenericType() to see if I can finagle something, but am having no luck.

While looking around, I've seen several articles like this that show how to instantiate a generic class using reflection, but I need the class type, not an actual object. Is there a way to pull this off?

Community
  • 1
  • 1
jkj2000
  • 1,563
  • 4
  • 19
  • 26
  • Please clarify what 'connection' is. Is it a List? Also, can I assume FirstName is a member of PersonRow and CarModel is a member of CarRow and Row has not members relevant to this question? – markshancock Mar 27 '17 at 04:26
  • @markshancock your assumptions are correct regarding FirstName and CarModel. 'connection' is a database access class mentioned at the start, considerably more complicated than a List of Rows. – jkj2000 Mar 27 '17 at 04:48
  • Is connection derived off of IEnumerable? – markshancock Mar 27 '17 at 16:20
  • If it is derived off IEnumerable, consider using Linq. – markshancock Mar 27 '17 at 16:55

0 Answers0