Object reference not set to an instance of an object как исправить torrent

Причина

Вкратце

Вы пытаетесь воспользоваться чем-то, что равно null (или Nothing в VB.NET). Это означает, что либо вы присвоили это значение, либо вы ничего не присваивали.

Как и любое другое значение, null может передаваться от объекта к объекту, от метода к методу. Если нечто равно null в методе «А», вполне может быть, что метод «В» передал это значение в метод «А».

Остальная часть статьи описывает происходящее в деталях и перечисляет распространённые ошибки, которые могут привести к исключению NullReferenceException.

Более подробно

Если среда выполнения выбрасывает исключение NullReferenceException, то это всегда означает одно: вы пытаетесь воспользоваться ссылкой. И эта ссылка не инициализирована (или была инициализирована, но уже не инициализирована).

Это означает, что ссылка равна null, а вы не сможете вызвать методы через ссылку, равную null. В простейшем случае:

string foo = null;
foo.ToUpper();

Этот код выбросит исключение NullReferenceException на второй строке, потому что вы не можете вызвать метод ToUpper() у ссылки на string, равной null.

Отладка

Как определить источник ошибки? Кроме изучения, собственно, исключения, которое будет выброшено именно там, где оно произошло, вы можете воспользоваться общими рекомендациями по отладке в Visual Studio: поставьте точки останова в ключевых точках, изучите значения переменных, либо расположив курсор мыши над переменной, либо открыв панели для отладки: Watch, Locals, Autos.

Если вы хотите определить место, где значение ссылки устанавливается или не устанавливается, нажмите правой кнопкой на её имени и выберите «Find All References». Затем вы можете поставить точки останова на каждой найденной строке и запустить приложение в режиме отладки. Каждый раз, когда отладчик остановится на точке останова, вы можете удостовериться, что значение верное.

Следя за ходом выполнения программы, вы придёте к месту, где значение ссылки не должно быть null, и определите, почему не присвоено верное значение.

Примеры

Несколько общих примеров, в которых возникает исключение.

Цепочка

ref1.ref2.ref3.member

Если ref1, ref2 или ref3 равно null, вы получите NullReferenceException. Для решения проблемы и определения, что именно равно null, вы можете переписать выражение более простым способом:

var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member

Например, в цепочке HttpContext.Current.User.Identity.Name, значение может отсутствовать и у HttpContext.Current, и у User, и у Identity.

Неявно

public class Person {
    public int Age { get; set; }
}
public class Book {
    public Person Author { get; set; }
}
public class Example {
    public void Foo() {
        Book b1 = new Book();
        int authorAge = b1.Author.Age; // Свойство Author не было инициализировано
                                       // нет Person, у которого можно вычислить Age.
    }
}

То же верно для вложенных инициализаторов:

Book b1 = new Book { Author = { Age = 45 } };

Несмотря на использование ключевого слова new, создаётся только экземпляр класса Book, но экземпляр Person не создаётся, поэтому свойство Author остаётся null.

Массив

int[] numbers = null;
int n = numbers[0]; // numbers = null. Нет массива, чтобы получить элемент по индексу

Элементы массива

Person[] people = new Person[5];
people[0].Age = 20; // people[0] = null. Массив создаётся, но не
                    // инициализируется. Нет Person, у которого можно задать Age.

Массив массивов

long[][] array = new long[1][];
array[0][0] = 3; // = null, потому что инициализировано только первое измерение.
                 // Сначала выполните array[0] = new long[2].

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames = null.
                               // Экземпляр словаря не создан.

LINQ

public class Person {
    public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Исключение бросается здесь, хотя создаётся
                                  // строкой выше. p = null, потому что
                                  // первый добавленный элемент = null.

События

public class Demo
{
    public event EventHandler StateChanged;

    protected virtual void OnStateChanged(EventArgs e)
    {        
        StateChanged(this, e); // Здесь бросится исключение, если на
                               // событие StateChanged никто не подписался
    }
}

Неудачное именование переменных

Если бы в коде ниже у локальных переменных и полей были разные имена, вы бы обнаружили, что поле не было инициализировано:

public class Form1 {
    private Customer customer;

    private void Form1_Load(object sender, EventArgs e) {
        Customer customer = new Customer();
        customer.Name = "John";
    }

