Shaddix
Shaddix

Reputation: 6109

C# 9 top-level programs without csproj?

One feature of coming C# 9 is so called top-level programs. So that you could just write the following without classes.

using System;

Console.WriteLine("Hello World!");

and dotnet run will launch it for you.

It works for me, but only if I also add a .csproj file like the one below

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
    </PropertyGroup>
</Project>

Is there a way to skip .csproj from the picture? :) So that there's just a single Program.cs file and nothing more.

Upvotes: 23

Views: 2427

Answers (2)

Erik Karlsson
Erik Karlsson

Reputation: 598

You can create a C# script file (.csx) and run it with the dotnet script tool from

https://github.com/filipw/dotnet-script

But not a true, valid, C# file no

Upvotes: 3

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

No there isn't. The csproj file, explains to the compiler what kind of output to make.

It also references any needed libraries, in your case that is the SDK: https://learn.microsoft.com/en-us/dotnet/core/tools/csproj

Metapackages are implicitly referenced based on the target framework(s) specified in the <TargetFramework> or <TargetFrameworks> property of your project file.

Without it, net core would miss information on what to build and how. You wouldn't even have the references to System Namespaces available.

Upvotes: 21

Related Questions