Visual Studio Code: "Program has more than one entry point defined"
Asked Answered
A

2

11

I created a C# project using Visual Studio Code. This project contains two .cs files, Addition.cs and Substraction.cs. Both files contain a main() function and both files contain two different programs.

Code in the Addition.cs file:

using System;

namespace Example
{
    class Addition
    {
        static void Main(string[] args)
        {
            int sum = 3 + 2;
            Console.WriteLine(sum);
        }
    }
}

Code in the Substraction.cs file

using System;

namespace Example
{
    class Substraction
    {
        static void Main(string[] args)
        {
            int sub = 3 - 2;
            Console.WriteLine(sub);
        }
    }
}

I want to test both the programs one by one, but when I do

"dotnet run"

It fails with the above error.

I know because of two main() functions (entry points) in the same project is creating this error, but this can be overcome in Visual Studio by setting up a startup project.

I am using Visual Studio Code, where I am unable to set up a startup project.

Is there a way to set up an entry point for a C# project in Visual Studio Code?

Aurar answered 7/11, 2017 at 7:44 Comment(0)
N
23

If both entry points are in the same project, setting the startup project wouldn't do anything anyway. You need to set the startup object.

This can be done in the project properties dialog in a full version of Visual Studio (look for "Startup object" under Application), or in the .csproj file by setting Project/PropertyGroup/StartupObject:

<StartupObject>Example.Addition</StartupObject>

Alternatively consider using a single Main() entry point which takes a command-line argument.

Nephoscope answered 7/11, 2017 at 7:48 Comment(0)
G
1

If you are using Visual Studio Code then add the following line.

<StartupObject>ExampleNameSpace.ExampleClass</StartupObject>

For ExampleNameSpace, type your namespace name

For ExampleClass, type your class name.

Let if I consider that your Namespace is CSharp and the class in which you defined the Main method is MainClass then your .csproj should look like this.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <StartupObject>CSharp.MainClass</StartupObject>
  </PropertyGroup>
</Project>

Note: This code sample is for .Net5

Gallicanism answered 28/10, 2021 at 4:29 Comment(2)
Hi John, Thanks for your answer but it looks like your answer is conveying same thing what @Ic. is provided in his/her answerAurar
Yes, it is. But he hasn't mentioned where to put this code when you are using Visual Studio Code in the .csproj file. I have written this for absolute beginners.Gallicanism

© 2022 - 2024 — McMap. All rights reserved.