Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

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

like image 449
MAR1 Avatar asked Oct 28 '25 23:10

MAR1


1 Answers

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.

like image 110
Jon Skeet Avatar answered Oct 30 '25 13:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!