Search code examples
c#refactoringresharperautomated-refactoring

Why is Resharper telling me my string[] is never assigned?


On this declaration:

string[] TardyEvenEmorys;

...Resharper tells me, "Field 'TardyEvenEmorys' is never assigned."

Later on in the code, assignments are made to the string[]:

TardyEvenEmorys[1] = string.Empty;
TardyEvenEmorys[2] = string.Empty;
TardyEvenEmorys[3] = string.Empty;
TardyEvenEmorys[4] = string.Empty;

...and then actual values are conditionally added:

foreach (KeyValuePair<int, string> entry in itemNumberTardyPairs)
{
    TardyEvenEmorys[entry.Key] = entry.Value;

. . .

...finally, those values are used in this way:

string url = GetTardyFilename(TardyEvenEmorys[Number]);

So what is Resharper telling me? That I should instantiate the string[] on declaration, or...???


Solution

  • You're assigning individual elements of the array, but never actually creating the array itself.

    So what is Resharper telling me? That I should instantiate the string[] on declaration, or...???

    You need to instantiate the array somewhere. This could be during the declaration, or later. For example, to do it during the declaration, you would need to add:

    string[] TardyEvenEmorys = new string[5]; // Some appropriate length
    

    Without this, the first time you assign one of the elements, you'll get an exception since the array is null.