Skip to content

Instantly share code, notes, and snippets.

@esersahin
Created January 17, 2024 13:14
Show Gist options
  • Save esersahin/429c9989a14e80d1159674efd43e99b6 to your computer and use it in GitHub Desktop.
Save esersahin/429c9989a14e80d1159674efd43e99b6 to your computer and use it in GitHub Desktop.
Generate Class Create Instance.cs
using System;
using System.CodeDom.Compiler;
using System.Reflection;
class Program
{
static void Main()
{
string code = "public class Person { public int Id {get; set;} public string UserName {get; set;} }";
// Compile the code
CompilerResults results = CompileCode(code);
if (results.Errors.Count == 0)
{
// The code compiled successfully, so create an instance of the generated class
object instance = CreateInstance(results.CompiledAssembly, "Person");
if (instance != null)
{
// Use reflection to access the properties
PropertyInfo idProperty = instance.GetType().GetProperty("Id");
PropertyInfo userNameProperty = instance.GetType().GetProperty("UserName");
// Set property values
idProperty.SetValue(instance, 1);
userNameProperty.SetValue(instance, "JohnDoe");
// Display property values
Console.WriteLine($"Id: {idProperty.GetValue(instance)}");
Console.WriteLine($"UserName: {userNameProperty.GetValue(instance)}");
}
}
else
{
// Display compilation errors
foreach (CompilerError error in results.Errors)
{
Console.WriteLine(error.ErrorText);
}
}
}
static CompilerResults CompileCode(string code)
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false
};
return codeProvider.CompileAssemblyFromSource(compilerParams, code);
}
static object CreateInstance(Assembly assembly, string className)
{
Type type = assembly.GetType(className);
if (type != null)
{
return Activator.CreateInstance(type);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment