Home > other >  can you compile a c# script without a csproj file in dotnet 5 and later
can you compile a c# script without a csproj file in dotnet 5 and later

Time:05-27

I mean like in c you can do cl.exe main.cpp

I don't have really any reason to do that, just curious

CodePudding user response:

Assuming by "script" you mean "normal C# source file" then yes, absolutely, if csc is available to you:

Program.cs:

using System;
Console.WriteLine("Hello world");

Compile:

csc Program.cs

Run:

./Program.exe

Now, decompiling that, it looks like it's targeting .NET Framework rather than .NET Core by default, but I'd expect it to be feasible to change that if you really want to, by specifying a custom response file. It does make the latest C# features available to you, but if you use C# features that are only supported on later versions of .NET (e.g. default interface implementations) then I suspect you'd have to explicitly specify the appropriate standard libraries rather than using the default .NET Framework ones.

If csc isn't available to you as an executable, the DLL may still be available in the .NET SDK directory, under Roslyn/bincore.

For example, on my WSL2 Ubuntu installation, just trying to run csc fails, but the command below definitely invokes csc:

dotnet /usr/share/dotnet/sdk/6.0.202/Roslyn/bincore/csc.dll

The bad news is that trying to use that to just compile a standalone program requires providing library references etc - that's probably more hassle than it's worth.

CodePudding user response:

No - but, for what you may be looking for, the dotnet new console command generates a default csproj that runs the Program.cs file that is also generated. With the new(ish) top level statement files, you can just insert a few usings and your script code, and just use dotnet run

If you're using an IDE, it'll run all the dotnet commands for you though

CodePudding user response:

Yes C# has a Scripting concept(.csx). It also has a REPL (csi.exe)

References : https://docs.microsoft.com/en-us/archive/msdn-magazine/2016/january/essential-net-csharp-scripting

  •  Tags:  
  • c#
  • Related