Click here to Skip to main content
13,190,404 members (51,418 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.5K views
Posted 22 Apr 2010

Object reference not set to an instance of an object

, 22 Apr 2010
Rate this:
Please Sign up or sign in to vote.
With C# .Net, many times you may need to typecast an object value to string. And you might have noticed that it throws null reference exception as ”Object reference not set to an instance of an object”. This is a run time exception & will occur mostly when you try to typecast a null value to...
With C# .Net, many times you may need to typecast an object value to string. And you might have noticed that it throws null reference exception as ”Object reference not set to an instance of an object”. This is a run time exception & will occur mostly when you try to typecast a null value to string.

For example:
String userId = Session[“user”].ToString();

Above code will run fine until Session[“user”] have some value but throw exception when it has null value. You can sort out these problem by casting it through Convert.ToString().

For example:
String userId = Convert.ToString(Session[“user”]);

Now your code will not throw any such exception even when it has null value and will cast null value to empty string.

:)

License

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

Share

About the Author

Navin Pandit
Software Developer (Senior)
India India
Save paper, save tree. Stop global warming.
http://www.navinpandit.blogspot.in/p/global-warming.html

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171016.2 | Last Updated 23 Apr 2010
Article Copyright 2010 by Navin Pandit
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid