Is it possible to automatically output value in C# Interactive (REPL) like Immediate does?

7k views Asked by At

I started using C# Interactive and like the fact that I can browse and explore some API functionalities like I do with Immediate without the need to run and debug my program.

The problem is that it does not output the info like Immediate does unless I do a command with a variable name:

 > string.Format("{0,15}", 10m);         //hit enter, here there is no output
 > var a = string.Format("{0,15}", 10m); //hit enter so...
 > a                                     // hit enter and...
  "        10"                           //...here the value is shown
 >

Is there a way to make C# Interactive output the values in every evaluation like Immediate does (And without write more code for that like Console.Write)?

3

There are 3 answers

1
Crowcoder On BEST ANSWER

Yes, to output the result of an evaluated expression simply do not put a semicolon at the end. In your example, instead of this:

string.Format("{0,15}", 10m);

do this:

string.Format("{0,15}", 10m)

See the documentation

3
acelent On

When you finish with a statement (e.g. ending with ;), which you must when declaring variables, you don't get any output, as it's supposed to have side-effects only.

When you finish with an expression (e.g. not ending with ;), you get the result of that expression. A workaround is:

var a = string.Format("{0,15}", 10m); a

Notice a as an expression at the end, you'll get its value printed.


Personally, for multi-line snippets I want to test, I usually have a res variable:

object res;
// code where I set res = something;
using (var reader = new System.IO.StringReader("test"))
{
    res = reader.ReadToEnd();
}
res

The typing overhead happens once per Visual Studio session, but then I just use Alt+↑ to select one of the previous entries.

5
SavindraSingh On

I know this is too late but anyone who is looking for an answer to similar question. Just in case you want to run a for loop and print values in C# interactive window, you can use Print() method:

string Characters = "Hello World!";
> foreach (char _Char in Characters)
. {
.     Print(_Char);
. }
'H'
'e'
'l'
'l'
'o'
' '
'W'
'o'
'r'
'l'
'd'
'!'