-3
using System;
using System.Collections.Generic;
using System.text;
namespace GameTest
{
// class 1
     class TestClass
     {
         public string Test = "Test";
     }
     class Program
     {
          static void Main(string[] args)
          {
           Console.writeline(class1.Test)
          {
     }
}

Returns: An object reference is required for the non-static field, method, or property 'TestClass.test'

I can't figure out why though please help me.

gogy255
  • 15
  • 3
  • 1
    `TestClass` needs to be static along with the `Test` property. Then, you can do `TestClass.Test` – iSR5 Sep 15 '21 at 05:15
  • I just wrote a quick sample code bc i am not gonna Ctrl-c Ctrl-v like 600 lines of code – gogy255 Sep 15 '21 at 05:17
  • 1
    I am closing this as a Typo and not useful for any future users. https://dotnetfiddle.net/6YRZRh – TheGeneral Sep 15 '21 at 05:18
  • 1
    "I just wrote a quick sample code bc i am not gonna Ctrl-c Ctrl-v like 600 lines of code" - it's good to create a [mcve], but you need to create one that actually shows the problem you're describing. This code doesn't. You've got a `{` which should be a `}`. You're missing a semi-colon. You've got `class1.Test` which I suspect should be `TestClass.Test`. You've got `writeline` which should be `WriteLine`. – Jon Skeet Sep 15 '21 at 05:54

1 Answers1

0

You've got two options, make test static (that means it doesn't need an instance of TestClass to exist) or create an instance of testClass

{
// class 1
     class TestClass
     {
         public string nonStaticTest = "Test";//value assigned when object created
         public static string staticTest = "Test";//value assigned at the start of runtime
     }
     class Program
     {
          static void Main(string[] args)
          {
              Console.writeline(TestClass.staticTest);//this is fine
              var instanceOfClass1 = new TestClass();
              Console.writeline(instanceOfClass1.nonStaticTest);//this is also fine
        
          {
     }
}
The Lemon
  • 1,211
  • 15
  • 26
  • 3
    Does not compile because some of the typos in the question are still in (captitalization of the writeline method, wrong closing brace). – Klaus Gütter Sep 15 '21 at 05:22
  • True, I was more focused on getting out a simple answer to the static issues OP was having, there didn't seem to be a point to fixing his other typos – The Lemon Sep 15 '21 at 05:31