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?
Asked
Active
Viewed 825 times
1
-
Your other .cs files must be bundled as assembly (.DLL) files, and can be used in other projects. Or you can include them in the same project, but the entry point function will always be Main(). – Anand Sowmithiran Jun 12 '22 at 16:06
-
We might be reading too much into this question. Are you trying to understand how to create more files and have them be part of the application? Or how code that isn't part of Program.cs fits in? – Scott Hannen Jun 12 '22 at 16:15
2 Answers
1
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");
}
}

mcky
- 823
- 2
- 7
- 20
-
I think the OP is wanting to execute code that is in other source files. – Anand Sowmithiran Jun 12 '22 at 16:08
-
@AnandSowmithiran I think you may be right. The question is worded in the most ambiguous way possible. – mcky Jun 12 '22 at 16:21
1
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"

Oxoron
- 664
- 1
- 7
- 26