Search code examples
c#variablesmethodspublic

How to use a variable instantiated outside a method in C#?


I want to know how to use a global variable - which I already instantiated it as a public integer type - in a method later.

Here's my code so far:

public int money = 500000;
//other variables

//...some code in between

public static void UpdateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
        {
            //   \/ Problem here
            if (money < cost)
            {
                //uncheck box
            }
            else
            {
                //implement input variables with other external variables
            }
        }

Solution

  • Remove "static" keyword from your method, static method cannot access instance variables. Static method is something belong to the type itself, while your instance variable is not. another option is to put the "money" as static, but than all your instances going to use the same "money" which is probably not what you aiming for.

        public void updateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
        {
            //   v- No more Problem here :)
            if (money < cost)
            {
                //uncheck box
            }
            else
            {
                //implement input variables with other external variables
            }
        }