I'm learning C# and I'm very new to it, so forgive me for the seemingly stupid question. I have some experience in Java, and I noticed that C# programs also need a main()
method in their main class.
What if I want to create a class that isn't a main class, i.e. one that I import into a main class?
I tried to do that, and when I compile (via cmd using csc File.cs
) the compiler says that the .exe that it will make has no main()
method. Does that mean that I was wrong, and every class needs a main()
method, or that I'm compiling it wrongly?
Maybe the problem's in the code (since I'm relying on my knowledge of Java syntax), which looks like this:
public class Class
{
int stuff;
public Class(int stuff)
{
this.stuff = stuff;
stuff();
}
public void method()
{
stuff();
}
}
EDIT: I'm afraid this is terribly misunderstood. I'm not asking if the file needs a main method, I'm asking how I can import this class into another class, because I realise that if I am to do this I can't have a main (as I said, I have some Java experience), but whenever I try to compile without one the compiler tells me that I need one.
Only one class with one method should be fine. If you want, you can set up the start up object in visual studio in the settings.
C# class without Main() means, you can compile it as a library (.dll) csc /target:library YourClassFileName.cs or csc /t:library YourClassFileName.cs to make it as YourClassFileName.dll file and then you can use it in another class file which have the Main() method (Entry point)
csc /reference:YourClassFileName.cs YourMainClassFileName.cs or csc /r:YourClassFileName.cs YourMainClassFileName.cs
to make an YourMainClassFileName.exe file
You only need a
main
method when you build an executable assembly (.exe), and you only need it in one class. This method will be the default entry point where execution starts. You don't need amain
method when you build your code as a class library (.dll).In this scenario you need at least one class in your code with the
Main
method in it. The other classes do not need theMain
method.Not all classes need
Main
method.As MSDN States
Only one class need to keep the
Main
method, the class which acts as entry point of the application.The signature of the main method is :
static void Main(string[] args)
orstatic void Main()
orstatic int Main(string[] args)
orstatic int Main()
Check out this link for more details :
Main() and Command-Line Arguments (C# Programming Guide
)For your above example:
If you need to use that class, you can create a static class with main method:
If this is a console application, you need a Main method to start with. Otherwise (web application, for example), you don't need one.