Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Object reference not set to an instance of an object

0.00/5 (No votes)
22 Apr 2010 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here