I feel bad for asking this when there are so many questions that are related but I was not able to find/understand the answer I am looking for.
// 2. Develop a program to convert currency X to currency Y and visa versa.
using System;
class Problem2
{
static void Main (string[] args)
{
while (true) {
Console.WriteLine ("1. Currency Conversion from CAD to Won");
Console.WriteLine ("2. Currency Conversion from Won to Cad");
Console.Write ("Choose from the Following: (1 or 2)? ");
int option = int.Parse( Console.ReadLine() );
//double x;
if (option == 1) {
Console.WriteLine ("Type in the amount you would like to Convert CAD to Won: ");
//double y =double.Parse( Console.ReadLine());
//Console.WriteLine( cadToWon( y ) );
Console.WriteLine( cadToWon( double.Parse( Console.ReadLine() ) ));
}
if (option == 2) {
Console.WriteLine ("Type in the amount you would like to Convert Won to CAD: ");
Console.WriteLine( wonToCad (double.Parse( Console.ReadLine())));
}
}
}
double cadToWon( double x )
{
return x * 1113.26;
}
double wonToCad( double x)
{
return x / 1113.26;
}
}
This give me the Error messgae “An object reference is required for the non-static field, method, or property ‘Problem2…” I know that I’ll be able to run the program if I add static infront of the methods but I’m wondering why I need it (I think it’s because Main is static?) and what do I need to change in order to use these methods without adding static to them?
Thank you
Since your Main method is static, cadToWon and wonToCad also have to be static if you want to call them from Main.
The other option would be to break all of the logic of your Main, cadToWon, and wonToCad methods out into a new class, and then have you Main method simply set up and run that new class. But I suspect that might be beyond the scope of your assignment.
To answer you question of why adding static makes this work:
staticmethods are shared across all instances of a class. So no matter what instance of classProblem2you’re in, there’s only oneMainmethod that’s shared across all of them.cadToWon, however, is an instance method. It belongs to a particular instance of classProblem2.As a result, you can’t call
cadToWonfromMain, sinceMaindoesn’t know what instance ofProblem2to callcadToWonon.Maindoesn’t know what instance to callcadToWonon sinceMaindoesn’tbelongto any instance.