Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i make a array list with below code:
HTML
ArrayList aa = new ArrayList();

and fill this with this code:
HTML
aa.Add(fiststquery.getUserName(user, pass));

and now i want check value of arraylist with this code:
HTML
if(aa[0]).ToString()==null)
,but this dosn't work and send this error:
"Object reference not set to an instance of an object"
Posted

Try to debug through the getUserName method. Mae sure it is returning a value.
If fiststquery.getUserName(user, pass) is returning null, you are adding null to aa.

As a result, when you do aa[0].toString(), you are trying to convert a null to string - which throws an error.

An alternate way could be to use if (aa[0] == null) directly.
You don't need the ToString method at all.

Convert.ToString() can also be used. This will not throw an error when the sting to be converted is null.
 
Share this answer
 
Comments
VJ Reddy 15-Apr-12 3:07am    
Good answer. 5!
Abhinav S 15-Apr-12 3:17am    
Thanks.
Mehdi Gholam 15-Apr-12 5:16am    
My 5!

obj.ToString() is a source of many bugs when obj is null. I usually use (""+obj) which guarantees a string even if obj is null.
Abhinav S 15-Apr-12 11:09am    
Thanks. Convert.ToString() could also be an option.
Just to add a bit more to Abhinav's reply:

Before any checks, you can check the size of the array by using Count. In this way you will be pretty sure that the index is valid (i mean if count is more that 0, then aa will have at least one non-null object]
 
Share this answer
 
Comments
VJ Reddy 15-Apr-12 3:07am    
Nice addition. 5!
Lakamraju Raghuram 15-Apr-12 3:10am    
(:-
VJ Reddy 15-Apr-12 4:59am    
Is my comment not appropriate, out of curiosity, as your expression is (:- which is a blank expression, as given here http://www.cool-smileys.com/text-emoticons.
Thank you.
Lakamraju Raghuram 15-Apr-12 11:35am    
Oh is it?
Then I am very poor at these SMS type of symbols.
Thank you for your appreciation and I want to convey the same by that symbol. My bad if it is wrong.
VJ Reddy 16-Apr-12 0:26am    
No problem.
Thank you for the response.

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