简体   繁体   中英

C# “An object reference is required for the non-static field,” Class issue with Static Member Function

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?

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.

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM