I have the following code that exhibits a strange problem:
var all = new FeatureService().FindAll();
System.Diagnostics.Debug.Assert(all != null, "FindAll must not return null");
System.Diagnostics.Debug.WriteLine(all.ToString()); // throws NullReferenceException
The signature of the FindAll method is:
public List<FeatureModel> FindAll()
Stepping through the code I have confirmed that the return value from FindAll is not null, and as you can see from the Assert, the "all" variable is not null, yet in the following line it appears to be null.
The issue is not specific to failing when the ToString() method is called. I simplified it down to this reproducible example while trying to trace the root cause.
This may be a clue: in the debugger, the variable "all" appears in the Locals window with a value of "Cannot obtain value of local or argument 'all' as it is not available at this instruction pointer, possibly because it has been optimized away."
I considered trying one of the approaches documented elsewhere for disabling code optimization but this wouldn't really solve the problem since the release version of the code will still be optimized.
I am using Visual Studio 2010 with .NET 4.0.
Any thoughts?
Thanks, Gary
UPDATE: per request, here is the entire method:
protected override List<FeatureModel> GetModels() {
var all = new FeatureService().FindAll();
var wr = new WeakReference(all);
System.Diagnostics.Debug.Assert(all != null, "FindAll must not return null");
System.Diagnostics.Debug.WriteLine(wr.IsAlive);
System.Diagnostics.Debug.WriteLine(all.ToString()); // throws NullReferenceException
return all;
}
As an FYI, the original implementation was simply:
protected override List<FeatureModel> GetModels() {
return new FeatureService().FindAll();
}
I originally encountered the null exception in the calling method. The code I posted was after tracing the issue for a while.
UPDATE #2: As requested, here is the stack trace from the exception:
at FeatureCrowd.DomainModel.FeatureSearch.GetModels() in C:\Users\Gary\Documents\Visual Studio 2010\Projects\FeatureCrowd\FeatureCrowd.DomainModel\FeatureSearch.cs:line 32
at FeatureCrowd.DomainModel.FeatureSearch.CreateIndex() in C:\Users\Gary\Documents\Visual Studio 2010\Projects\FeatureCrowd\FeatureCrowd.DomainModel\FeatureSearch.cs:line 42
at FeatureCrowd.DomainModel.FeatureService.CreateSearchIndex() in C:\Users\Gary\Documents\Visual Studio 2010\Projects\FeatureCrowd\FeatureCrowd.DomainModel\FeatureService.cs:line 100
at Website.MvcApplication.BuildLuceneIndexThread(Object sender) in C:\Users\Gary\Documents\Visual Studio 2010\Projects\FeatureCrowd\FeatureCrowd.Website\Global.asax.cs:line 50
at Website.MvcApplication.Application_Start() in C:\Users\Gary\Documents\Visual Studio 2010\Projects\FeatureCrowd\FeatureCrowd.Website\Global.asax.cs:line 61