✅ Source Generator, dynamic assembly not added.

RRuttie12/25/2022
I have the following code:
            var assemblyName = new AssemblyName("MyAssembly");
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");

            var typeBuilder = moduleBuilder.DefineType("MyNamespace.MyType", TypeAttributes.Public);
            var methodBuilder = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public | MethodAttributes.Static);
            var ilGenerator = methodBuilder.GetILGenerator();

            // Generate some IL code
            ilGenerator.Emit(OpCodes.Ldstr, "Hello, world!");
            ilGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }));
            ilGenerator.Emit(OpCodes.Ret);

            typeBuilder.CreateTypeInfo();
            var sourceText = "namespace MyNamespace { public static class MyClass { public static void MyMethod() { MyType.MyMethod(); } } }";
            context.AddSource("MyFile.cs", sourceText);

When trying to compile a project that references the source generator, I get a CS0103, saying "The name 'MyType' does not exist in the current context".
Any ideas on how to fix?
RRuttie12/25/2022
Actually, let me try to explain what I'm trying to do with that code:
I want to directly add IL to a project using source-generators.
This can allow me to get around some restrictions using C# strings with AddSource gives me.
Tthinker22712/25/2022
You can't directly add IL, you can only add strings or parse trees.
Tthinker22712/25/2022
If there are restrictions then those restrictions are likely purposeful.
RRuttie12/25/2022
Well, what I'm trying to do in the IL code is access a field I normally don't have access to, as a sort of alternative to reflection but faster
Tthinker22712/25/2022
Firstly I don't think the runtime would allow you to do that
RRuttie12/25/2022
fun fact: it does
Tthinker22712/25/2022
huh, neat
Tthinker22712/25/2022
Secondly go ask in #roslyn
RRuttie12/25/2022
I have it working as just calling a method that builds it at runtime, but I'd prefer to use a source-generator so that the method building is done at compile time (for performance reasons)
Tthinker22712/25/2022
Well, the code source generators generate have all the same restrictions as regular C# code