Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3801676
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T14:05:15+00:00 2026-05-19T14:05:15+00:00

How can I wrote C# code to compile and run dynamically generated C# code.

  • 0

How can I wrote C# code to compile and run dynamically generated C# code. Are there examples around?

What I am after is to dynamically build up a C# class (or classes) and run them at runtime. I want the generated class to interact with other C# classes that are not dynamic.

I have seen examples that generate exe or dll files. I am not after that, I just want it to compile some C# code in memory and then run it. For instance,

So here is a class which is not dynamic, it will be defined in my C# assembly and will only change at compile time,

public class NotDynamicClass
{
    private readonly List<string> values = new List<string>();

    public void AddValue(string value)
    {
        values.Add(value);
    }

    public void ProcessValues()
    {
        // do some other stuff with values
    }
}

Here is my class that is dynamic. My C# code will generate this class and run it,

public class DynamicClass
{
    public static void Main()
    {
        NotDynamicClass class = new NotDynamicClass();

        class.AddValue("One");
        class.AddValue("two");
    }
}

So the result is that at the end my non dynamic code would call ProcessValues and it would do some other stuff. The point of the dynamic code is to allow us or the client to add custom logic to the software.

Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T14:05:16+00:00Added an answer on May 19, 2026 at 2:05 pm

    Two possibilities:

    1. Reflection.Emit
    2. System.CodeDom.Compiler

    UPDATE:

    As request in the comments section here’s a full example illustrating the usage of Reflection.Emit to dynamically build a class and add a static method to it:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Reflection.Emit;
    
    public class NotDynamicClass
    {
        private readonly List<string> values = new List<string>();
    
        public void AddValue(string value)
        {
            values.Add(value);
        }
    
        public void ProcessValues()
        {
            foreach (var item in values)
            {
                Console.WriteLine(item);
            }
        }
    }
    
    class Program
    {
        public static void Main()
        {
            var assemblyName = new AssemblyName("DynamicAssemblyDemo");
            var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, false);
            var typeBuilder = moduleBuilder.DefineType("DynamicClass", TypeAttributes.Public);
    
            var methodBuilder = typeBuilder.DefineMethod(
                "Main",
                MethodAttributes.Public | MethodAttributes.Static,
                null,
                new Type[0]
            );
    
            var il = methodBuilder.GetILGenerator();
            var ctor = typeof(NotDynamicClass).GetConstructor(new Type[0]);
            var addValueMi = typeof(NotDynamicClass).GetMethod("AddValue");
            il.Emit(OpCodes.Newobj, ctor);
            il.Emit(OpCodes.Stloc_0);
            il.DeclareLocal(typeof(NotDynamicClass));
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ldstr, "One");
            il.Emit(OpCodes.Callvirt, addValueMi);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ldstr, "Two");
            il.Emit(OpCodes.Callvirt, addValueMi);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, typeof(NotDynamicClass).GetMethod("ProcessValues"));
            il.Emit(OpCodes.Ret);
            var t = typeBuilder.CreateType();
            var mi = t.GetMethod("Main");
            mi.Invoke(null, new object[0]);
        }
    }
    

    You could put breakpoints inside your not NotDynamicClass methods and see how they get invoked.


    UPDATE 2:

    Here’s an example with CodeDom compiler:

    using System;
    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using Microsoft.CSharp;
    
    public class NotDynamicClass
    {
        private readonly List<string> values = new List<string>();
    
        public void AddValue(string value)
        {
            values.Add(value);
        }
    
        public void ProcessValues()
        {
            foreach (var item in values)
            {
                Console.WriteLine(item);
            }
        }
    }
    
    class Program
    {
        public static void Main()
        {
            var provider = CSharpCodeProvider.CreateProvider("c#");
            var options = new CompilerParameters();
            var assemblyContainingNotDynamicClass = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            options.ReferencedAssemblies.Add(assemblyContainingNotDynamicClass);
            var results = provider.CompileAssemblyFromSource(options, new[] 
            { 
    @"public class DynamicClass
    {
        public static void Main()
        {
            NotDynamicClass @class = new NotDynamicClass();
            @class.AddValue(""One"");
            @class.AddValue(""Two"");
            @class.ProcessValues();
        }
    }"
            });
            if (results.Errors.Count > 0)
            {
                foreach (var error in results.Errors)
                {
                    Console.WriteLine(error);
                }
            }
            else
            {
                var t = results.CompiledAssembly.GetType("DynamicClass");
                t.GetMethod("Main").Invoke(null, null);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some c code that I compile and run, in a directory that
If I'm using a Hashtable , I can write code like this: object item
How can I write the following code quickly in emacs? \newcommand{\cA}{\mathcal A} \newcommand{\cB}{\mathcal B}
What is the least amount of code you can write to create, sort (ascending),
Eg. can I write something like this code: public void InactiveCustomers(IEnumerable<Guid> customerIDs) { //...
For a school assignment I have to write x86 assembly code, except I can't
I'm very busy write now debugging some code, so I can't cookup a complete
I wrote the wrong thing in a commit message. How can I change the
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system
I accidently wrote some code today that was like this: Private Sub Foo() Dim

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.