I want to make a c# script that says “Hello, World”. I have installed WSL and dotnet and I’m using a Linux Terminal. How do I do this?
I have tried to make the file using touch .cs which does create a file and I have written Console.WriteLine(“Hello, World”); in it.
I have tried using dotnet build but it says
Data at root level is invalid
Then I tried committing and then dotnet build again but that gave me the same error.
3
As you mentioned, you have dotnet
CLI.
So the answer is – each C# code needs a project, that specifies some stuff (what framework it uses, some build settings, etc.). That info is put into *.csproj
file. And then inside of it you can add references to C# code files .cs
. Or you can just put .cs
files in the same directory and they will be picked up automatically.
So what you need to do is:
- Create project with
dotnet new console
– it will create simple console app with one C# fileProgram.cs
, which will haveConsole.WriteLine
in it - To build it, simply run
dotnet build
, it will automatically look forcsproj
file - To run it, execute
dotnet run
– it will automatically pickcsproj
file.
To add new C# file, just do
'public static class Test { public static void Method() { Console.WriteLine("my first c sharp code"); } }' >> Test.cs
'Test.Method();' >> Program.cs
This will create Test
class in Test.cs
file and add its method invocation to Program.cs
It’s not possible to directly compile and run a .cs
file, you need to create a project first and add that file to your project.
There’s an issue and ongoing conversation to add this feature in dotnet cli.
Not an exact answer to the question but an elaborated comment on the assertion:
It’s not possible to directly compile and run
there are some REPL (Read Eval Print Loop) that allow you to run a csharp file.
csi.exe, shipped with visual studio, used to be a good one.
I encourage you ro read from https://www.nuget.org/packages/CSharpRepl/0.3.5.
Whatever, dotnet run
with a csproj is a good way to run cs files (with better perfs once the exe exists).