Skip to content

Instantly share code, notes, and snippets.

@Konctantin
Created March 23, 2011 08:48
Show Gist options
  • Save Konctantin/882805 to your computer and use it in GitHub Desktop.
Save Konctantin/882805 to your computer and use it in GitHub Desktop.
Calculator
using System;
using System.CodeDom.Compiler;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace BitCalculator
{
public partial class MainForm : Form
{
private delegate string Calculate();
public MainForm()
{
InitializeComponent();
}
private void tbInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(tbInput.Text.Trim()))
{
try
{
tbOutput.ForeColor = Color.Cyan;
tbOutput.Text = (Compile<Calculate>(tbInput.Text) as Calculate)();
}
catch (Exception ex)
{
tbOutput.ForeColor = Color.Red;
tbOutput.Text = ex.Message;
}
}
}
private Delegate Compile<T>(string code)
{
string compileStr = string.Format(@"
using System;
class Calculator
{{
public static string Invoke()
{{
return ({0}).ToString();
}}
}}", code);
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
CompilerResults compileResults = new CSharpCodeProvider().CompileAssemblyFromSource(compilerParameters, compileStr);
if (compileResults.Errors.Count > 0)
throw new Exception("Error");
else
return Delegate.CreateDelegate(typeof(T), compileResults.CompiledAssembly.GetType("Calculator").GetMethod("Invoke"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment