Friday, 16 September 2011

Object reference not set to an instance of an object. - ASP .Net Mvc 3

So if you are searching for this error then my first guess is that you are pretty new to MVC or infact .Net framework. Well no need to worry, this is the error you will se the most in your future life as ASP .Net MVC programmer.

What does it mean?

"Object reference not set to an instance of an object." simply means
that there is a null object in your code, which is being accessed. .Net compiler won't know what type of object it is and it won't know what to extract when the object itself is null.

for all the objects before accessing them you need to either initialize them by using constructor method or assign them a value

obj = new Object() or obj = Value

It's like you want to get on a branch of Tree, when the tree itself doesn't exist.


Please either Debug your code or track the null object in the Error Trace. You can also use stack trace to find what exactly is setting your object as null.

Just Choose Debug->window->Call stack  while running your solution in debug mode.

Here are some tips to save yourself from this kind of errors in future

If object is a string, always use String.IsNullOrEmpty({string}) before accessing it.

 For Guid objects you can use Guid.hasValue, or object == Guid.Empty

you can also use TryParse for converting strings to int, double or float.
 For other objects a simple way is to just use

if(obj==null)
{
//set default value obj = new Object() or obj = defaultValue
//or threw new exception
}
Remember, you should always try to catch null objects and throw exception or set a default value if needed.

The earliest you catch any null object better will be your code and less chances of bugs.

please leave comments if you have any questions or suggestions

Alert : ASP.Net MVC 4 is now available for free download , please click here to download MVC 4

No comments:

Post a Comment