Realto619
Realto619

Reputation: 301

C# Function Similar to PHP Eval()

I'm looking for a way to display code snippets stored in a database on a webpage with .NET and C# and I saw the exact function that I was looking for a while back, but I cannot remember what search terms I used or the name of the C# function that designed to do that specifically.

Essentially, it's a C# version of PHP's Eval() function, so I can render code examples that I've collected over the years and see the end result as well as the actual source code. I'm sure that this has already been asked, but I couldn't find what I was looking for when I looked through the existing questions on here.

This will be a password protected page on my site for my eyes only (theoretically, at least), so I'm not overly concerned about someone running malicious code. But I appreciate the kind warnings that some may feel obliged to offer before answering my question. Seriously, I do.

I have a feeling that about 10 people will see this question and go, "well, obviously it's (Insert Function Name Here), you silly wabbit." So this is my way of admitting my shame of not knowing right here, up front. Especially when I just saw it like a week ago.

Thanks in advance! Paul


Addendum: I found the following code and it works like a charm on HTML, JS & CSS. Since I've only been working with C# for a few months, I don't have a lot of C# code to render so it works quite well.

String EncodedString = rs["Code"].ToString();
StringWriter writer = new StringWriter();
Server.HtmlDecode(EncodedString, writer);
String DecodedString = writer.ToString();
codeDecoded.Text = DecodedString;

Upvotes: 0

Views: 1610

Answers (2)

James Manning
James Manning

Reputation: 13589

Just curious, are you looking for a REPL-like experience or just one-time evaluations?

Assuming the latter for now, if you can use Roslyn, their scripting API should work fine for this.

http://visualstudiomagazine.com/articles/2011/11/16/the-roslyn-scripting-api.aspx

Upvotes: 0

smqplus
smqplus

Reputation: 253

Take a look at the CSharpCodeProvider class.

A similar question was asked here.

Upvotes: 1

Related Questions