I'm learning C# and it says in a tutorial "When you run your programme, C# looks for a Method called Main. It uses the Main Method as the starting point for your programmes. It then executes any code between those two curly brackets. "
But on another tutorial site it has a slice of code that says
using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
With the Main method below the other methods. (I'm new at this so I assume that public void acceptdetails, get area, display, are all methods). My question is, why isn't it at the top right below namespace? I put the method up there and it worked the same and checked other posts on here and it said maybe the author was just trying to put emphasis on other things, but I don't fully understand why.
It doesn't matter where you put it. Main() is always the entry point when the program first runs. Functions such as Main() can be anywhere in the code and the compiler will start running there, assuming it compiles and syntax is fine.
It looks like the author of the above code purposely put the Main() function at the bottom of that source code to illustrate this point.
Main()
is a 'special' function that serves as the entry point for the program, even if it does not occur first in the code listing. In the code above, the programmer put the declaration of the Rectangle
class first, but that doesn't affect which code runs first.
Main()
runs first. That's the way the language is designed to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With