An object reference is required for the non-static field, method, orproperty

  • Thread starter Thread starter Progress City
  • Start date Start date
P

Progress City

Compiling the code below gives me the following error

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

How do I create an object reference for the array "a"?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
class Program
{
int[] a = { 2, 4, 6, 8 };

static void Main(string[] args)
{
for (int n = 0; n < 4; n++)
Console.WriteLine(a[n]);
Console.ReadKey();
}
}
}
 
Progress City said:
Compiling the code below gives me the following error

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

How do I create an object reference for the array "a"?

You'd have to create a new instance of Program, e.g.:

static void Main(string[] args)
{
Program p = new Program();
for (int n = 0; n < 4; n++)
Console.WriteLine(p.a[n]);
Console.ReadKey();
}

Alternatively, make "a" static.

My guess is you're just starting out in C# - in which case a good book
would be a better place to start than newsgroups. It's not that we
dislike answering simple questions, it's just that you'll make progress
faster with a book :)
 
Compiling the code below gives me the following error

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

How do I create an object reference for the array "a"?

Where are you getting the error?

I'm guessing it's on the line that calls Console.WriteLine(). If so, it's
because Main() is a static method, but you've declared "a" as an instance
variable.

Make "a" static, and the error should go away.

Pete
 
Progress City said:
Compiling the code below gives me the following error
"An object reference is required for the non-static field, method, or
property"
How do I create an object reference for the array "a"?

You'd have to create a new instance of Program, e.g.:

static void Main(string[] args)
{
Program p = new Program();
for (int n = 0; n < 4; n++)
Console.WriteLine(p.a[n]);
Console.ReadKey();
}

Alternatively, make "a" static.

My guess is you're just starting out in C# - in which case a good book
would be a better place to start than newsgroups. It's not that we
dislike answering simple questions, it's just that you'll make progress
faster with a book :)

Thanks for your incredibly quick reply!
 
Yepp

using System;
using System.Collections.Generic;
using System.Text;


namespace Test
{
class Program
{
static int[] a = { 2, 4, 6, 8 };


static void Main(string[] args)
{
for (int n = 0; n < 4; n++)
Console.WriteLine(a[n]);
Console.ReadKey();
}
}
}

Cheeleading program?
 
Back
Top