4

Short version

Is there a more reliable or elegant way in C# to get to generic type parameters of some base class than in How to get base class's generic type parameter? , especially if you don't know how deep your inheritance chain is?

Sure, you could implement a generic method, and simply return typeof() of the generic parameter capture, which is nearly what I want (see below). Can you do something like this in a more static way (without needing an instance)? (The post mentioned above doesn't cover this approach at all, which is why I am asking this "again")

Longish version

I have a OO constellation, as is typical for a Proxy Pattern:

class PersonDataAccess : DataAccess<Person, MyContext, ...> { }

interface IPersonDataAccess { }

class PersonDataAccessProxy : IPersonDataAccess { }

where the base class for the PersonDataAccess would have the following signature:

abstract class DataAccess<TEntity, TContext, ...> {  }

I am keeping this rather unspecific, since there may be simply more than one generic type argument. Lastly, of course, there is

class Person { }

which is some sort of entity or domain.

The Interface would have the public members of the DataAccess, while the Proxy would encapsulate the DataAccess, and implement the interface by delegation to the DataAccess. Basically exactly as in the first picture of http://en.wikipedia.org/wiki/Proxy_pattern

For the most part I can automatically generate my interfaces and proxies. So I'll get all types inheriting from DataAccess, get their public members and generate an interface and proxy implementation from that.

To the problem:

Now, sometimes I need the type parameter of DataAccess while iterating through the the DataAccesses. So if I have the System.Type-Object of my PersonDataAccess, what I would like to get is Person.

I am aware of this: How to get base class's generic type parameter?

But this seems rather dangerous and unreliable, especially since it would crash if PersonDataAccess would not directly inherit from DataAccess (which is what I sometimes have). What I would rather have, is code like this:

Type GetEntityType<TValue, TContext, ...>(DataAccess<TEntity, TContext, ...> dataAccess)
{
    return typeof(TEntity);
}

The problem with that is, I would need an instance of my DataAccess, which is rather problematic since this code needs to run during code generation, and not during runtime.

So, is there any better way than reflecting through the inheritance chain, until you find your desired base type and hope that the first generic type parameter is the one you want?

Community
  • 1
  • 1
Oliver Schimmer
  • 387
  • 2
  • 14

0 Answers0