"Object reference not set to an instance of an object" error is one of the most common errors when developing .NET applications. Here are the five most common mistakes that result in this error. In this article, also learn how to fix errors, and object references not set to an instance of an object.
Why does this error happen?
This error's description speaks for itself but when you do not have much experience in development, it is very difficult to understand. So, this error description says that an object that is being called to get or set its value has no reference. This means that you are trying to access an object that was not instantiated.
Why should I know this?
This is important in order to avoid runtime errors that could possibly expose your sensitive data and this could lead to a vulnerability breach. Vulnerability breaches are usually used by hackers for a cyber attack to steal your data or to take your server offline.
How to avoid exposing code and entities?
You must always wrap code that could possibly throw an exception inside try-catch blocks. There are others security approaches that you can use to protect your data that can be found here.
Common mistakes
Objects used in this sample.
Controller
public class HomeController : Controller
{
SampleObj sampleObj;
SampleChildObj sampleChild;
List<string> lstSample;
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View();
}
public IActionResult NewObject()
{
sampleChild.Item2 = "error";
return View();
}
public IActionResult ConditionStatement()
{
if (true == false)
{
sampleChild = new SampleChildObj();
sampleChild.Item2 = "";
}
else
sampleChild.Item2 = "error";
return View();
}
public IActionResult ObjectInsideObject()
{
sampleObj = new SampleObj();
sampleObj.ChildObj.Item2 = "error";
return View();
}
public IActionResult AddInNullList()
{
lstSample.Add("error");
return View();
}
}
Classes
public class SampleObj
{
public string Item1 { get; set; }
public SampleChildObj ChildObj { get; set; }
}
public class SampleChildObj
{
public string Item2 { get; set; }
}
Aman PanchalPosted Jun 13, 2020, 10:03 PM
Tried to explain in simple words in my article also https://elearning.onlinehaikya.com/blogs/CsharpBlogs/object-reference-not-set-to-an-instance-of-an-object
Dipa MehtaPosted Mar 7, 2020, 7:38 AM
Thank for sharing this article.
Raju PaladiyaPosted Mar 6, 2020, 11:27 PM
Nicely explained