Console Application in .NET

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?
 
F

Family Tree Mike

You could also declare your routine as static:

static double RoundToTwoDecimalPlaces(double val)
 
M

Mr. Arnold

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().
 
C

Curious

Thanks Family Tree Mike! It works if I declare the method static in
class Program.
 
C

Curious

Arnold,

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

Jon Skeet [C# MVP]

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#).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top