Problem with generics and dynamic class creation

A

andrew queisser

I've been trying to dynamically create a class DevT that's derived
from a generic base GenBase<T>. It doesn't seem to work. I'm attaching
a code sample below that illustrates the problem.

CreateType() fails when the base class is a parametrized class, as in
DevT : GenBase<int>.
CreateType() works if the base class is not parametrized, even if the
base of the base was parametrized, as in DevT : GenBaseInt :
GenBase<int>

The error dialog I'm getting is this:

An unhandled exception of type 'System.TypeLoadException' occurred in
mscorlib.dll

Additional information: Type name 'GenDerivBug.GenBase[[System.Int32,
mscorlib, Version=1.2.3400.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]]' from assembly 'GenDerivBug,
Version=1.0.1419.18373, Culture=neutral, PublicKeyToken=null' is
invalid.

Can anyone tell me whether the code should work and it's just a
problem with Whidbey?

Thanks much,
Andrew Queisser

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;

namespace GenDerivBug
{
// Generic base class with testing function
public class GenBase<T>
{
public virtual T foo(T t) { return t; }
}

// Non-generic class derived from constructed type
public class GenBaseInt : GenBase<int>
{
}

public class Test
{
public static void Main()
{
// create a dynamic assembly and module
AssemblyName asn = new AssemblyName();
asn.Name = "GenDynAssy";
AssemblyBuilder asb = Thread.GetDomain().DefineDynamicAssembly(asn,
AssemblyBuilderAccess.Run);
ModuleBuilder module;
module = asb.DefineDynamicModule("GenAlgoDynMod");

// create a class derived from the generic base
// this is what I want but it leads to CreateType() failing
TypeBuilder derivBuilder = module.DefineType("DevT",
TypeAttributes.Public, typeof(GenBase<int>));

// the following line makes CreateType work but it's not what I
want:
//TypeBuilder derivBuilder = module.DefineType("DevT",
TypeAttributes.Public, typeof(GenBaseInt));

// create a type and see if it works
Type derivType = derivBuilder.CreateType();
GenBase<int> gb =
(GenBase<int>)Activator.CreateInstance(derivType);
int i = 3;
int j = gb.foo(i+1);
Console.WriteLine("i={0} j={1}", i, j);
}
}
}
 
J

Joel Pobar [MSFT]

Hi,

The build of Whidbey you are using does not have Reflection.Emit support
for Generics. There are plans to add that support in a later build.

Thanks
-Joel.


Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top