1

class Program {
    static void Main(string[] args) {
        string getnums = Console.ReadLine();
        int getnum=Convert.ToInt32(getnums);
        int[] array1=new int[getnum];
        
        GenerateNum(getnum);
        RevArray();
        PrintArray();
    }
    static int[] GenerateNum(int g){
        
        for(int index=0; index<g; index++){
            array1[index]=index;
        }
        return array1;
    }
    static int[] RevArray(){
        for(int index=0; index<=getnum/2; index++){
            int a=array1[index];
            array1[index]=array1[getnum];
            array1[getnum]=a;
        }
        return array1;
    }
    static void PrintArray(){
        Console.WriteLine(array1);
    }
} 

Hi. I'm trying to write a program with three methods and each of them does one action. GenerateNum() takes getnum as a parameter and creates an array with numbers up to getnum. RevArray() reverses the array and PrintArray() prints it out. However I get error messages. All of them are name 'array1' and name 'getnum' does not exist in the current context. I have defined them in the Main method, then why doesn't it work? Please help me. Thanks in advance!

anon
  • 73
  • 9
  • 2
    Those variables are local to the `Main` function so you can't access them. You need to declare them in a wider scope (Like defining them as fields of `Program` class). – Eldar Dec 16 '20 at 09:09

1 Answers1

3

I have defined them in the Main method

Variables defined in some method A are only available to that method. If you want to use them in other methods, you need to either

  • declare them in a wider scope (for example, by making them static fields of your class) or by
  • passing them as parameters.

The latter is usually preferable (see, e.g. Are global variables bad?).


For example, GenerateNum could be defined as

 static int[] GenerateNum(int g, int[] array1) { ... }

and called as

GenerateNum(getnum, array1);

There are lots of other things that could be improved in your code (for example, you do not need to return arrays if you modify them in-place, and GenerateNum could allocate the array itself instead of requiring an array with the correct size to be passed), so you might want to submit your code to https://codereview.stackexchange.com after you got it running.

Heinzi
  • 167,459
  • 57
  • 363
  • 519