I've been trying simple experiments to learn C# methods. The below code simply calls playerSelection() which asks the user for a character and returns that character to Main(string[] args). Main prints that to the console. With the below code I get the following error "An object reference is required from a non-static field."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SimpleFunction
{
class Program
{
static void Main(string[] args)
{
char cplayerChoice = playerSelection();
Console.WriteLine(cplayerChoice);
}
char playerSelection()
{
Console.WriteLine("\nEnter a Character");
char cplayerChoice = Console.ReadKey().KeyChar;
return cplayerChoice;
}
}
}
Now if I add the word static like so:
static char playerSelection()
it compiles and works. I do understand static versus non...abstractly.
I'm learning C# from a book and in that book they go through the below example to illustrate using methods:
using System;
namespace GetinPaid
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
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);
}
}
}
Why in their example can they call methods without using the keyword static but I have to use it?
Thanks!
In their example, they're creating an instance of Program
, and calling a method on that instance:
(new Program()).run();
This is more cleanly written as:
Program program = new Program();
program.run();
From within those instance methods, you can call other instance methods because you're implicitly calling them on this
.
As an aside, if that really is sample code from the book, I suggest you get a different book: there are some very questionable aspects of style there. In particular:
private
is explicit or implicitReadInt32
instead of readInt
. Again, it's not as important for private methods, but it's a bad habit to get intodouble
for currency values is a really bad ideap
gives no information (in various places, used for different meanings)TryParse
rather than Parse
, and check the return value then potentially reprompt on bad inputSee more on this question at Stackoverflow