C# from the command window

If you are using .NET Core (or .NET 5.0) you can easily activate the ability to run C# code from the command window (Windows Terminal or the old cmd.exe).

To get started, install dotnet-script by typing:

dotnet tool install --global dotnet-script

Once installed, you can start the dotnet-script program just by typing:

dotnet-script

The prompt now looks like a greater than-sign (>). From here, you can type any C# code and you can reference anything within the System namespace. For example, if you type:

Console.WriteLine("Hello world!");

…you will get the following answer:

Hello world!

A few things to keep in mind: Types you add will be remembered for the whole session. For example, if you type in a class, you can use that class in the session. And if the command windows expect further input, the prompt will change from a greater than-signe to an asterisk sign (*). So if you type in something like class MyClass { and press Enter, nothing will be executed. Instead, the command window will indicate that more input is expected by displaying an asterisk sign. To try this out, type something like this (terminating each statement with Enter):

class MyClass {
public void DoSomething() {
Console.WriteLine("Hello!");
}
}

And then, you can use your new type like this:

new MyClass().DoSomething();

The response will be:

Hello!

The picture shows the different prompts when you type in a simple for loop:

This is a very powerful tool to use when you want to perform tasks that are a bit too complicated for a calculator, but perhaps a bit too simple fore an advanced computer program, or when you want to try out some API you are working on. Happy programming!

Leave a Reply

Your email address will not be published. Required fields are marked *