I get the Type but that's not the same as the Class which is what I'm looking for.
Is there an inverse operation of typeof?
EDIT
I need the class in order to use a generic repository:
GenericRepository<BaseEntity> repository = new GenericRepository<BaseEntity>(new AzureBrightData());
I started by writing BaseEntity from which all entity class descend, but the problem is that the repository needs to know which table to search for.
For example, if we have a partition key and row key combination pair of (1,1) this doesn't allow me or the repository to know from which table to get the registry. It's not enough and that's why I believe I need the table.
I'll base my answer on the clarification you provided in a comment:
I misunderstood what everyone said here or at least I did not make myself clear. I want to get the class as I would use it normally. For example, I have to pass the class like this: public void methodName<T>()
where T
is the class.
Short answer: No, you can't, because generic types are resolved at compile time.
Long answer: Yes, you can, but you need to use reflection. Here's how you do that:
- StackOverflow: How to use reflection to call generic Method?
- StackOverflow: What's the best way to instantiate a generic from its name?
If i undestood answers under your question than maybe you are looking for something like this (instantiate Type):
Assembly asmApp = Assembly.LoadFile("some.dll");
Type tApp = asmApp.GetType("Namespace.SomeClass");
object oApp = Activator.CreateInstance(tApp, new object[0] { });
Use the "Activator" class:
Activator.CreateInstance<T>
I think you are looking for Activator.CreateInstance.
Use the new() constraint.
public T Create<T>() where T : new() {
return new T();
}
Here are a few options listed in order of my preference. I am assuming that T
is the type parameter in your generic class or method.
new T(); // T must be constrained to support a default constructor.
or
Activator.CreateInstance(typeof(T), new object[] { });
or
typeof(T).GetConstructor(new Type[] { }).Invoke(null);
or
AppDomain.CurrentDomain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);
I must be missing something. The answers provided so far don't seem to match the questions. I would love more clarity.
Nevertheless I'll try to answer the question as I see it.
You say you're trying to do this:
var repository = new GenericRepository<BaseEntity>(new AzureBrightData());
Are you trying to do something more like this?
var repository = new GenericRepository<AzureBrightData>();
If so, then your generic repository class needs to be defined as such:
public class GenericRepository<T> where T : BaseEntity, new()
{
...
}
Then you can define your BaseEntity
class as you have been, but the instantiation of your repository will give you the actual class - and I hope then the table - that you are looking for.
I hope I have understood your question.