Click here to Skip to main content
15,867,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I always face this problem. Why is there is an error for the variable? It say that null reference exception could result at runtime. Could someone told me what mistake that I've done and how to recover my mistake back.
Posted

You should always assign a value to your variables. The compiler will complain if you do not do this.

In case you don't want to assign a value you can assign a null.
 
Share this answer
 
Comments
Pravin Patil, Mumbai 20-Sep-11 4:37am    
Good answer..
My 5...
It's because you're declaring a variable 'x' and doing something with it before you've assigned a value to it. If you don't assign a value to a variable it tends to be null. Therefore if you declare a string variable, but don't set it and then call .ToString() on it, you'll get a NullReferenceException.
 
Share this answer
 
Comments
Luiey Ichigo 20-Sep-11 5:25am    
Yeah now i get what you say.
1) I declaring x as DataRow.
2) Then I use For..Next condition to fill the data from database to x and 3) After that I use:-
If (Not (data) is Nothing)

just because I want to check the database and if the data from database is not null, the data will be filled up in the form.
jim lahey 20-Sep-11 5:27am    
Good stuff - defensive coding with null checks will save you a lot of trouble in the long run

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