I know people have asked about this question before but the scenario's were too specific and I am confused about the fundamentals.
I have two basic versions of a C# program, one that works, and one that doesn't. I would love it if someone could please explain why I get the error An object reference is required for the nonstatic field, method, or property in the second program.
Works:
namespace Experiments
{
class Test
{
public string myTest = "Gobbledigook";
public void Print()
{
Console.Write(myTest);
}
}
class Program
{
static void Main(string[] args)
{
Test newTest = new Test();
newTest.Print();
while (true)
;
}
}
}
Does not work:
namespace Experiments
{
class Test
{
public string myTest = "Gobbledigook";
public void Print()
{
Console.Write(myTest);
}
}
class Program
{
public Test newTest = new Test();
static void Main(string[] args)
{
newTest.Print();
while (true)
;
}
}
}
When I try to Print() the text from the Test() class in the second program, it gives me that error An object reference is required for the nonstatic field, method, or property, and I don't understand why. I can see it has to do with where I declare an instance of the Test() class, but I don't remember anything like this happening in C++, so it mystifies me.
What's going on?
It is not because of the definition of the class, it is all about the usage of keyword static
.
The newTest
object of the class Test
is a public member of the class Program
and the main
is a static function inside the program class. and it is clearly mentioned in the error message An object reference is required for the non-static method
. So what you need is Declare the newTest
object as static in order to access them in static methods like main.
like this
public static Test newTest = new Test();
An Additional Note
Consider that you ware defining the method Print
as static
inside the class Test
as like the following:
public static void Print()
{
Console.Write(myTest);
}
Then you cant call the method like what you are currently using(newTest.Print();
). Instead of that you have to use Test.Print();
, Since A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class