I’m using static methods and attributes, when I call a static method, I get a NullReferenceException.
sample class:
internal class Utils
{
private static Regex[] _allRegexes = { _regexCategory };
private static Regex _regexCategory = new Regex(@"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", RegexOptions.IgnoreCase);
public static string ExtractKeyWords(string queryString)
{
if (string.IsNullOrWhiteSpace(queryString))
return null;
_allRegexes[0];//here: _allRegexes[0]==null throw an exception
}
}
cause:
_allRegexes[0]==null
I can’t figure it out why this happens, I think _allRegexes should be initialized when I call that method.
Can anybody explain it?
Static fields get initialized in declaration order. This means
_regexCategoryisnullwhen you initialize_allRegexes.(Quoted from C# Language Specification Version 4.0 – 10.5.5.1 Static field initialization)
This leads to
_allRegexesbecoming an array that contains a singlenullelement, i.e.new Regex[]{null}.This means you can fix your code by putting
_regexCategorybefore_allRegexesin your class.