    private void Button_Click(object sender, EventArgs e) {
        MessageBox.Show(customer.Name);
    }
}

Можно избежать проблемы, если использовать префикс для полей:

private Customer _customer;

Цикл жизни страницы ASP.NET

public partial class Issues_Edit : System.Web.UI.Page
{
    protected TestIssue myIssue;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Выполняется только на первой загрузке, но не когда нажата кнопка
            myIssue = new TestIssue(); 
        }
    }
    
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        myIssue.Entry = "NullReferenceException здесь!";
    }
}

Сессии ASP.NET

// Если сессионная переменная "FirstName" ещё не была задана,
// то эта строка бросит NullReferenceException.
string firstName = Session["FirstName"].ToString();

Пустые вью-модели ASP.NET MVC

Если вы возвращаете пустую модель (или свойство модели) в контроллере, то вью бросит исключение при попытке доступа к ней:

// Controller
public class Restaurant:Controller
{
    public ActionResult Search()
    {
         return View();  // Модель не задана.
    }
}

// Razor view 
@foreach (var restaurantSearch in Model.RestaurantSearch)  // Исключение.
{
}

Способы избежать

Явно проверять на null, пропускать код

Если вы ожидаете, что ссылка в некоторых случаях будет равна null, вы можете явно проверить на это значение перед доступом к членам экземпляра:

void PrintName(Person p) {
    if (p != null) {
        Console.WriteLine(p.Name);
    }
}

Явно проверять на null, использовать значение по умолчанию

Методы могут возвращать null, например, если не найден требуемый экземпляр. В этом случае вы можете вернуть значение по умолчанию:

string GetCategory(Book b) {
    if (b == null)
        return "Unknown";
    return b.Category;
}

Явно проверять на null, выбрасывать своё исключение

Вы также можете бросать своё исключение, чтобы позже его поймать:

string GetCategory(string bookTitle) {
    var book = library.FindBook(bookTitle);  // Может вернуть null
    if (book == null)
        throw new BookNotFoundException(bookTitle);  // Ваше исключение
    return book.Category;
}

Использовать Debug.Assert для проверки на null для обнаружения ошибки до бросания исключения

Если во время разработки вы знаете, что метод может, но вообще-то не должен возвращать null, вы можете воспользоваться Debug.Assert для быстрого обнаружения ошибки:

string GetTitle(int knownBookID) {
    // Вы знаете, что метод не должен возвращать null
    var book = library.GetBook(knownBookID);  

    // Исключение будет выброшено сейчас, а не в конце метода.
    Debug.Assert(book != null, "Library didn't return a book for known book ID.");

    // Остальной код...

    return book.Title; // Не выбросит NullReferenceException в режиме отладки.
}

Однако эта проверка не будет работать в релизной сборке, и вы снова получите NullReferenceException, если book == null.

Использовать GetValueOrDefault() для Nullable типов

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Отобразит значение по умолчанию, потому что appointment = null.

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Отобразит дату, а не значение по умолчанию.

Использовать оператор ?? (C#) или If() (VB)

Краткая запись для задания значения по умолчанию:

IService CreateService(ILogger log, Int32? frobPowerLevel)
{
    var serviceImpl = new MyService(log ?? NullLog.Instance);
    serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}

Использовать операторы ?. и ?[ (C# 6+, VB.NET 14+):

Это оператор безопасного доступа к членам, также известный как оператор Элвиса за специфическую форму. Если выражение слева от оператора равно null, то правая часть игнорируется, и результатом считается null. Например:

var title = person.Title.ToUpper();

Если свойство Title равно null, то будет брошено исключение, потому что это попытка вызвать метод ToUpper на значении, равном null. В C# 5 и ниже можно добавить проверку:

var title = person.Title == null ? null : person.Title.ToUpper();

Теперь вместо бросания исключения переменной title будет присвоено null. В C# 6 был добавлен более короткий синтаксис:

var title = person.Title?.ToUpper();

Разумеется, если переменная person может быть равна null, то надо проверять и её. Также можно использовать операторы ?. и ?? вместе, чтобы предоставить значение по умолчанию:

// обычная проверка на null
int titleLength = 0;
if (title != null)
    titleLength = title.Length;

// совмещаем операторы `?.` и `??`
int titleLength = title?.Length ?? 0;

Если любой член в цепочке может быть null, то можно полностью обезопасить себя (хотя, конечно, архитектуру стоит поставить под сомнение):

int firstCustomerOrderCount = customers?[0]?.Orders?.Count() ?? 0;

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

  1. public class HomeController : Controller  
  2.    {  
  3.        SampleObj sampleObj;  
  4.        SampleChildObj sampleChild;  
  5.        List<string> lstSample;  
  6.        public IActionResult Index()  
  7.        {  
  8.            return View();  
  9.        }  
  10.   
  11.        public IActionResult About()  
  12.        {  
  13.            ViewData[«Message»] = «Your application description page.»;  
  14.   
  15.            return View();  
  16.        }  
  17.   
  18.        public IActionResult Contact()  
  19.        {  
  20.            ViewData[«Message»] = «Your contact page.»;  
  21.   
  22.            return View();  
  23.        }  
  24.   
  25.        public IActionResult Error()  
  26.        {  
  27.            return View();  
  28.        }  
  29.        public IActionResult NewObject()  
  30.        {  
  31.            sampleChild.Item2 = «error»;  
  32.            return View();  
  33.        }  
  34.   
  35.        public IActionResult ConditionStatement()  
  36.        {  
  37.            if (true == false)  
  38.            {  
  39.                sampleChild = new SampleChildObj();  
  40.                sampleChild.Item2 = «»;  
  41.            }  
  42.            else  
  43.                sampleChild.Item2 = «error»;  
  44.   
  45.            return View();  
  46.        }  
  47.        public IActionResult ObjectInsideObject()  
  48.        {  
  49.            sampleObj = new SampleObj();  
  50.            sampleObj.ChildObj.Item2 = «error»;  
  51.            return View();  
  52.        }  
  53.        public IActionResult AddInNullList()  
  54.        {  
  55.            lstSample.Add(«error»);  
  56.            return View();  
  57.        }  
  58.    }  

Classes

  1. public class SampleObj  
  2. {  
  3.   
  4.     public string Item1 { get; set; }  
  5.     public SampleChildObj ChildObj { get; set; }  
  6. }  
  7. public class SampleChildObj   
  8. {  
  9.     public string Item2 { get; set; }  
  10. }  

New object not instantiated

Practical example,

Here, we have a sample situation of when we have this error.

  1. public IActionResult NewObject()  
  2. {  
  3.     sampleChild.Item2 = «error»;  
  4.     return View();  
  5. }  

This happens when you create a new object but do not instantiate it before getting/setting a value.

Condition statement(if, switch)

Practical example

Here, we have a sample situation of when we have this error,

  1. public IActionResult ConditionStatement()  
  2. {  
  3.     if (true == false)  
  4.     {  
  5.         sampleChild = new SampleChildObj();  
  6.         sampleChild.Item2 = «»;  
  7.     }  
  8.     else  
  9.         sampleChild.Item2 = «error»;  
  10.   
  11.     return View();  
  12. }  

Why does this happen?

This is a very common mistake. It happens when you create an object that is going to be instantiated inside a conditional statement but forgets to instantiate it in one of the conditions and try to read/write on it.

Object Inside Object

Practical Example

Here, we have a sample situation of when we have this error:

  1. public IActionResult ObjectInsideObject()  
  2. {  
  3.     sampleObj = new SampleObj();  
  4.     sampleObj.ChildObj.Item2 = «error»;  
  5.     return View();  
  6. }  

Why Does This Happens?

It happens when you have an object with many child objects. So, you instantiate the main object but forget to instantiate its child before trying to get/set its value.

Add an item in a null list

Practical Example

Here we have a sample situation of when we have this error,

  1. public IActionResult AddInNullList()  
  2. {  
  3.     lstSample.Add(«error»);  
  4.     return View();  

Why does this happen?

When you are trying to read/write data in a list that was not instantiated before.

Important

  1. In order to avoid exposing your data, you must always handle exceptions. Read more about how to do that here. 
  2. The items listed above are some of the most common ways to throw this type of error but there are many other situations in which we may face it. Always remember to check if your objects are instantiated before reading or writing data into them.

Best practices

  • Tips about commenting your code, making it more readable in order to help others developers to understand it.
  • Object naming practices, create a pattern to name variables, services, and methods.
  • Handling errors to not show sensitive data to your users.
  • Security tricks to protect your data.
  • Reading/writing data without breaking your architecture.

*I am planning to write more about common mistakes and share tips to improve code quality. If you have any specific topic that you would like to read here, please write it below in the comments section.

Congratulations! You just learned how to deal with the most common daily mistakes.

Download the code from GitHub here.

Debugging System.NullReferenceException — Object reference not set to an instance of an object

TOC

Time for another post in the series Debugging common .NET exceptions. Today’s exception is, without a doubt, the error most people have experienced: System.NullReferenceException. The exception happens when you try to invoke a reference that you were expecting to point to an object but in fact, points to null. Let’s get started!

Debugging System.NullReferenceException - Object reference not set to an instance of an object

Handling the error

There are some clever ways to avoid a NullReferenceException, but before we start looking into those, let us see how the exception can be caught. Being a plain old C# exception, NullReferenceException can be caught using a try/catch:

try
{
    string s = null;
    s.ToString();
}
catch (NullReferenceException e)
{
    // Do something with e, please.
}

Running the code above will produce the following error:

System.NullReferenceException: Object reference not set to an instance of an object.

Debugging the error

We already know why the exception is happening. Something is null. When looking at the code above, it’s clear that s is null and the stack trace even tells us that:

stacktrace_1571989670

Sometimes spotting what is null can be hard. Take a look at the following example:

var street = service.GetUser().Address.Street;

If the code above throws a NullReferenceException, what is null? service? The result of GetUser()? Address? At first glance, Visual Studio isn’t exactly helpful either:

NullReferenceException in Visual Studio

There is a range of different ways to find out what is going on. Let’s look at the most commonly used ones.

Splitting chained method-calls to multiple lines

Spotting which call that caused an error is a lot easier if the calls are split into multiple lines:

var service = new Service();
var user = service.GetUser();
var address = user.Address;
var street = address.Street;

Running the code reveals the actual call causing the exception:

NullReferenceException in Visual Studio 2

In the example above user.Address returns null, why address.Street causes the NullReferenceException.

While splitting code into atoms like this can help debug what is going wrong, it’s not preferable in terms of readability (IMO).

Using Null Reference Analysis in Visual Studio

If you are on Visual Studio 2017 or newer (if not, now is the time to upgrade), you will have the Null Reference Analysis feature available. With this in place, Visual Studio can show you exactly what is null. Let’s change the example back to method-chaining:

var street = service.GetUser().Address.Street;

To enable the analysis go to Debug | Windows | Exception Settings. Check Common Language Runtime Exceptions (if not already checked) or extend the node and check the exceptions you are interested in. In this case, you can check System.NullReferenceException. When running the code, the debugger breaks on the NullReferenceException and you now see the Exception Thrown window:

Exception Thrown Window

Voila! The window says «ConsoleApp18.User.Address.get returned null». Exactly what we wanted to see. This will require you to run the code locally, though. If you are experiencing the exception on your production website, the Null Reference Analysis will not be available, since this is a feature belonging to Visual Studio (unfortunately). With that said, you can attach a debugger to a remote site running on Azure as explained here: Introduction to Remote Debugging on Azure Web Sites.

Fixing the error

There are various ways to fix NullReferenceException. We’ll start with the simple (but dirty) approach.

Using null checks

If null is an allowed value of an object, you will need to check for it. The most simple solution is to include a bunch of if-statements.

if (service != null)
{
    var user = service.GetUser();
    if (user != null)
    {
        var address = user.Address;
        if (address != null)
        {
            var street = address.Street;
        }
    }
}

The previous code will only reach address.Street if everything else is not null. We can probably agree that the code isn’t exactly pretty. Having multiple nested steps is harder to read. We can reverse the if-statements:

if (service == null) return;
var user = service.GetUser();
if (user == null) return;
var address = user.Address;
if (address == null) return;
var street = address.Street;

Simpler, but still a lot of code to get a street name.

Using null-conditional operator

C# 6 introduced a piece of syntactic sugar to check for null: null-conditional operator. Let’s change the method-chain example from before to use the «new» operator:

var user = service?.GetUser()?.Address?.Street;

The ? to the right of each variable, corresponds the nested if-statements from previously. But with much less code.

Use Debug.Assert during development

When getting a NullReferenceException it can be hard to spot the intent with the code from the original developer. Rather than including if-statements, it can be clearer for future authors of your code to use the Debug.Assert-method. Much like in a xUnit or NUnit test, you use Assert to verify the desired state on your objects. In the example from above, the service object could have come through a parameter or a constructor injected dependency:

class MyClass
{
    Service service;
    
    public MyClass(Service service)
    {
        this.service = service;
    }
    
    public string UserStreet()
    {
        return service.GetUser().Address.Street;
    }
}

To make a statement in your code that service should never be allowed to have the value of null, extend the constructor:

public MyClass(Service service)
{
    Debug.Assert(service != null);
    this.service = service;
}

In the case MyClass is constructed with null, the following error is shown when running locally:

Assert error

Use nullable reference types in C# 8.0

When designing code you often end up expecting parameters to be not null but end up checking for null to avoid a NullReferenceException. As you already know, all reference types in C# can take the value of null. Value types like int and boolean cannot take a value of null unless explicitely specified using the nullable value type (int? or Nullable<int>). Maybe it should have been the other way around with reference types all along?

C# 8 can fix this with nullable reference types (maybe NOT nullable reference types is a better name). Since this is a breaking change, it is launched as an opt-in feature. Nullable reference types are a great way to avoid NullReferenceExceptions, since you are very explicit about where you expect null and where not.

To enable not nullable reference types, create a new .NET Core 3 project and add the following to the csproj file:

<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>

You should be on C# 8 already, but to make it explicit, I’ve added the LangVersion element. The Nullable element enables nullable reference types. Out of the box, C# 8 creates a warning if it identifies the use of null where a value is expected. Let’s see how that looks:

class Program
{
    static void Main()
    {
        new Program().SayHello(null);
    }

    public void SayHello(string msg)
    {
        Console.WriteLine(msg);
    }
}

When compiling we see the following warning:

Program.cs(9,36): warning CS8625: Cannot convert null literal to non-nullable reference type. [C:projectscore3core3.csproj]

I know you are not one of them, but some people developed a warning-resistance which means that warnings are simply ignored. To overcome this, make sure that errors like this causes build errors over warnings by adding the following to csproj:

<WarningsAsErrors>CS8602,CS8603,CS8618,CS8625</WarningsAsErrors>

This will tell the C# compiler to treat these four nullable reference type warnings as errors instead.

Just to make it clear, allowing null in the msg parameter, you use the ? characters as with value types:

public void SayHello(string? msg)
{
    ...
}

Logging and monitoring

Logging and monitoring for null reference exceptions are a must. While some developers tempt to create control flow from exceptions (no-one should), null reference exceptions should never happen. This means that a System.NullReferenceException is a type of exception that should always be logged and fixed. A null check through either an if statement or the null-conditional operator is always the preferred way of handling potential null values. But make sure to implement a logging strategy that logs all uncaught exceptions, including the System.NullReferenceException.

When logging a System.NullReferenceException in a log file, database, elmah.io, or similar, it can be hard to spot what is null. You typically only see the method-name that causes the NullReferenceException and the Null Reference Analysis feature is only available while debugging inside Visual Studio. I will recommend you to always Include filename and line number in stack traces. This will pinpoint the exact line where the error happens.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

elmah.io app banner

See how we can help you monitor your website for crashes
Monitor your website

The “Object reference not set to an instance of an object” is a very famous error in C# that appears when you get a NullReferenceException. This occurs when you try to access a property or method of an object that points to a null value. They can be fixed using Null conditional operators and handled using try-catch blocks.

In this post, we will learn more about the error and the ways to fix it.

What is “NullReferenceException: Object reference not set to an instance of an object” error?

As mentioned earlier, the NullReferenceException indicates that your code is trying to work with an object that has a null value as its reference. This means that the reference object has not been initialized.

This is a runtime exception that can be caught using a try-catch block.

Example code

try
{
    string a = null;
    a.ToString();
}
catch (NullReferenceException e)
{
    //Code to do something with e
}

How to fix this error?

You can fix this error by using the following methods:

  • Using Null conditional operators
  • Using the Null Coalescing operator
  • Using nullable datatypes in C#   

1) Using Null conditional operators

This method is easier than using an if-else condition to check whether the variable value is null. Look at this example,

int? length = customers?.Length; // this will return null if customers is null, instead of throwing the exception

2) Using the Null Coalescing operator

This operator looks like “??” and provides a default value to variables that have a null value. It is compatible with all nullable datatypes.

Example

int length = customers?.Length ?? 0; // 0 is provided by default if customers is null      

3) Using nullable datatypes in C#   

All reference types in C# can have a null value. But some data types such as int and Boolean cannot take null values unless they are explicitly defined. This is done by using Nullable data types.

For example,

static int Add(string roll_numbers)
{
return roll_numbers.Split(","); // This code might throw a NullReferenceException as roll_numbers variable can be null 
}

Correct code

static int Add(string? roll_numbers) // As roll_numbers argument can now be null, the NullReferenceException can be avoided  
{
return roll_numbers.Split(",");  
}

The best way to avoid the «NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!=null) to avoid this exception.

