C# null coalescing operator returning null

前端 未结 6 2335
小鲜肉
小鲜肉 2021-02-14 10:44

Recently my co-worker showed me a block of code that was not working correctly:

public class SomeClass
{
    private IList _categories;

    publ         


        
相关标签:
6条回答
  • 2021-02-14 11:09

    (1) DoSomethingElse() could be setting the _categories field to null, before the error appears. A way to test this is to make the _categories field readonly. If that is the error, then you will get a compiler error that a readonly field cannot be used as an assignment target.
    (2) Your _categories field is being set via some other function in a different thread. Either way, the following should fix your problem, or at least make it clear where it is.

    public class SomeClass
    {
        private static readonly object CategoryListLock = new object();
        private readonly List<Category> _categories = new List<Category>();
        private bool _loaded = false;
    
        public void SetCategories()
        {
            if(!_loaded)
            {
                lock(CategoryListLock)
                {
                    if(!_loaded)
                    {
                        _categories.AddRange(GetCategories());
                        _loaded = true;
                    }
                }
            }
            DoSomethingElse();
        }
    
        public IList<Category> GetCategories()
        {
            return RetrieveCategories().Select(Something).ToList();
        }
    }
    

    **After seeing your edit, it looks like you have two different fields that are IList<Category> _categories. It doesn't make sense that the _categories field in the CategoryListControl is null, but the static _categories in the CategoryRepository class looks like it should be null based on what you posted. Perhaps you are getting confused about which field is throwing the error. I understand that the line is called in the CategoryListControl, so your error will say it is in the CategoryListControl class, but the actual exception could be from the GetChildren() method, which attempts to make a children list from a null list). Since the fields are named the same thing, it is easy to see how they could get confused. Test this by making the _categories field in CategoryRepository a readonly initialized field.

    Even if the _categories field in the CategoryRepository is not always null, it could be subject to any of the threading concerns that I explained how to fix for the Control class**

    ItTo make sure you are debugging the correct _categories field, try this.

        _categories = GetCategories() ?? new List<Category>();
        if(_categories == null){
              throw new Exception("WTF???");
         }
        DoSomethingElse();
    

    If you don't get the Exception with "WTF???" then you know the source of the error is elsewhere.

    And, regarding the Linq extensions: Neither Where() nor ToList() can return null. Both methods will throw an ArgumentNullException if any parameters are null. I checked this with reflector.

    Please let us know what results you get with this. I'm curious now too.

    0 讨论(0)
  • 2021-02-14 11:18

    If you sure that its because of threading issue, then use the lock keyword. I believe this should work.

    public class SomeClass
    {
        private IList<Category> _categories;
    
        public void SetCategories()
        {
            lock(this) 
            {
              _categories = GetCategories() ?? new List<Category>();
              DoSomethingElse();
            }
        }
    
        public IList<Category> GetCategories()
        {
            return RetrieveCategories().Select(Something).ToList();
        }
    }
    
    0 讨论(0)
  • 2021-02-14 11:22

    This could happen because you have optimizations turned on - in that case the assignment may be delayed for as long as the compiler can demonstrate that doing so doesn't change the result. Of course, this looks weird in the debugger, but it's perfectly OK.

    0 讨论(0)
  • 2021-02-14 11:24

    Try doing a clean build. Build menu-> clean, then debug again. The code itself is fine.

    0 讨论(0)
  • 2021-02-14 11:28

    This could be a problem with the debugger rather than with the code. Trying printing out the value or doing a null check after the statement with the coalesce operator.

    0 讨论(0)
  • 2021-02-14 11:30

    The null-coalescing operator is not broken. I use it in a similar manner all the time quite successfully. Something else is going on.

    0 讨论(0)
提交回复
热议问题