1

I have this code to try to output an already inputted list and ask for a matching grade. The array works, when I check the length of it, it matches the input.

I have declared the string array inside my one class.

static string[] nameArray;

Then I have 2 functions that work in this order:

static void ConvertListToArray()
{
    string[] nameArray = names.ToArray();
    arrayLength = nameArray.Length;
}
       
static void AskNameForGrade()
{
    for (int i = 0; i < arrayLength; i++)
    { 
        Console.WriteLine($"Please enter grade for {nameArray[i]}");
    }
}

The part that gives me the error is the {nameArray[i]}

The error message is

"System.NullReferenceException: 'Object reference not set to an instance of an object.'"

I'm thinking that the array is null, but if I check the size before its equal to the input I put in (ie > 1)

I'm sure this is something simple, but any help would be appreciated.

1 Answer 1

3

Disregarding any other problem, the issue is likely the static nameArray field has not be initialized, you are however initializing a local scoped variable with the same name. This is why the static member arrayLength has the value you would assume, and the static member nameArray is uninitialized and null. It's never been set...

I believe there would have a compiler warning alerting you to the problem.

Local variable 'nameArray' hides field string[] blah blah blah

The fix is to remove the local variable

static string[] nameArray;

static void ConvertListToArray()
{
    //string[] nameArray = names.ToArray();
    nameArray = names.ToArray(); // set your static member instead
    arrayLength = nameArray.Length;
}
Sign up to request clarification or add additional context in comments.

3 Comments

For OP - this is a good example of the difference between variable declaration and assignment. And string[] nameArray = names.ToArray(); does both.
Hi Michael - just a quick note on spelling. I notice that frequently your posts are misspelling "its". Unfortunately the English rules of this word are a bit awkward! A good rule of thumb is to work out if you are using a contraction of "it is", then it needs an apostrophe to be correctly spelled. If on the other hand you are using the word in the context of ownership (the dog and its bone) then no apostrophe should be used. This is why your spelling checker probably won't catch it.
@halfer thanks for that, I notice you fix a lot of my posts. I certainty do bastardize the English language, however ill keep that one in mind, as I know I commonly choose the wrong one,.

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.