Assigning Generic Type during runtime
-
In the code I am working with i have a class called RecordHistoryService<x,y> X, and Y are unknown at design time and known at runtime i need to instantiate RecordHistoryService<x,y>, is there any way to do it? I have this, but it doesnt compile: i.e.
Type _rhType = Type.GetType(rhType);
Type _entityType = Type.GetType(entityType);
RecordHistoryService<_rhType, _entityType> recordHistory;thx for your help :D
-
In the code I am working with i have a class called RecordHistoryService<x,y> X, and Y are unknown at design time and known at runtime i need to instantiate RecordHistoryService<x,y>, is there any way to do it? I have this, but it doesnt compile: i.e.
Type _rhType = Type.GetType(rhType);
Type _entityType = Type.GetType(entityType);
RecordHistoryService<_rhType, _entityType> recordHistory;thx for your help :D
Look into reflection.
The best way to accelerate a Macintosh is at 9.8m/sec² - Marcus Dolengo
-
Look into reflection.
The best way to accelerate a Macintosh is at 9.8m/sec² - Marcus Dolengo
-
In the code I am working with i have a class called RecordHistoryService<x,y> X, and Y are unknown at design time and known at runtime i need to instantiate RecordHistoryService<x,y>, is there any way to do it? I have this, but it doesnt compile: i.e.
Type _rhType = Type.GetType(rhType);
Type _entityType = Type.GetType(entityType);
RecordHistoryService<_rhType, _entityType> recordHistory;thx for your help :D
If the types are not totally random, you could use some kind of factory method to instantiate it...if totally random, I think the easiest way is to use reflection, or something like this article
Intelligence is almost useless for those who have nothing else! Email: caiokf@gmail.com
-
It is the only way I can think of doing it. It is kind of expensive but not too horrible, one alternative(and I say that for lack of better word) is to make a bunch of methods that are specific to the type being passed, although I would NEVER do this, it is horrible practice. My suggestion is reflection, although kind of expensive, it won't be bad unless doing this many times very fast.
The best way to accelerate a Macintosh is at 9.8m/sec² - Marcus Dolengo
-
In the code I am working with i have a class called RecordHistoryService<x,y> X, and Y are unknown at design time and known at runtime i need to instantiate RecordHistoryService<x,y>, is there any way to do it? I have this, but it doesnt compile: i.e.
Type _rhType = Type.GetType(rhType);
Type _entityType = Type.GetType(entityType);
RecordHistoryService<_rhType, _entityType> recordHistory;thx for your help :D
You'd be looking at Type.MakeGenericType(...) off the top of my head.
Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
Alpha release: Entanglar: Transparant multiplayer framework for .Net games.