Home > Software design >  how to execute another .cs file except Program.cs in vs code using c#
how to execute another .cs file except Program.cs in vs code using c#

Time:06-13

can i add another .cs file except Program.cs and run it. i have tried multiple times to run other .cs files but every time it is "Program.cs" which is executing in terminal and shows "Hello World" output. except "Main method trick" is there any option to create many .cs files as much as i can

CodePudding user response:

Main method is an entry point for the .NET app by agreement. Don't change this behaviour without a strict understanding (and documentation) of what you're doing.

Probably, you would like to create a few projects in your solution, with the Main method in each. In that case select the project you want to run right clicking on it in the Solution Explorer and choosing "Set as Startup Project" enter image description here

CodePudding user response:

If you are trying to compile and run an individual file, your compiler is likely set up to only compile Program.cs. Read this and it should help:

Compiling/Executing a C# Source File in Command Prompt

but if you are trying to execute code from another file, try the following

Program.cs:

Console.WriteLine("Hello, World!");
SecondFile secondFile = new();
secondFile.MethodInFile2();

SecondFile.cs:

class SecondFile {
    public void MethodInFile2() {
        Console.WriteLine("This is in the second file");
    }
}
  • Related