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?
-
1Don'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.Joel Coehoorn– Joel Coehoorn2014-07-24 14:38:08 +00:00Commented Jul 24, 2014 at 14:38
-
1Read 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#Glenn Ferrie– Glenn Ferrie2014-07-24 14:38:25 +00:00Commented Jul 24, 2014 at 14:38
-
Since C# has open specification you can write your own compiler :)Ondrej Svejdar– Ondrej Svejdar2014-07-24 14:40:07 +00:00Commented Jul 24, 2014 at 14:40
-
3blogs.msdn.com/b/csharpfaq/archive/2011/12/02/…ASA– ASA2014-07-24 14:41:47 +00:00Commented Jul 24, 2014 at 14:41
Add a comment
|
1 Answer
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 .