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

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();
}
}
}
 
J

Jon Skeet [C# MVP]

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 :)
 
P

Peter Duniho

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
 
P

Progress City

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!
 
C

christery

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top