Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

An object reference is required for the non-static field, method, or property 'Program.x'

I am new to C#, sorry if this is duplicate. I am simply trying to add two variables together but I get the error from the title

An object reference is required for the non-static field, method, or property 'Program.x'

Here is code

using System;

namespace HelloWorld
{
  class Program
  {
    int x = 3;
    int y = 10;
    static void Main(string[] args)
    {
        int mathResults = x + y;

        string results = mathResults.ToString();

        Console.WriteLine("Hello World!");    
    }
  }
}

Could someone please explain WHY I am getting this error? Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As your Main() method is static, you must use static variables in it.

So it should be like this :

class Program
  {
    static int x = 3;
    static int y = 10;

    static void Main(string[] args)
    {
        int mathResults = x + y;

        string results = mathResults.ToString();

        Console.WriteLine("Hello World!");    
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading