Reputation: 16049
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?
Upvotes: 11
Views: 16839
Reputation: 115
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
Upvotes: 1
Reputation: 116498
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.
Upvotes: 24