Hamid
Hamid

Reputation: 827

c# create an instance of an object from string

I have a string variable contain:

string classCode = "public class Person { public string Name{get;set;} }";

How can I create an instance of an object from the classCode ? like

object obj = CreateAnInstanceAnObject(classCode);

Upvotes: 3

Views: 1053

Answers (4)

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Building on the answers from above, here is a working demo to generate, compile and instantiate a class from an in-memory assembly:

namespace DynamicCompilation
{
    using System;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Reflection;

    using Microsoft.CSharp;

    internal static class Program
    {
        private static void Main()
        {
            var ccu = new CodeCompileUnit();
            var cns = new CodeNamespace("Aesop.Demo");

            cns.Imports.Add(new CodeNamespaceImport("System"));

            var ctd = new CodeTypeDeclaration("Test")
            {
                TypeAttributes = TypeAttributes.Public
            };
            var ctre = new CodeTypeReferenceExpression("Console");
            var cmie = new CodeMethodInvokeExpression(ctre, "WriteLine", new CodePrimitiveExpression("Hello World!"));
            var cmm = new CodeMemberMethod
            {
                Name = "Hello",
                Attributes = MemberAttributes.Public
            };

            cmm.Statements.Add(cmie);
            ctd.Members.Add(cmm);
            cns.Types.Add(ctd);
            ccu.Namespaces.Add(cns);

            var provider = new CSharpCodeProvider();
            var parameters = new CompilerParameters
            {
                CompilerOptions = "/target:library /optimize",
                GenerateExecutable = false,
                GenerateInMemory = true
            };

            ////parameters.ReferencedAssemblies.Add("System.dll");

            var results = provider.CompileAssemblyFromDom(parameters, ccu);

            if (results.Errors.Count == 0)
            {
                var t = results.CompiledAssembly.GetType("Aesop.Demo.Test");
                var inst = results.CompiledAssembly.CreateInstance("Aesop.Demo.Test");
                t.InvokeMember("Hello", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, inst, null);
            }

            Console.ReadLine();
        }
    }
}

Upvotes: 3

JaredPar
JaredPar

Reputation: 755457

Simple put you cannot do this in one line as you are attempting. It is possible to create an instance of an existing class via it's name and one of the overloads of Activator.CreateInstance.

What you are trying to achieve here though is quite different. You are attempting to both 1) define a new class type and 2) create an instance of it. Defining new metadata in the running process dynamically is very difficult to achieve with static languages like C#. It requires a significant amount of work that can't easily be put into a StackOverflow answer.

Upvotes: 1

George Johnston
George Johnston

Reputation: 32278

The following project should guide you in what your trying to accomplish:

RunTime Code Compilation

However, if you are attempting to write code at runtime, you may want to rethink your architecture. You may be creating more of a headache for yourself than you need to be.

What are you trying to accomplish by creating this object?

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564861

You'll need to use CodeDom to compile an in-memory assembly, and then use reflection to create the type.

Here's a sample article on MSDN that walks through the process of code generation.

Once you've compiled the code, you can use Activator.CreateInstance to create an instance of it.

Upvotes: 6

Related Questions