Getting error: A field initializer cannot reference the non static field, method, or property

The error message was:

Error   1   A field initializer cannot reference the non-static field, method, or property 'AmazingPaintball.Form1.thePoint'    

This is the constructor:

namespace AmazingPaintball
{
class Paintball
{
    public Point startPoint;


    public Paintball(Point myPoint)
    {
        startPoint = myPoint;


    }

This is the code that causes the error:

    Point thePoint = new Point(50, 50);
    Paintball gun = new Paintball(thePoint);
Jon Skeet
people
quotationmark

You haven't shown enough context, but I suspect you've got something like:

class Game
{
    Point thePoint = new Point(50, 50);
    Paintball gun = new Paintball(thePoint);
}

As the compiler says, a field initializer can't refer to another field or an instance member. The solution is simple though - put the initialization in the constructor:

class Game
{
    Point thePoint;
    Paintball gun;

    public Game()
    {
        thePoint = new Point(50, 50);
        gun = new Paintball(thePoint);
    }
}

That's assuming you really need both fields, mind you. If you only actually need a gun field, you can use:

class Game
{
    Paintball gun = new Paintball(new Point(50, 50));
}

(As an aside, I'd strongly advise against variable names beginning with the. The prefix doesn't add any extra information... it's just noise.)

people

See more on this question at Stackoverflow