Error trying to set or read the value of already defined variables - System.NullReferenceException

1

I'm having problems with this code. Whenever it runs, it causes an exception of type System.NullReferenceException .

// Clear out the Array of code words
        wordBuffer = null;
        Int32 syntaxCount = 0;
        // Create the regular expression object to match against the string
        Regex defaultRegex = new Regex(@"\w+|[^A-Za-z0-9_ \f\t\v]",
        RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match wordMatch;
        // Loop through the string and continue to record
        // words and symbols and their corresponding positions and lengths
        for (wordMatch = defaultRegex.Match(s); wordMatch.Success; wordMatch = wordMatch.NextMatch())
        {
            var word = new Object[3] { wordMatch.Value, wordMatch.Index, wordMatch.Length };
            wordBuffer[syntaxCount] = word;
            Debug.WriteLine("Found = " + word[0]);
            syntaxCount++;
        }
        // return the number of symbols and words
        return syntaxCount;

The exception occurs on these two lines (if I remove the first, the exception occurs on the second):

Debug.WriteLine("Found = " + word[0]);
                syntaxCount++;

Specifically when I try to get the value of word[0] , E in the second line with the variable syntaxCount , but none of them is null, as you can see in the image below:

Thevariable"s" is just a line of a RichEditBox, word[0] has a value, so why is it causing the NullReferenceException exception? syntaxCount has a value too: /

    
asked by anonymous 01.02.2015 / 03:00

2 answers

0

You set the variable wordBuffer to null.

  

wordBuffer = null;

and then try to use it to store a word.

  

wordBuffer [syntaxCount] = word;

You should replace the line wordBuffer = null; with something like this: wordBuffer = new string[{tamanho do vetor}] , replacing {tamanho do vetor} with the desired size for the vector.

    
03.03.2015 / 12:51
1

I reproduced the code here and realized the following:

  

wordBuffer = null; // is an array, change by the code below or in the form you think is best

var wordBuffer = new Array[20];
  

Match (s) // (s) I did not see the statement might be higher than the code, anyway   see the example below

string s = "ab!@#$#@!";

Good luck. @ marlon-santos

    
01.02.2015 / 03:54