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?