What causes this: "An object reference is required for the non-static field, method, or property "

Started by
1 comment, last by ChaosEngine 11 years, 8 months ago
Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication_FileTest.Program.GetAverageSalary(string)' C:\Users\Dawn\documents\visual studio 11\Projects\ConsoleApplication_FileTest\ConsoleApplication_FileTest\Program.cs 98 24 ConsoleApplication_FileTest
static void Main(string[] args)
{

Dictionary<string, double> averages = new Dictionary<string, double>();
string filename = "c:\\test.txt";
averages = GetAverageSalary(filename)
}

=====================
Dictionary<string, double> GetAverageSalary(string filename)
{
...
Advertisement
GetAverageSalary is a non-static method. Main is a static method. You can't call a non-static method from a static method.

If you make GetAverageSalary a static method it should work.

static Dictionary<string, double> GetAverageSalary(string filename)

GetAverageSalary is a non-static method. Main is a static method. You can't call a non-static method from a static method.



More correctly, you can't call a non-static method from a static method without a class instance.

i.e.

class Thing
{
public static void DoStuff()
{
}
public /* not static */ void DoMoreStuff()
{
}
}
class Program
{
public static void Main()
{
Thing.DoStuff(); // ok
Thing.DoMoreStuff(); // not ok

// should be
var thingy = new Thing();
thingy.DoMoreStuff();
}
}

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

This topic is closed to new replies.

Advertisement