简体   繁体   中英

C# static methods & attributes: Object reference not set to an instance of an object

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 _regexCategory is null when you initialize _allRegexes .

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

(Quoted from C# Language Specification Version 4.0 - 10.5.5.1 Static field initialization)

This leads to _allRegexes becoming an array that contains a single null element, ie new Regex[]{null} .

This means you can fix your code by putting _regexCategory before _allRegexes in your class.

It should be

    private static Regex _regexCategory = new Regex(@"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", RegexOptions.IgnoreCase);
    private static Regex[] _allRegexes = { _regexCategory };

In your code the IL will load _regexCategory into _allRegexes which is NULL because the IL had never initialized it..

It initalizes when you instantiate _regexCategory with new keyword

This code works without NRE

internal class Utils
{
    private static Regex _regexCategory = new Regex(
        @"(?<name>c(ategory){0,1}):(?<value>([^""\s]+)|("".+""))\s*", 
        RegexOptions.IgnoreCase);
    private static Regex[] _allRegexes = { _regexCategory };


    public static string ExtractKeyWords(string queryString)
    {
        if (string.IsNullOrWhiteSpace(queryString))
            return null;

        //change it to your needs, I just made it compile
        return _allRegexes[0].Match(queryString).Value;
    }
}    

class Program
{
    static void Main(string[] args)
    {
        string result = Utils.ExtractKeyWords("foo");
    }
}

I believe the problem is in the order in which parameters are getting initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM