Console Application in .NET

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

When I select File->New->Project, and then if I pick "Console
Application", it automatically creates a file, "Program.cs".

After I fill in some code in the Main method, the content of
"Program.cs" is below:

class Program
{
static void Main(string[] args)
{

double d = 45.66778;
d = RoundToTwoDecimalPlaces(d);
}


double RoundToTwoDecimalPlaces(double val)
{

string decimal_adjusted = val.ToString("N4");
double val_adjusted = double.Parse(decimal_adjusted);
return val_adjusted;
}
}


However, this won't compile. The error is:

"An object reference is required for the nonstatic field, method, or
property 'Program.RoundToTwoDecimalPlaces(double)'"

I must create a new class such as "MyNumeric", and add the method
"RoundToTwoDecimalPlaces" to the class, "MyNumeric". Then I have to
create in "Main" an object such as "mn" and use "d =
mn.RoundToTwoDecimalPlaces(d);"

It seems that I'll have to access the method "RoundToTwoDecimalPlaces"
from an object instead of accessing it directly from the same class
"Program". This doesn't make sense to me.

Anyone comments on this?
 
You could also declare your routine as static:

static double RoundToTwoDecimalPlaces(double val)
 
Curious said:
class Program
{
static void Main(string[] args)
{

double d = 45.66778;
d = RoundToTwoDecimalPlaces(d);
}


double RoundToTwoDecimalPlaces(double val)
{

string decimal_adjusted = val.ToString("N4");
double val_adjusted = double.Parse(decimal_adjusted);
return val_adjusted;
}
}


However, this won't compile. The error is:

"An object reference is required for the nonstatic field, method, or
property 'Program.RoundToTwoDecimalPlaces(double)'"

That's because Main() is *Static* and every procedure called from Main()
must be declared as Static too.

Don't hold me to it, because it's been awhile, but even declaration of
(double d) may need to be (static double d), because you declared it in
(static Main()) instead of declaring it between class Program and the
static Main() statements, outside of static Main().
 
Arnold,

Thanks for your input! FYI, (double d) doesn't have to be defined as
static inside static Main.
 
Curious said:
Thanks for your input! FYI, (double d) doesn't have to be defined as
static inside static Main.

And indeed can't. Local variables can never be declared as static (in
C#).
 
Back
Top