In this post, we will show you how to fix Object reference not set to an instance of an object error prompt which you may see in Microsoft Visual Studio.

Fix Object reference not set to an instance of an object error in Microsoft Visual Studio

What is the meaning of Object reference not set to an instance of an object?

It is quite a common error in Visual Studio and is called a null exception error. The error is triggered when the object that you are referring to doesn’t exist, is deleted, removed, or is classified as null. Now, it mostly occurs due to human error, in case there is some error in your code. While this is the popular scenario, there are instances when this error occurs due to other reasons.

What causes Object reference not set to an instance of an object in Microsoft Visual Studio?

Apart from human error in code, here are some other popular causes that may trigger the error in hand:

  • It can be triggered due to bugs and glitches in the program. In case you are using an outdated version of Visual Studio, consider updating it.
  • The corrupted user data and cache for Microsoft Visual Studio can be another reason for the error. You can try resetting the user data in order to fix the error.
  • It can also be caused in case the program is missing administrator rights to run. So, relaunch it with admin access and see if you stop receiving the error.
  • The installed extensions can also be a problem. So, update all of them and see if the error is fixed.

In any case, if you are receiving the same error, you have landed on the correct page. Here, we are going to discuss various solutions to fix the “Object reference not set to an instance of an object” error in Microsoft Visual Studio. Let us check out.

Here are the methods to fix the “Object reference not set to an instance of an object” error in Microsoft Visual Studio:

  1. Review your code.
  2. Relaunch Microsoft Visual Studio as an administrator.
  3. Reset User Data.
  4. Update Microsoft Visual Studio.
  5. Update extensions.
  6. Install Microsoft ASP.NET and Web Tools.

1] Review your code

The first thing you should do is thoroughly check your code and make sure there is no referred object having a null value. This error is most likely to trigger when there is a problem within the code itself. So, do check and review your code and ensure it is good to go.

If your code is fine and you keep getting the same error, the cause might be something else other than human error. Hence, you can try the next potential fix to resolve the error.

2] Relaunch Microsoft Visual Studio as an administrator

Lack of sufficient permission to run the program can be a cause that you are receiving the error in hand. If the scenario is applicable, you can relaunch Visual Studio with administrator privilege. For that, you can simply close Microsoft Visual Studio and related processes by going to the Task Manager. After that, go to the Microsoft Visual Studio’s executable and right-click on it. From the right-click context menu, select the Run as administrator option. See if this fixes the “Object reference not set to an instance of an object” error for you.

If yes, you can make Microsoft Visual Studio always run as an administrator instead of repeating the above procedure every time you launch it. Here is how you can do that:

  1. Firstly, open File Explorer using Win+E hotkey and navigate to the installation directory of Microsoft Visual Studio.
  2. Now, right-click on the Visual Studio’s executable and then select the Properties option.
  3. Next, in the Properties window, go to the Compatibility tab and enable the Run this program as an administrator checkbox.
  4. Then, click on the Apply > OK button to save changes.
  5. Finally, you can run Visual Studio and it will always run with administrator rights.

