Creating a ValueTuple with a TypeBuilder element #111760
-
Let's say I have a class Element {} How can I use this type as the element type of a tuple? Let's just say, to make it simple, I want to build something semantically equivalent to this using ValueTuple<Element> item = new(null);
class Element {} The below code is supposed to achieve this, but the code fails on line 18 with a using System;
using System.Reflection;
using System.Reflection.Emit;
PersistedAssemblyBuilder ab = new(new("Test"), typeof(object).Assembly);
ModuleBuilder mb = ab.DefineDynamicModule("Test.dll");
TypeBuilder elementType = mb.DefineType("Element");
elementType.CreateType();
TypeBuilder tb = mb.DefineType("Program");
MethodBuilder methb = tb.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);
methb.SetReturnType(typeof(void));
ILGenerator il = methb.GetILGenerator();
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Newobj, typeof(ValueTuple<>).MakeGenericType(elementType).GetConstructor([])); // EXCEPTION
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ret);
tb.CreateType();
ab.Save("Test.dll"); I was expecting this to be an issue only with the new .NET 9 version of Is there something wrong with my code or is there some workaround I need to do to achieve this? I would believe it if this was not yet supported on .NET 9 (since the implementation is still lacking quite a bit), but I think a use case as simple and common as this should be supported on .NET Framework. It's also very much possible I am overseeing something. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It's mentioned in documentation: https://learn.microsoft.com/en-us/dotnet/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit
Although the scenario isn't exact the same with this issue ( var openCtor = typeof(ValueTuple<>).GetConstructor([typeof(ValueTuple<>).GetGenericArguments()[0]]);
var ctor = TypeBuilder.GetConstructor(typeof(ValueTuple<>).MakeGenericType(elementType), openCtor); Constructors for generics involving type builders should be retrieved from |
Beta Was this translation helpful? Give feedback.
It's mentioned in documentation: https://learn.microsoft.com/en-us/dotnet/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit
Although the scenario isn't exact the same with this issue (
TypeBuilderInstantiation
), the solution is the same: