Click to See Complete Forum and Search --> : Question about main function


harshtrivedi
October 14th, 2009, 06:12 PM
I have often seen code something similar to
class Program
{
static void Main(string[] Args)
{
(new Program()).run();
}
public void run();
{
//code generally seen in main function;
}
}

Can anyone tell me what is the purpose for following such a method of coding and what are the advantages disadvantages for the same?

vcdebugger
October 14th, 2009, 11:46 PM
Is it in C# or in Java ?

boudino
October 15th, 2009, 02:49 AM
It is defined standard which you must obey if you want you application to run. The Main method is the entry point of a C# console application or windows application. (Libraries and services do not require a Main method as an entry point.). When the application is started, the Main method is the first method that is invoked.

BigEd781
October 15th, 2009, 11:55 AM
It is defined standard which you must obey if you want you application to run.

You know, I thought the same thing at first, but I think that the OP is more concerned with the code inside of main, i.e., (new Program()).run(). I have never seen anyone do that before...

harshtrivedi
October 15th, 2009, 04:44 PM
the code is in C#

you can find similar code at http://www.java2s.com/Code/CSharp/Development-Class/Readdoubleandintfromconsole.htm

here is a sample application for reading input from 2 numbers posted at above site
using System;
using System.Collections.Generic;
using System.Text;

class Program {
static void Main(string[] args) {
(new Program()).run();
}

public void run() {
double dailyRate = readDouble("Enter your daily rate: ");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
}

private void writeFee(double p) {
Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
}

private double calculateFee(double dailyRate, int noOfDays) {
return dailyRate * noOfDays;
}

private int readInt(string p) {
Console.Write(p);
string line = Console.ReadLine();
return int.Parse(line);
}

private double readDouble(string p) {
Console.Write(p);
string line = Console.ReadLine();
return double.Parse(line);
}
}

boudino
October 16th, 2009, 02:36 AM
I'm using similar code quite often, even I preferre to keep Program class just with Main() function and create a new class for the application logick.

harshtrivedi
October 16th, 2009, 01:55 PM
Thanks Boudino,
I read some where that such a method keeps code safe. So in that case, my main function will contain a statement
(new NewClass()).run()
or should I be using
NewClass tempnewclass = new NewClass();

Are there any requirements that my new class should be static or of any other type....?

-harsh

boudino
October 19th, 2009, 02:33 AM
No.