Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.18/5 (3 votes)
Hi Comunity,

i have an Problem.
Why it crashes here with NullReferenceException?

Not Working
C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   int a = 0; //<- throwing NullReference Exception. Why???
   a = Int32.Parse( textBoxWagenID.Text);
   m_EntityContext.Foo.Where( p => p.Bar == a).First();
}


Working
C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   DoSth();
}

private void DoSth()
{
   int a = 0; //<- not throwing NullReference Exception!!!!
   a = Int32.Parse( textBoxWagenID.Text);
   m_EntityContext.Foo.Where( p => p.Bar == a).First();
}


Is this not the Same??
Posted
Updated 7-Nov-16 5:18am
Comments
Florian Rappl 11-Jan-13 13:49pm    
Are you sure this is the problem? I highly doubt it.

An integer will never give you a null reference, since it is a struct and therefore allocated on the stack (i.e. no pointer). Even unassigned any struct will already have a value. The only way to produce this is to use a variable of type int?. This is not the case.

However, I've seen codes throwing errors on other locations. This might be the case here.
Sergey Alexandrovich Kryukov 11-Jan-13 14:33pm    
I think you are quite right. I suspect the reason is that the debugging session is messed up. There are relatively rare situations when the debugger gets confused.
Please see my answer.
—SA
[no name] 11-Jan-13 13:52pm    
just tried this on my machine, its working fine ... there must be something else
Sergey Alexandrovich Kryukov 11-Jan-13 14:34pm    
You are right. I suspect this is the situation I'm familiar with: messed up debugging session — please see my answer.
—SA
Wendelius 11-Jan-13 13:52pm    
Are you sure that the exception is really fired in the int declaration? The following lines are much more potential.

If my eyes do not betray me, I am sure you do not present the situation correctly. The code variants are functionally fully equivalent, but this is not even the main point. The point is: the code line you commented cannot throw an exception in principle.

What happens can be a completely different thing. There are some cases, where the debugger shows incorrect code lines. I don't know how to reproduce it, but it always happens after long and spaghetti-like session of debugging with some modifications in the code. Maybe, the results of previous compilations are not cleared properly.

So, here is the advice: close Visual Studio and clean all the projects. Better yet, remove all existing "obj" sub-directories; usually this is quite enough. Run Visual Studio again and perform debugging very accurately, not modifying your code. This way, you will see what really happens.

—SA
 
Share this answer
 
v3
Comments
Wendelius 11-Jan-13 14:47pm    
Very true.
Sergey Alexandrovich Kryukov 11-Jan-13 14:49pm    
Thank you, Mika.
—SA
fjdiewornncalwe 11-Jan-13 14:50pm    
I have seen the incorrect highlighted row in the debugger at times as well. I couldn't tell you how I produced it, but usually a clean restart or reboot fixed the situation.
Sergey Alexandrovich Kryukov 11-Jan-13 14:52pm    
This is almost what I said, but usually reboot is not needed, but removing of temporary files (just "obj") can rather help. And it, in turn, needs Visual Studio to be restarted. Agree?
—SA
Jibesh 11-Jan-13 15:06pm    
Right. thats the odd behavior of Visual Studio. if you see something weird with visual studio dont think twice restart!! is the most possible solution.
My suspicion:

  1. your KeyDown event handler is triggered when the Text property is still null (i.e. the event is registered before the Text property is set)
  2. int.Parse(...) is throwing an exception if the text is null.


Do the following:
C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   int a;
   if (textBoxWagenID != null && int.TryParse(textBoxWagenID.Text ?? string.Empty, out a))
   {
      m_EntityContext.Foo.Where( p => p.Bar == a).First();
   }
}


And again: I would not debug this as a KeyDown/KeyUp event! You would trigger an event storm while debugging...

Cheers
Andi

PS: In Visual Studio, turn on in the debuging --> Exceptions dialog the .Net runtime exception to stop on throwing. You will be promptet the exact object that causes the problem. In this case for sure either textBoxWagenID or its Text property.
 
Share this answer
 
v3
Comments
karnayanar 11-Jan-13 22:29pm    
Thanks Andi.
Andreas Gieriet 12-Jan-13 9:05am    
You are welcome.
Andi
Unfortunately none of the above solved the same problem for me. I eventually built a new project with minimal dependencies, and still got the error with the same integer variable, but after commenting out various sections of code was able to track down to use of lambda expression in list(of T).Find which was using the integer variable. Aha - original problem above is using a lambda expression!

To illustrate, the problematic variable is "x". Integers before and after did not cause problems. I could step past this variable (x) after commenting out everywhere that it was subsequently used within the sub:
VB.NET
Public Sub ProcessNotifications()
        Try

            Dim assetList As New List(Of AssetInfo)

            Using reader As SqlDataReader = _dbUtils.GetNotificationSummary()

                If reader.HasRows Then

                    Dim notificationId As Integer = 0
                    Dim x As Integer = 0
                    Dim skywaveId As Integer = 0
                    Dim ai As AssetInfo = Nothing
                    Dim msg As MsgResponse = Nothing

As I uncommented different sections, the culprit further down was:
VB.NET
ai = assetList.Find(Function(p) p.AssetId = x)

Obvious work-around is to change to loop
VB.NET
for i = 0 to assetList.count - 1
Seems like karnayanar (11-Jan-13 14:23pm above) was thinking about this too.

Would be nice to know why it is happening.... collections.generic is part of mscorlib which is part of .Net project, and all of my referenced projects are using same .Net framework (4.5.1).

Anyone else have any ideas?

Regards

Tim
 
Share this answer
 
Comments
[no name] 7-Nov-16 11:29am    
You should ask your own question about your code instead of posting your question as a solution to someone else's question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900