I am trying to test some code and now visual studio is throwing a null reference exception on the following line:
List<int> liveIds = new List<int>();
I am starting to think that visual studio has old code that it is looking at because no matter how I have tried to declare this line it continues to throw a null reference exception on this line.
Anyone know something that I might be missing?
UPDATE:
ok so I changed out the variable and now I can't get the same error to happen on the previous line. Now it is happening on this line.
Ok so after some testing, things worked once I refactored the code and extracted the following code to a new method:
// remove hospitals that are not currently assigned to someone
hospitalsToCheck.RemoveAll(
h =>
{
return
!currentAssignments.Exists(
a => a.AssignmentGroup.AssignedUnitIds.Intersect(h.Units.Select(u => u.UnitId)).Any());
});
It seems that when I had code that was manipulating the list in the same method that it was defined, that is when I was getting the null reference exception.
Maybe the debugger itself is producing the exception.
I got a very similar situation, where i'm assigning a value from a function and the exception occurs right after executing the function (the Locals window indicates that the function does return a value):
var xmlElement = Serialize(data);
From Disassembly it seems that the exception happens immediately after the assignment, but before the next line of code. I'm guessing this is where some debugger code gets executed:
Screenshot of disassembly
Maybe debugger did not expect for that line of code to be executed, because I altered the execution path with "Set Next Statement" command (moved from the "else" block into this one). Same thing happens if I alter the code (remove the "if") while the debug is running, but the problem does not repeat if I rerun the encompassing procedure after the edit.
Related
I am using PostSharp in C#, for using AOP in my codebase. Recently i've noticed that errors are not being thrown where they are actually thrown, but at the end of the method which was weaved with any aspect. For example, take the sample code below:
public void methodUsingAspects()
{
doSomething1();
doSomethingWhichThrowsError(); //an error is thrown in this method
doSomething2();
} //in visual studio, while debugging, the debugger stops at this line (end of method), not at the actual line the error got thrown.
The error gets shown as if thrown where there is the last curly bracket }. This is quite frustrating especially when the error is thrown quite deep inside the calls the method does.
I can assume why this is done, since the code is changed - but is it possible to somehow leave it work as it was before?
I have the following code inside a method:
string username = (string)context["UserName"];
string un = (string)context["UserName"];
The problem is that the first string "username" is not assigned, while the second does.
To make it more strange, when I have stopped the debugging after the first line and copied the line to the Immediate window, dropping the varible type delaration, it was assigned succesfully.
I have made rebuild all and checked project properties which seems to be OK.
The context variable is a System.Configuration.SettingsContext, which is a hash table. To be more specific, I'm implementing a profile provider, the GetPropertyValues method.
I am using VS 2012 and .NET 4.5
EDIT:
I am using code contract in my project, which uses compile time code injection for runtime checking. I disabled it and all is working well. I'll try to remove contracts one by one to find which one is causing the problem.
What you are seeing is similar to a Code Contracts bug I saw before. I wrote something about it here a few months back. If you have this bug, you probably also have a lambda or LINQ expression in your method that uses username.
For future reference, this is the bug I saw:
I had in the same method a lambda expression capturing a local variable, lets say values, and a Contract.Requires() expression checking something completely unrelated. While debugging that method, the debugger shows in Locals the variable values twice, and reports the value of values always as null even when this is clearly not the case.
To reproduce:
static void Reproduction(string argument)
{
Contract.Requires(argument != null); // <-- (1)
int[] values = new int[1];
Debug.Assert(values != null);
Func<int, bool> d = i => values[i] >= 0; // <-- (2)
Console.WriteLine(values);
}
Put a breakpoint somewhere in this method after the assignment to values and ensure that the method gets called. When the debugger hits the breakpoint, look at the Locals list of Visual Studio for the duplicate variable. Hover the mouse over values to find that it gets reported as being null, something which is clearly not the case.
The problem disappears when removing either the contract (1) or the line with the lambda (2).
After investigating and desabling contracts I found that the problem appears only when runtime contracts checking is enabled and this contract appears:
Contract.Ensures(Contract.Result<System.Configuration.SettingsPropertyValueCollection>() != null);
If I delete this line, the code works, so it looks like code contracts bug, though I couldn't recreate it on a test project.
I'm making a database call with linq and it is returning some results to me. Following is the code for the same:
var resultSet = DataContext.GetList(id);
foreach(var result in resultSet)
{
// do something here with result
}
After this, I try to access again same resultSet as below:
foreach(var result in resultSet)
{
// do something here with result
}
When I'm in debug mode it doesn't throw any error, instead it simply exits debug mode and execution is completed and focus comes back to page.
I want to know why it is not throwing any error in debug mode that I'm using the enumeration for the second time? Am I missing anything? All other errors are throwing exceptions even in the debug mode.
Update: I intentionally didn't do that second calling. It was done by mistake, but it took sometime for me to find that error, if it would have thrown an error, then I would have easily fixed it. This is reason I posted this question here.
Note: I'm doing this throw a ajax call.
I think if you go to Debug (Menu)> Exceptions and check the checkbox under Thrown for Common Language Runtime Errors. Now Visual Studio debugger should break when the error occurs and you should be able to see what's happening.
When debugging C# with Visual Studio, is it possible to see WHICH object reference on a given line of code caused a NullReferenceException?
I have what seems like an odd situation where, occassionally, when running a debug build of an application from Visual Studio, I will get a NullReferenceException at a certain line.
Visual Studio will pop up the exception assistant box pointing at the line, but none of the 3 object references used on that line are null at that point.
The line is:
myClassInstance.myMethod(myOtherClassInstance.IPAddressInstance.ToString());
Both of my class instances are non-null, as is the IPAddress instance (which has its intended value).
Be careful of functions that return null objects. This got me once and isn't very clear within the debugger. Check this out:
public class FooBar
{
public int ReturnInt() { return 0; }
}
public FooBar ReturnNullObject()
{
return null;
}
// Execution code:
int exceptionalInt = ReturnNullObject().ReturnInt();
Edit: according to your edit, make sure IPAddressInstance isn't returning null.
Edit: you might want to break the single line into a couple of lines. This should help.
var ip = myOtherClassInstance.IPAddressInstance;
var ipString = ip.ToString();
myClassInstance.myMethod(ipString);
If you're calling code marked with the [DebuggerNonUserCode] attribute, the problem might be in framework code, not on that line.
In any case, do you have a specific example that you could post?
Set a breakpoint at that line at do "step-into" till you get NRE.
No magic, right? Some code try to dereference null.
Even if you do smth like A.Property.Property2.ToString() as Visual Studio says none of them are null, the problem is then in ToString() method, which lies in an assembly, that Visual Studio do not enter in Debug.
I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception:
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
The line that's throwing it is:
pid = parentCategory.Id;
The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int.
Edit: It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw.
Edit: Relevant snippets of the Category class:
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
Well if anyone wants to look at the full code, it's on Google Code at http://code.google.com/p/chefbook/source/checkout
I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot.
Update: Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.
Based on all the info so far, I think either "the line that's throwing is" is wrong (what makes you think that), or possibly your 'sources' are out of sync with your built assemblies.
This looks impossible, so some 'taken for granted assumption' is wrong, and it's probably the assumption that "the source code you're looking at matches the process you're debugging".
When things look right on the surface then it's likely something you would dismiss. Are you 350% positive that your DLL/PDB matches your source code thus giving you the right line?
Try manually deleting your assemblies and run whatever it is you're running. Does it fail as it should?
Try cleaning out your solution and recompiling. Copy the assemblies to wherever and run it again. Does it work this time? Null ref at the same spot?
Debug the surrounding lines for values you expect. parentCategory, etc. should match what you think.
Modify the code by throwing an exception. Do the stack trace lines match exactly the lines in your code?
I've had some extremely mind-boggling experiences just like this because one of my assumptions was wrong. Typical is a stale assembly. Question all assumptions.
What doesn't make sense, though, is that the OP states that the console.writeline outputs a valid int and it calls the same property as the line where he states the error is being thrown.
A stacktrace would be helpful, or being able to look at the actual unit test.
Yes, could we see the code of the category class .. in particular the Id property? Assuming the Id property is an int (and not a nullable int), the get method must be accessing a NULL object.
Id could be a nullable int type (int?) with no value, however I feel that the property Id must be doing more than just returning an int, and something inside that is null.
EDIT Your edit reveals this is more than peculiar, could you supply us with a stack trace?
I'm not an expert on C#, and am not sure if it makes a difference, but are you debugging in Debug mode, or Release mode? If you're in release mode, the line that your IDE is pointing to and the line the problem is actually on may be different (I know this is the case in C++ when using Visual Studio)
I'd have to agree with Brian... Maybe you're using outdated .pdbs and the code you're seen on debug mode does not comply with the code actually being debugged.
Try cleaning the project, and rebuilding it in debug mode.
Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.