Click here to Skip to main content
13,255,238 members (50,875 online)
Rate this:
 
Please Sign up or sign in to vote.
Hi Comunity,

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

Not Working
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
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 11-Jan-13 8:38am
Updated 7-Nov-16 6: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
HashamAhmad 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
Mika 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.
Sergey Alexandrovich Kryukov 11-Jan-13 14:35pm
   
You are right, it could not be so.
I suspect this is the situation I'm familiar with: messed up debugging session — please see my answer.
—SA
jibesh 11-Jan-13 14:01pm
   
int a=0; never throw exception it might be something else can you put a try catch and copy the exception stack here.

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

copy paste what you get in message string.

You can use Improve Question link to modify your question
Sergey Alexandrovich Kryukov 11-Jan-13 14:35pm
   
You are right, it could not be so. I suspect this is the situation I'm familiar with: messed up debugging session — please see my answer.
—SA
karnayanar 11-Jan-13 14:22pm
   
just "Object reference not set to an object instance." at the allocation.
karnayanar 11-Jan-13 14:23pm
   
I tried following with the debugger step by step:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
int b; //debugger shows -> b = 0; a = "" is NULL
b = 1; //debugger shows -> b = 1; a = "" is NULL
int a; //debugger shows -> b = 0; a = "" is NULL
a = 1; //<- throws NullReference Exception.
a = Int32.Parse( textBoxWagenID.Text);
m_EntityContext.Foo.Where( p => p.Bar == a).First();
}

This is interesting.

So the struct int is NULL even though the type ist not int?.

Can it have something to do with the fact that the variable is used in the query?
When i not use the var a in the Query it works fine.
Philippe Mori 7-Nov-16 22:19pm
   
Which version of Visual Studio? Which debugger engine? And are you using Edit-and-continue feature? Have you installed all updates?

I have seen case where editing code while debugging cause that kind of behavior... So the first thing to try, it to stop debugging, then build solution and restart debugging.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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
  Permalink  
v3
Comments
Mika Wendelius 11-Jan-13 14:47pm
   
Very true.
Sergey Alexandrovich Kryukov 11-Jan-13 14:49pm
   
Thank you, Mika.
—SA
Marcus Kramer 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.
Marcus Kramer 11-Jan-13 15:35pm
   
Absolutely.
karnayanar 11-Jan-13 15:00pm
   
I agree.
But i tried it on different Computers allways with the same result.
jibesh 11-Jan-13 15:08pm
   
did you try to catch the exception? since you said its happening all the time we would like to see the exception stack too. care to past here?
Sergey Alexandrovich Kryukov 11-Jan-13 17:22pm
   
Well, that's worse...
karnayanar 11-Jan-13 15:34pm
   
ExceptionStack:

bei FooManager.Form1.textBox1_KeyDown(Object sender, KeyEventArgs e) in C:\FooManager\Form1.cs:Zeile 226.
bei System.Windows.Forms.Control.OnKeyDown(KeyEventArgs e)
bei System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
bei System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
bei System.Windows.Forms.Control.WndProc(Message& m)
bei System.Windows.Forms.TextBoxBase.WndProc(Message& m)
bei System.Windows.Forms.TextBox.WndProc(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
bei System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Sergey Alexandrovich Kryukov 11-Jan-13 17:23pm
   
Strange stack. Isn't it upside down? Where do you think is the top of it? That is, what is called first?
—SA
karnayanar 11-Jan-13 18:11pm
   
thats what the VS2010 put out as Stack.
Sergey Alexandrovich Kryukov 11-Jan-13 18:40pm
   
OK, maybe. Is it the output of Exception.Stack or..?
—SA
Andreas Gieriet 11-Jan-13 20:29pm
   
My 5!
Debugging a KeyDown event is not advised anyways.
Cheers
Andi
Sergey Alexandrovich Kryukov 11-Jan-13 20:32pm
   
Thank you, Andi.
—SA
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

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:
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.
  Permalink  
v3
Comments
karnayanar 11-Jan-13 22:29pm
   
Thanks Andi.
Andreas Gieriet 12-Jan-13 9:05am
   
You are welcome.
Andi
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 6

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:
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:
ai = assetList.Find(Function(p) p.AssetId = x)

Obvious work-around is to change to loop
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
  Permalink  
Comments
NotPolitcallyCorrect 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web04 | 2.8.171114.1 | Last Updated 7 Nov 2016
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100