In case you are still experiencing the same error In Microsoft Visual Studio, try the next potential fix.

Read: The program can’t start because VCRUNTIME140.DLL is missing.

3] Reset User Data

User data can potentially cause the “Object reference not set to an instance of an object” error. In case it is corrupted, you are likely to encounter this error. Now, it is difficult to know the particular content that is causing the error. Hence, you will have to reset the user data to fix the error if and only the scenario is applicable. However, do remember that this will result in losing all your settings including layouts, linked Microsoft accounts, and other content.

Here are the steps to reset the user data for Microsoft Visual Studio:

  1. Firstly, open File Explorer using Windows+E hotkey and then go to the following location in the address bar:
    C:Users%userprofile%AppDataLocalMicrosoftVisualStudio
  2. Now, select all the content at the above location using the Ctrl+A hotkey and then press the Delete button to remove all data.

Try restarting Visual Studio and check if you stopped receiving the “Object reference not set to an instance of an object” error.

4] Update Microsoft Visual Studio

The next thing you should try to fix the error is to update Microsoft Visual Studio to the latest version. This error can be caused due to old bugs and glitches in the application. The new updates address such bugs and fix them. Hence, if you are using an older version of Microsoft Visual Studio, it is time to update it.

Here are the steps to update Microsoft Visual Studio:

  1. Firstly, click on the taskbar search button and then type Visual Studio Installer in the search box; open the respective app from the results.
  2. Now, in the opened window, locate the edition you are currently using.
  3. Next, in case there is an update available to the Microsoft Visual Studio edition you have installed, you will see an Update option associated with it. Simply tap on this option and follow the instructions to update it.

After updating the Visual Studio application, relaunch it and check whether or not the error is gone.

See: Fix AppModel Runtime Errors 57, 87, 490, etc.

5] Update extensions

If you have installed some extensions in Microsoft Visual Studio and they are out-of-date, you should consider updating them. Outdated extensions can trigger errors like “Object reference not set to an instance of an object” and others. So, make sure you have updated extensions in Visual Studio. Here are the steps to do that:

  1. Firstly, open Microsoft Visual Studio and go to the Extensions menu.
  2. Now, select the Manage Extensions option.
  3. Next, in the Manage Extensions window, go to the Updates section from the left side pane to see the extensions for which updates are available.
  4. After that, from the top of the installed extensions, click on the Update All button to update all the extensions.
  5. When the process is complete, go ahead and reboot your PC.
  6. On the next startup, launch Visual Studio, and hopefully, you won’t see the “Object reference not set to an instance of an object” error anymore.

6] Install Microsoft ASP.NET and Web Tools

Tools including Microsoft ASP.NET and HTML/JavaScript tools enable you to generate dynamic webpages as well as can prevent errors like “Object reference not set to an instance of an object.” So, you can simply install these tools and see if installing them resolves the error or not. You can easily install these tools in Visual Studio by following the below steps:

  1. Firstly, open Visual Studio and navigate to the Tools menu on the top.
  2. Now, select the Get Tools and Features option from the drop-down options.
  3. In the new window, look for the “ASP.NET and web development” tool and select it.
  4. Next, click on the Modify > Install button from the bottom of the window and let it install the package.
  5. After installing the package, relaunch the Microsoft Visual Studio and check whether or not the error prompt has stopped now.

Read: The object invoked has disconnected from its clients.

How do I fix object reference not set to an instance of an object in Excel?

The “Object reference not set to an instance of an object” error in Excel might occur while trying to delete or remove a table. So, to be able to delete the table without the error, you can get into Data View and on the tab strip present at the bottom of Data View, right-click on the table you want to delete. And then, select the Delete option and press Yes on the UAC prompt to confirm the deletion.

How do I stop NullReferenceException?

There are some tips you can follow to avoid the NullReferenceException error. You can use the IF statement or use Null Conditional Operator to check the property prior to accessing instance members. Other than that, you can use GetValueOrDefault(), Null Coalescing Operator, etc. to avoid NullReferenceException.

Hope this article helps you get rid of the “Object reference not set to an instance of an object” error prompt in Microsoft Visual Studio.

Now read: Visual Studio Code crashing on Windows.

Понравилась статья? Поделить с друзьями:
  • Как найти адрес по телефону в ростове
  • Как найти все сообщения человека в беседе
  • Как найти главную мысль текста пример
  • Как найти телефон когда его спрятали родители
  • Как найти серебряную сережку в снегу