Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

C# from the command window

2020-11-07

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!

Categories: C#

Leave a Reply

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



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips