Home > Back-end >  Specifying cs file to build with dotnet CLI
Specifying cs file to build with dotnet CLI

Time:05-14

Suppose I have two files in my current working directory:

// file1.cs
Console.WriteLine("file1");
//file 2.cs
Console.WriteLine("file2");

In powershell, I do a dotnet new and delete the automatically generated Program.cs file. Then I do a dotnet build and get an error:

Only one compilation unit can have top level statements

I understand why this occurs, but I would like to be able to have full control of which .cs file is being targetted, while the other ones get ignored.

Is there any way to achieve this without having to create a whole new project for every file?

CodePudding user response:

https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements

These files both use top-level statements. It implies that they both contain the Main method where program execution starts. You can only have one entry point. Generally, C# code is going to be contained within classes. Define a class in one (or both) files and put your methods within.

// Program.cs
public class Program
{
    static void Main()
    {
        Console.WriteLine("Program.cs");
    }
}

// Util.cs
public class Util
{
    public static void Display()
    {
        Console.WriteLine("Util.cs");
    }
}

CodePudding user response:

Doing this with .NET doesn't seem to be possible as of now. An issue on the dotnet/sdk GitHub has requested for this feature to be implemented.

However, you can use the C Sharp Compiler to compile a Windows executable and specify a .cs file with csc file1.cs

file1.cs:
using System;

Console.WriteLine("File 1");
  • Related