0

I can execute a C# source from PowerShell and a PowerShell source from C#. The question is, How can I execute a C# source from a C# program without compiling with csc.exe?

4
  • 1
    Don't. Just don't. You're probably thinking about an eval() function, like with javascript and other dynamic languages. The thing is, for general purpose languages, eval() is a huge gaping security issue. C# does make it possible to execute c# source code, but it rightly makes it very hard to do. Commented Jul 24, 2014 at 14:38
  • 1
    Read up on Roslyn. It's a new 'compiler-as-a-service' capability in the .NET platform. roslyn.codeplex.com -- Ultimately, you cannot really execute C# code without compiling, but you can use Rosyln to do some "scripty" stuff with C# Commented Jul 24, 2014 at 14:38
  • Since C# has open specification you can write your own compiler :) Commented Jul 24, 2014 at 14:40
  • 3
    blogs.msdn.com/b/csharpfaq/archive/2011/12/02/… Commented Jul 24, 2014 at 14:41

1 Answer 1

2

Yes. This is explicitly catered for in the .net framework using the CodeDom class namespace. http://msdn.microsoft.com/en-us/library/650ax5cx(v=vs.110).aspx System.CodeDom and System.CodeDom.Compiler.

(from the documention)

CSharpCodeProvider provider = new CSharpCodeProvider();

// Build the parameters for source compilation.
CompilerParameters cp = new CompilerParameters();

// Add an assembly reference.
cp.ReferencedAssemblies.Add( "System.dll" );

// Generate an executable instead of 
// a class library.
cp.GenerateExecutable = true;

// Set the assembly file name to generate.
cp.OutputAssembly = exeFile;

// Save the assembly as a physical file.
cp.GenerateInMemory = false;

// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);

I realise this does use the compiler internally, which is something the OP wished to avoid, but I can't see any reason not to use this to .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.