[.net] Generics Problem

Started by
11 comments, last by smitty1276 15 years, 4 months ago
To the dude that compiled to instaciate a class: it is not only ineffective, but inappropriate. Reflection is about this exactly: to give you true flexibility. It is quite slow, because it parses heavily the metadata stored in the assembly, but definitely faster than compilation. Hell, you think Visual Studio compiles every time you press ctrl+space? Or is entirely parser-based state machine? If it were, .NET code completion would suck as much as native C++ code completion!

I will quick-guide you how to do it without compilation.

First, you need to load the assembly metadata into memory, so you issue
Assembly myAssembly = Assembly.Load()

Look up different overrides and needed namespace usings on MSDN

Then, you get all types in the assembly with (and filter them with Linq)
Type[] allTypes = myAssembly.GetTypes();

Or get the type of a specific class
Type myClassType = myAssembly.GetType("Full.Class.Name");

Create a list of parameters to pass to the constructor:
object myClassConstructorParams = new object[] {"param1", 2};

And finally initialize it:
object myClassInstance = Activator.CreateInstance(myClassType, myClassConstructorParams);


Then you can use it just as a regular class instance:
MyClass instance = myClassInstance as MyClass;


Hope this helps.

[Edited by - dilyan_rusev on December 11, 2008 6:10:43 PM]
Advertisement
At this point there is no point in using generics. You may as well use an array list and do type casting as use List<object>. It is the cheapest option and only reasonable option if you want a heterogeneous collection in C#.

If C# had algebraic types you could do this with static typing with the appropriate packing and unpacking functions via pattern matching. if you knew every possible type of what may belong.
If you are going to treat them non-generically, there is no reason to use generics. Also, I found this to be pretty strange in your sample:

// class A;
// class B;
B b = (B)someInstanceOfA;

What's the point of even having a derived class B if you are assuming that *ALL* instances of class A are also class B?



This topic is closed to new replies.

Advertisement