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".

The content is below:

class Program
{
static void Main(string[] args)
{
StreamReader sr = null;

try
{

double d = 45.66778;
d = RoundToTwoDecimalPlaces(d);
console.WriteLine(d.ToString());

}
catch (Exception e)
{
Console.WriteLine(e.Message);

}


}


double RoundToTwoDecimalPlaces(double val)
{
// val contains your given value

// we declare a string that contains the truncated value
string decimal_adjusted = val.ToString("N4");

double val_adjusted = double.Parse(decimal_adjusted);

return val_adjusted;
}

}

It won't even compile. The error is:

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

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

It seems that in order to make the code compile, I have to create a
new class and access the method "RoundToTwoDecimalPlaces" from that
class. This doesn't make sense to me- It's a generic math function and
shouldn't be attached to any class.

Anyone agree with me on this?
 
Curious,

I like it more like this.

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

try
{

double d = 45.66778;
d = new RunPart().RoundToTwoDecimalPlaces(d);
Console.WriteLine(d.ToString());


}
catch (Exception ex)
{
Console.WriteLine(ex.Message);

}


}

class RunPart
{
internal double RoundToTwoDecimalPlaces(double val)
{
// val contains your given value

// we declare a string that contains the truncated value
string decimal_adjusted = val.ToString("N4");

double val_adjusted = double.Parse(decimal_adjusted);

return val_adjusted;
}

}
}
///

Cor
 
Curious,

I like it more like this.

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

            try
            {

                double d = 45.66778;
                d = new RunPart().RoundToTwoDecimalPlaces(d);
                Console.WriteLine(d.ToString());

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }

        }

        class RunPart
        {
           internal double RoundToTwoDecimalPlaces(double val)
            {
                // val contains your given value

                // we declare a string that contains the truncated value
                string decimal_adjusted = val.ToString("N4");

                double val_adjusted = double.Parse(decimal_adjusted);

                return val_adjusted;
            }

        }
    }
///

Thanks Cor! I agree that "internal" is the right protection method -
It means public within the assembly. It can be used anywhere in the
assembly.
 
Back
Top