Reputation: 1965
Recently my co-worker showed me a block of code that was not working correctly:
public class SomeClass
{
private IList<Category> _categories;
public void SetCategories()
{
_categories = GetCategories() ?? new List<Category>();
DoSomethingElse();
}
public IList<Category> GetCategories()
{
return RetrieveCategories().Select(Something).ToList();
}
}
(I am aware that the operator is superfluous since the linq ToList will always return a list, but that is how the code was set up).
The problem was that _categories was null. In the debugger, setting a breakpoint on _categories = GetCategories() ?? new List<Category>()
, then stepping over to DoSomethingElse(), _categories would still be null.
Directly setting _categories to GetCategories() worked fine. Splitting the ?? in to a full if statement worked fine. The null coalescing operator did not.
It is an ASP.NET application, so a different thread could possibly be interfering, but it was on his machine, with only him connected in a browser. _cateogories is not static, or anything.
What I'm wondering is, how could this possibly happen?
Edit:
Just to add to the bizarreness, _categories
is never set anywhere besides that function (apart from initializing the class).
The exact code is like so:
public class CategoryListControl
{
private ICategoryRepository _repo;
private IList<Category> _categories;
public override string Render(/* args */)
{
_repo = ServiceLocator.Get<ICategoryRepository>();
Category category = _repo.FindByUrl(url);
_categories = _repo.GetChildren(category) ?? new List<Category>();
Render(/* Some other rendering stuff */);
}
}
public class CategoryRepository : ICategoryRepository
{
private static IList<Category> _categories;
public IList<Category> GetChildren(Category parent)
{
return _categories.Where(c => c.Parent == parent).ToList<Category>();
}
}
Even it GetChildren magically returned null, CategoryListControl._categories still should never, ever be null. GetChildren should also never, ever return null because of IEnumerable.ToList().
Edit 2:
Trying out @smartcaveman's code, I found out this:
Category category = _repo.FindByUrl(url);
_categories = _repo.GetChildren(category) ?? new List<Category>();
_skins = skin; // When the debugger is here, _categories is null
Renderer.Render(output, _skins.Content, WriteContent); // When the debugger is here, _categories is fine.
As well, when testing if(_categories == null) throw new Exception()
, _categories was null on the if statement, then stepping over the exception was not thrown.
So, it seems like this is a debugger bug.
Upvotes: 10
Views: 2171
Reputation: 48066
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.
Upvotes: 1
Reputation: 42246
(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.
Upvotes: 1
Reputation: 44066
The null-coalescing operator is not broken. I use it in a similar manner all the time quite successfully. Something else is going on.
Upvotes: 2
Reputation: 51309
Try doing a clean build. Build menu-> clean, then debug again. The code itself is fine.
Upvotes: 1
Reputation: 3430
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();
}
}
Upvotes: 1
Reputation: 36
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.
Upvotes: 2