Skip to content

Instantly share code, notes, and snippets.

@hansschmucker
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hansschmucker/820d3bdeca34c665b77a to your computer and use it in GitHub Desktop.
Save hansschmucker/820d3bdeca34c665b77a to your computer and use it in GitHub Desktop.
Compiles C# code piped to it and runs it immediately without a temporary EXE. Prefix "@" if you want to describe a whole class, not just the content of main.
@PowerShell -command "$src=''+$input; if ( $src -match '^[\s]*@([\s\S]*)$' ){ $src=$matches[1]; }else{ $src='using System; public class App { public static void Main() { '+$src+' } } '; } $opt = New-Object System.CodeDom.Compiler.CompilerParameters; $opt.GenerateInMemory = $true; $cr = [System.CodeDom.Compiler.CodeDomProvider]::CreateProvider('CSharp').CompileAssemblyFromSource($opt, $src); if($cr.CompiledAssembly) {$obj = $cr.CompiledAssembly.CreateInstance('App'); $obj.GetType().GetMethod('Main').Invoke($obj, $null);}else{ $cr.errors; }"
@hansschmucker
Copy link
Author

To use it, you can just pipe code to it (just be sure to escape the linebreak and adding a space before the final pipe character):
@echo ^
var a="Hello World";^
System.Console.WriteLine(a);^
|c#

@hansschmucker
Copy link
Author

Here's a link to the article explaining what this is good for:
http://www.tapper-ware.net/blog/?p=349

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment