Search code examples
c#arraystemporary-objects

Trying to access a temporary array in another method


I'm sorry if this is a silly question, but as a beginner in coding, I find it hard to remember the limits/bounds of variables that I create. I am trying to create a temporary array in the GetLetters() method below, but I later need to access this information in the EstimateGrade() method so as to "estimate a grade" for the user based on their name.

I get the error that "the name 'threeLetters' does not exist in the current context'.

Is there a way to access the threeLetters array without creating a public array.

public int[] GetLetters(String userName)
    {
        //Creating an array that will hold the 3 values that determine grade
        int[] threeLetters = new int[3];

        char firstLetter = userName[0];
        threeLetters[0] = userName[0];
        char thirdLetter = userName[2];
        threeLetters[1] = userName[2];
        char fifthLetter = userName[4];
        threeLetters[2] = userName[4];

        if(userName.Length > 5)
        {
            threeLetters = new int[0];
        }

        return threeLetters;
    }

    public int EstimateGrade(int[] grade)
    {
        int sum = (threeLetters[0] + threeLetters[1] + threeLetters[2]) * 85;
        int result = sum % 101;
        return result;
    }

Solution

  • threeLetters[] is local to GetLetters(), ie threeLetters[] is not accessible outside the GetLetters(). Since you are passing threeLetters[] as parameter to EstimateGrade() with alias name grade[] then change the threeLetters to grade. See the below code.

    public int EstimateGrade(int[] grade)
    {
        int sum = (grade[0] + grade[1] + grade[2]) * 85;
        int result = sum % 101;
        return result;
    }