Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could .NET be parsed and evaluated at runtime

I thought it would be fun if I could write vb.net or c# code at runtime and the interpreter would automatically parse it like python does it, so I made a little program, which would do something similar. Basically it looks like this:

InputArgs = Console.ReadLine()
ParseInput(InputArgs.Split(" "))

Private Sub ParseInput(Args as List(Of String), Optional TempArgs as List(Of String))
Dim arg as string = Args(0)
If arg = ".." then
 ...
elseif arg = ".." then
 ...
end if
End Sub

I know it's not a good system, but it show's the basics. So my question is: Is it possible to make vb.net or c# like python - interpreted at runtime?

like image 700
Cobold Avatar asked Feb 01 '26 05:02

Cobold


2 Answers

This already exists in a fair number of shapes and forms:

Mono.CSharp

Mono has the Mono.CSharp assembly, which you can reference to do whatever CSharp.exe (A C# 'interpreter' or interactive shell, if you will) can do:

void ReadEvalPrintLoopWith (ReadLiner readline)
{
    string expr = null;
    while (!InteractiveBase.QuitRequested){
            string input = readline (expr == null);
            if (input == null)
                return;

            if (input == "")
                continue;

            expr = expr == null ? input : expr + "\n" + input;

            expr = Evaluate (expr);
    } 
}

Needless to say this works on MS.Net too (of course, that's the point about portable .Net).

Full sources here on github - just as the rest of Mono, in fact.

DLR

Several DLR languages have been implemented, including but not limited to

  • IronRuby
  • IronPython
  • Jint (http://jint.codeplex.com/) - does javascript on .Net 2.0

It will allow you to evaluate python/ruby code on the fly in the .NET framework.

Roslyn

Microsoft has published Roslyn as a CTP (preview). It can basically do the same stuff as the Mono REPL (first item), and (much) more. But it is a preview still.

like image 130
sehe Avatar answered Feb 03 '26 17:02

sehe


It can be, but it would be a lot of work.

One way would be to write a parser + interpreter yourself. To create the parser, you'd need a grammar definition of the input language, such as C#. The C# grammar is very complex, mind you.

Another way is to dynamically compile C# code. Here is an example of how to do that: http://www.voidspace.org.uk/ironpython/dynamically_compiling.shtml and http://blogs.msdn.com/b/saveenr/archive/2009/08/11/a-walkthrough-of-dynamically-compiling-c-code.aspx.

Good luck!

like image 20
Roy Dictus Avatar answered Feb 03 '26 18:02

Roy Dictus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!