Tvde1 Tvde1 - 1 month ago 8
C# Question

Turn textbox text into string with code in it

So I've made a function called

Something(string text)
that needs a
string
.
Now I have a button that onclick does
Something(textBox1.Text)
.

I want the
textBox.Text
to be able to be something like
"test " + (5+2).toString()


Now the function will get
""test " + (5+2).toString()"
(for example) as input and it'll treat that like a big string.

What I want it to do is get
test 7
and not treat it like one big string.

How would I go about doing that?

Thanks in advance!
-Tim

EDIT:

This would be my function:

private void Something(string text)
{
MessageBox.Show(text);
}


If I then do

Something(textBox1.Text);


When textBox1 looks like

__________________
| "hi " + "test" |
------------------


It will do make a MessageBox that says
"hi" + "test"
and not
hi test
.

Answer

You need to compile the string in your textbox and run the code before giving it to your Something-method.

Take a look at Roslyn to easily evaluate the expression from the textbox.

Then you'll get:

string result = await CSharpScript.EvaluateAsync<string>("\"test \" + (5+2).toString()");
Something(result);
Comments