1

I'm working on a project for school (going for my BA in CIS) and I've come across this issue with a class function.

 public static int GetNumberCreated()
    {
        // return the total number of airplanes created using the class as the blueprint

        return numberCreated;  // returns the number of airplanes created
    }//end of public int GetNumberCreated()

It's for a program to return the value of how many airplanes you've made thus far in this small C# program. I declared numberCreated at the beginning:

private int numberCreated;

I get the classic error "An object reference is required for the non-static field, method, or property" I've done a decent amount of research trying to figure out what is going on but i've come up with nothing.

I did however set a property at the bottom of the class so that a form would be able to access the variable:

public int NumberCreated { get; set; }

I also attempted changing the property to this:

public int NumberCreated { get { return numberCreated; } set { numberCreated = value; } }

with no luck. >.>'

What am i doing wrong?

4 Answers 4

5

You need to declare your number created int as static.

eg public static int NumberCreated {get;set;}

You can access a static member from a non static method, but you cant access a non static member from a static method. eg, instance variables are not accessable from static methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ^_^' I can't believe that's all I was missing. Thanks guy.
1

It's a simple thing - you need to add the "static" keyword before your method signature, like so:

public static int NumberCreated { get; set; }

Then you can increment / decrement like so:

AirplaneFactory.NumberCreated++ / AirplaneFactory.NumberCreated--

Comments

1

GetNumberCreated is a static method. The numberCreated is a variable that is created with the object of this class. So, the static method doesn't know where to look, because there is no such variable.

You need a private static int.

Comments

0

In a nutshell, your static method can be called even when "numberCreated" has not been brought into existence yet. The compiler is telling you that you're trying to return a baby without any prior guarantee that it's been born.

Change numberCreated to a static property and it'll compile.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.