Object reference not set to an instance of an object как исправить ошибку

Когда я выполняю некоторый код, выбрасывается исключение NullReferenceException со следующим сообщением: Object reference not set to an instance of an object. или В экземпляре объекта не зад...

Причина

Вкратце

Вы пытаетесь воспользоваться чем-то, что равно 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;

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.

The “Object reference not set to an instance of an object” error is a prevalent Windows error that originates from a Microsoft Visual Studio issue. This error code will appear in a situation where a Microsoft Visual Studio object is missing, is classified as null, or cannot be reached. 

Object Reference Not Set to an Instance of an Object on Windows

As it turns out, this issue is not specific to Microsoft Visual Studio developers as it can also be thrown by other applications that are built using Microsoft Visual Studio dependencies. Here’s a shortlist of potential culprits that are most likely responsible for this problem:

  • Missing Windows 1803 Update on Windows 10 – If you’re still using Windows 10, chances are you’re experiencing this problem due to a conflict between some of your system drivers and some of the touchscreen devices that are currently installed (most commonly experienced with Surface devices). Microsoft has fixed this issue via the 1803 update, so install it if it’s missing from your computer. 
  • Corrupted Visual Studio data – If you’re experiencing this issue while attempting to use Microsoft Visual studio, the problem is most likely related to some kind of corruption affecting your current user data. To fix this problem, you’ll need to reset the user data currently associated with your account.
  • Missing Microsoft Visual Studio permissions – Another scenario that will produce this error is a scenario in which the Microsoft Visual Studio application doesn’t have the required permissions to override files. To fix this issue, you’ll need to force the application to open with administrator access.
  • A conflict caused by the ouch Keyboard and Handwriting Panel Service – If you’re actively using devices with a touchscreen surface or your device supports it natively, there’s also the possibility that the Touch Keyboard and Handwriting Panel Service is causing this problem. You can test out this theory by temporarily disabling this service.
  • Updated Microsoft Visual Studio version – If you’ve just imported a new project into Microsoft Visual Studio and you started getting this error, it’s possible that the error is occurring because you’re using an outdated Visual Studio version that’s incompatible with the project you are trying to open. In this case, you can fix the issue by updating your MS Visual Studio version.
  • Outdated Microsoft Visual Studio version – If you’re relying on one or more Visual Studio extensions in your projects, make sure all of them are updated. Several users have confirmed that they managed to fix this error by updating every used Visual Studio extension. 
  • Missing ASP.NET or Web Tools dependency – In case you only get this error while attempting to open projects that are using Web Tools and ASP.NET dependency, you should double-check and ensure that you actually have these dependencies installed.
  • Vault Server Problem – If you get this error while attempting to access your AutoDesk Vault, you should first check the status of the critical Vault services and ensure that they’re up and running.
  • Corrupted local Vault Client profile – As it turns out, this issue can also occur in a situation where the current Vault user profile that you’re actively using has become corrupted. In this case, you can fix the issue by deleting your local Vault User profile and starting from scratch.
  • Outdated Vault version – In case you only see this error while attempting to access your AutoDesk Vault and you already ensured that the servers were not affected, you should start by making sure that you’re using the latest Vault deployment package locally. If you’re not updated to the latest version, perform the update manually. 
  • Corrupted Vault installation – Under certain circumstances, you might experience this problem due to a wider case of corruption that affects your local Vault installation. In this case, you can fix the problem by reinstalling the entire local Vault infrastructure.
  • Antivirus or firewall interference – In some cases, you might experience this problem in a scenario in which your active antivirus ends up blocking the execution of another executable from the Vault ecosystem. In this case, you can resolve the issue by whitelisting the executable that gets flagged or by uninstalling the overprotective suite. 

Now that we went over every potential reason why you might see the “Object reference not set to an instance of an object” error, let’s go over every confirmed fix 

1. Install the 1803 Update (Windows 10 Only)

The error is sometimes received when loading the Juris® Suite Inquiry on Windows 10 Professional Edition computers. Upon investigating, found that this issue is caused by a Windows Update and has been resolved by a hotfix included in the Windows Update 1803.  

Update: The error can also occur due to a conflict on some touchscreen devices, such as Microsoft Surface.

In case you’re experiencing this issue on Windows 10 and you haven’t installed the 1803 update yet, updating should take care of the issue if this is the root cause of the problem. 

If you’re looking for specific instructions on how to update, follow the instructions below:

  1. To open the Run dialog box, press Windows key + R. In the text box, type “ms-settings:windowsupdate” and press Enter to go to the Windows Update tab in Settings. 
    Access the Windows Update component
  2. In the Windows Update screen, go to the right section and click Check for Updates
    Check for Updates
  3. After the initial scan is complete, install any pending Windows updates. If you have a lot of updates, you might have to restart before you can install all of them. If so, restart as instructed, but come back to this screen after startup to finish installing the updates.
  4. When you finish installing updates, reboot your computer one final time and see if the “Object reference not set to an instance of an object” error is still occurring.

If this fix was not applicable or it didn’t fix the issue in your case, move down to the next method below. 

2. Disable the Touch Keyboard and Handwriting Panel Service (if applicable) 

If you previously confirmed that the Windows Update 1803 is installed on your Windows 10 version, the next thing you should investigate is a potential conflict caused by the Handwriting Panel Service.

Several users that are dealing with the same issue have confirmed that they finally managed to take care of the “Object reference not set to an instance of an object” error after effectively disabling the Touch Keyboard and Handwriting Panel from the services screen.

Warning:  This procedure will affect the usage of any connected touch screen device. Don’t attempt this fix below if you’re using a touchscreen device like Microsoft Surface since it will effectively break the touchscreen functionality.

If you are prepared to apply this fix, follow the instructions below:

  1. Press Windows key + R to open up a Run dialog box. Next, type ‘services.msc’ and press Ctrl + Shift + Enter to open up the Services screen with admin access.
    Open up the services screen
  2. At the User Account Control (UAC), click Yes to grant admin access. 
  3. Once you’re inside the Services screen, scroll down through the list of available services and locate the Touch Keyboard and Handwriting Panel service. 
  4. When you see it, right-click on it and choose Properties from the context menu. 
    Accessing the Properties screen
  5. Once you’re inside the Properties screen of Touch Keyboard and Handwriting Panel service, access the General tab and set the Startup Type to Disabled before hitting Apply to save the changes. 
  6. Restart your PC and check if the problem is now fixed by repeating the same action that was previously causing the “Object reference not set to an instance of an object” error.

If the problem is still not resolved, move down to the next method below. 

3. Reset Visual Studio user data

User data may also be the root cause of the “Object reference not set to an instance of an object” error. To fix this, we need to reset all user data related to Visual Studio.

Note: Please note that your user settings, such as Visual Studio layout, linked Microsoft account, or start page, may be lost after you perform the procedure below. 

To accomplish this, we’ll need to access the user Visual Studio folder (under AppData) via File Explorer and delete the contents inside before restarting Visual Studio.

Follow the instructions below for step-by-step instructions on how to do this:

  1. First things first, make sure that Visual Studio is closed and not running in the background.
  2. Open File Explorer and navigate to the following location:
    C:Users%userprofile%AppDataLocalMicrosoftVisualStudio

    Accessing the Visual Studio User Profile
  3. Once you arrive inside the correct location, clear the contents of the folder by selecting everything, then right-clicking on a selected item and clicking on Delete. 
  4. Restart your PC, then open Visual Studio once again and see if the problem is fixed.

In case this method was not applicable or it didn’t fix the issue in your case, move down to the next potential fix below. 

4. Run Microsoft Visual Studio with the required Permissions

Another scenario that might end up producing this issue is a scenario in which Microsoft Studio doesn’t have the required permissions to edit files from the projects that you’re opening inside the program.

This is way more common on Windows 10 where the developing environment does not open with admin rights by default.

Fortunately, you can force Microsoft Visual Studio to open with the necessary permissions by forcing your OS to open it with admin access. 

If you haven’t tried this yet, follow the instructions to open Microsoft Visual Studio with the required permissions:

  1. Start by pressing the Windows key, then type Visual Studio in the search bar at the top.
  2. From the list of results, right-click on Visual Studio and then click on Open file location from the context menu that just appeared. 
    Open the file location of Visual Studio
  3. Next, right-click on Visual Studio from the revealed location, then click on Run as Administrator from the context menu. 
  4. Now that you’ve ensured that Visual Studio opened with the necessary permissions, repeat the action that was causing the “Object reference not set to an instance of an object” error and see if the problem is fixed.

If the issue is still ongoing, try the next fix below.  

5. Update Microsoft Visual Studio

Microsoft regularly releases updates for Visual Studio to address common bugs and errors. For example, the “Object reference not set to an instance of an object error” can be fixed with an update if the problem is related to an application bug. Thus, it is important to keep Visual Studio up-to-date to avoid this and any similar errors.

Despite the fact that Microsoft Visual Studio prompts users when a new update is available, one should check for updates manually from time to time, just in case the prompt was missed or ignored.

Follow the instructions below to check if a new update is available for your current Visual Studio version:

  1. Press the Windows key on your keyboard and type ‘Visual Studio Installer‘ inside the search box at the top. 
  2. From the list of results, click on the Open button associated with Visual Studio Installer. 
    Opening the Visual Studio Installer
  3. Once the Visual Studio Installer utility is opened, wait until the auto-check is performed. If a new version is identified, you will be prompted by an Update button.
  4. Click on the Update button, then follow the on-screen instructions to complete the installation of the available update.  
  5. After the new version is installed, reboot your PC and see if the “Object reference not set to an instance of an object” error is fixed once the next startup is complete.

In case the same problem is still occurring or your Visual Studio version was already updated to the latest, move down to the next method below. 

6. Update Microsoft Visual Studio Extensions

Even if you made sure that you’re running on the latest version of Microsoft Visual Studio, it’s still likely that some of the extensions (if you’re using any) might be outdated and indirectly cause the “Object reference not set to an instance of an object” error. 

If you’re actually relying on Visual Studio extensions in your development, follow the instructions below to check if every extension is updated to the latest version:

  1. First things first, make sure that you open the project that you’re experiencing the issue with.
  2. Once the project is loaded, use the ribbon bar at the top to click on Extensions, then click on Manage Extensions from the context menu that just appeared. 
    Managing the extensions
  3. Once you’re inside the extensions tab, check if any of the available Visual Studio extensions need updating. If new updates are available, click on Update all and confirm the process. 
    Update the available Visual Basic extensions
  4. Once every available update is installed, restart the application and see if the “Object reference not set to an instance of an object” error is fixed.

If this method was not applicable in your particular scenario, move down to the next method below. 

7. Install Microsoft ASP.NET and Web Tools

Microsoft ASP.NET and HTML/JavaScript are all tools that are used to create dynamic web pages and prevent errors, such as “Object reference not set..”. If you don’t have these dependencies installed, chances are installing them will fix the issue automatically.

Fortunately, Visual Studio makes it easy to install Microsoft ASP.NET and Web Tools.

Follow the instructions below to install the missing Microsoft ASP.NET and Web Tools:

  1. Start by opening Visual Studio and load up your existing project that’s causing the problem.
  2. Once the project is loaded, use the ribbon bar at the top to click on Tools > Get Tools and Features. 
    Accessing the Get Tools and Features
  3. Once you’re inside the Get Tools and Features menu, check the box associated with ASP.NET and web development, then click on Install while downloading
    Installing the ASP.NET and web development dependency
  4. Once this dependency is installed, restart the application and see if the problem is now fixed. 

If the problem is still not fixed, move down to the next method below. 

8. Check for a Vault critical server problem (if applicable)

If you’re experiencing this issue while attempting to use the Vault server infrastructure provided by AutoDesk, one of the most common causes is an issue with the critical services used by the Vault Servers infrastructure.

To investigate whether this is the cause of the issue, follow the instructions below to check if the following services are all running:

  • Autodesk Data Management Job Dispatch.
  • SQL Server (AUTODESKVAULT)*.
  • SQL Server Agent (AUTODESKVAULT)*.
  • Windows Process Activation Service.
  • World Wide Publishing Services.

If any of the services mentioned above are not running, start them manually to fix the “Object reference not set to an instance of an object” error:

  1. Log in to Windows on the Vault server, then press Windows key + R to open up a Run dialog box. 
  2. Inside the run prompt that just appeared, type ‘services.msc’ and press Ctrl + Shift + Enter to open the Services screen with admin access. 
    Open up the services screen
  3. Once you’re inside the Services Management Console, check the status of the services below and ensure that every one of them is currently running:
    Autodesk Data Management Job Dispatch.
    
    SQL Server (AUTODESKVAULT)*.
    
    SQL Server Agent (AUTODESKVAULT)*.
    
    Windows Process Activation Service.
    
    World Wide Publishing Services.
  4. If any of these services are not currently running, right-click on each of them individually and click on Restart. 
  5. Once every service is restarted, repeat the action that was causing the error and see if it’s now fixed.

If the “Object reference not set to an instance of an object” error is still occurring, move down to the next method below. 

9. Delete the Local Vault Client Profile (if applicable) 

Another potential cause that might trigger the “Object reference not set to an instance of an object” error when using the Vault Servers is some type of corruption that is affecting the Vault user profile.

If this scenario is applicable and you haven’t attempted this fix yet, all you need to do is every Autodesk folder that holds user data.

IMPORTANT: You will only be able to do this when the main application is closed. So before proceeding with the deletion of the folders below, close the Autodesk app.

Here are the folders that need to be deleted in order to clear the data related to the Vault Client Profile:

  • “%APPDATA%AutodeskVaultCommon”
  • “%APPDATA%AutodeskProductstream 20xx”
  • “%APPDATA%AutodeskVault Explorer 20xx”
  • “%APPDATA%AutodeskAutoCAD 20xx Vault Addin”
  • “%APPDATA%AutodeskAutodesk Vault Basic 20xx”
  • “%APPDATA%AutodeskAutodesk Vault Workgroup 20xx”
  • “%APPDATA%AutodeskAutodesk Vault Professional 20xx”
  • “%APPDATA%AutodeskAutoloader”
  • “%APPDATA%AutodeskReference Repair Utility”
  • “%APPDATA%AutodeskInventor 20xx Vault Addin”
  • “%APPDATA%AutodeskVaultManager”

Note: Deleting these folders won’t affect the functionality of the Autodesk app. These folders will be automatically regenerated the next time you open the app.

If this method is not applicable or it didn’t work for you, move down to the next method below. 

10. Update Vault version (if applicable) 

In the past, this issue started occurring for AutoDesk users in scenarios where their Vault products were running on a deprecated version.

To make sure that you’re using the latest version, visit the official Vault Download page and download & install the latest available build. 

If the problem is still not fixed or not applicable, move down to the next method below. 

11. Uninstall and Reinstall Vault (if applicable) 

If you’re experiencing issues with your Vault software, you may need to repair, reinstall, or uninstall Vault Server, Vault Client, or the Vault integration for a CAD product (depending on the scenario that is applicable).

This scenario is applicable in scenarios where the Autodesk software is inconsistent and you suspect that the local installation contains some corrupted components that are causing issues with the Vault integration.

Note: This method is only applicable in scenarios where you are using Autodesk Vault (Server, Client, or CAD integration). If you’re not using Vault at all, skip this method altogether and move down to the final fix below. 

Depending on where the corruption initiates from, one of the sub-guides below should help you fix the issue:

  • Uninstall and reinstall the Vault Client
  • Uninstall and reinstall the Vault Server
  • Uninstall and reinstall the Vault Integration 

Note: Our recommendation is to follow the sub-guides in the same order as presented below and see if any of them ends up fixing the “Object reference not set to an instance of an object” error. 

Uninstall and Reinstall the Vault Client

There are three main causes that will ultimately signal a potential corruption issue with the Thick Vault Client from Autodesk:

  • The edition you’re using is not consistent with your package (e.g. you’re using Vault Office when you should be using Vault Professional)
  • The software is behaving inconsistently due to a false positive.
  • Some program file components have become corrupted.

If any o the scenarios described above are applicable, follow the instructions below to uninstall and reinstall the Vault Client:

  1. Start by pressing the Windows key + R to open up a Run dialog box. 
  2. Next, inside the Run prompt, type ‘appwiz.cpl’ and press Enter to open up the Programs and Features menu. 
    Open up the Programs and Features menu
  3. Once you’re inside the Programs and Features menu, locate the entry associated with Vault Basic, Vault Workshop, or Vault Professional (Client), right-click on them, and choose Uninstall. 
    Uninstall the Autodesk vault
  4. From the uninstallation screen that just appeared, click on Uninstall from the list of available options.
    Starting the Autodesk Vault uninstallation process
  5. Click Uninstall again, then follow the on-screen instructions to complete the uninstallation. 
    Confirm the uninstallation process
  6. Once the uninstallation is complete, visit the installation directory of Autodesk Vault and remove any leftover files.
  7. Restart your client, then reinstall the software from scratch using the provided installation media (or download link). 

Uninstall and reinstall the Vault Integration

Integrating your Vault-enabled applications ( AutoCAD, Inventor, Revit, etc) with a Vault server enables interaction without needing to switch programs. If the Thick Vault client detects qualifying products during its installation, it will automatically install integrations.

However, if the AutoDesk Vault software is behaving inconsistently and you suspect that some of the files belonging to the installation have become corrupted, you can attempt to fix the issue by attempting to uninstall the Vault integration/s.

To do this, you would need to use the Programs and Features menu to “Change” the installation of the Thick Vault client and get rid of the problematic integration.

Follow the instructions below for specific instructions on how to do this:

  1. To begin, press the Windows key + R to open a Run dialog box.
  2. Inside the Run prompt, type ‘appwiz.cpl’ and press Enter to open the Programs and Features menu.
    Open up the Programs and Features menu
  3. Once you’re inside the Programs and Features menu, find the entry associated with Vault Basic, Vault Workshop, or Vault Professional (Client), right-click on it, and choose Uninstall/Change.
  4.  The uninstallation screen will appear; click on Add or Remove Features from the list of available options.
    Add or remove Features inside the AutoDesk vault
  5. Next, you will get a list of all the integrations that are currently installed. Cycle through the list and untick the integration that is causing the problem from the list. 
    Removing the problematic integrations
  6. Once you’ve excluded the integrations that you want to remove, click on Update to make the changes reflect on the Vault app. 
  7. Follow the remaining instructions to complete the process, then reboot your PC and see if the problem is now fixed after going through the steps of reinstalling the integration that you’ve just recently removed. 

If the same kind of issue is still occurring, move down to the next sub-guide below. 

Uninstall and reinstall the Vault Server

If you notice that the software started to behave inconsistently and you burned through the other potential fixes above, you should investigate whether the programs or the components owned by Vault are actually corrupted and causing the problem.

In this case, you should be able to fix the problem by uninstalling and reinstalling the vault server. 

Follow the instructions below for specific instructions on how to do this:

  1. To begin, press the Windows key + R to open a Run dialog box.
  2. Then, type ‘appwiz.cpl’ into the prompt and press Enter to access the Programs and Features menu.
    Open up the Programs and Features menu
  3. In the Programs and Features menu, locate the entry for Vault Basic,or Workgroup or Professional (Server). Right-click on the entry and select Uninstall from the drop-down menu.
    Uninstall the Autodesk Vault Professional Server
  4. A new screen will appear with the option to click on Uninstall. Click on Uninstall again and follow the instructions to finish the uninstallation.
    Uninstalling the Autodesk Vault server installation
  5. After uninstallation is complete, go to the installation directory of the Autodesk Vault server and remove any leftover files.
  6. Finally, restart your client and reinstall the software from scratch using the provided installation media (or download link).

If this method didn’t fix the issue in your case, move down to the next potential fix below. 

12. Prevent antivirus interference (if applicable) 

If you’ve come this far without a resolution that worked in your case, you should know that certain security software can sometimes be over-aggressive with their protection and block the communications of legitimate software like AutoDesk Vault. 

If you’re certain that you’re dealing with a false positive, the only thing you can do is take some steps to prevent your active antivirus from interfering with the AutoDesk Vault.

AV suites such as Comodo, Avast, McAffee are often cited as the main culprits for causing this type of behavior with AutoDesk vault.

However, there may be other programs that will cause the same type of behavior. If you think your AV software might be the problem, you should start by disabling real-time protection and see if that makes the difference.

To disable real-time protection in most security suites, including Avast, simply go to the taskbar menu.

Disabling the real-time protection

If you’re using a 3rd party security suite that also has a firewall, however, simply disabling real-time protection will not be enough. In this case, you will need to uninstall the entire security suite and clear any remnant files that might still cause problems.

Here is a quick guide on how to uninstall a problematic 3rd party security suite and clear any leftover files:

  1. To open the Programs and Features menu, press Windows key + R to open up a Run dialog box.
  2. Next, type ‘appwiz.cpl’ and press Enter.
    Open up the Programs and Features menu
  3. Scroll through the list of installed applications in the Applications and Features menu to find the 3rd party security suite you wish to uninstall.
  4. Next, right-click on it and choose Uninstall from the context menu.
    Uninstalling antivirus suite
  5. Follow the on-screen instructions to finish uninstalling, then restart your computer to save the changes.
  6. To remove any leftover files from the uninstalled AV suite, follow these instructions to ensure that you’re not leaving behind any AV files that might cause the same behavior. 
  7. Repeat the action that was causing the “Object reference not set to an instance of an object” error and see if the problem is now fixed. 

If you’re seeing the «Object reference not set to an instance of an object» error when using Microsoft Visual Studio on Windows, this article will help you fix it.

Object Reference Not Set to an Instance of an Object error

The error message «Object reference not set to an instance of an object» means that perhaps you’re referring to an object that doesn’t exist or cleaned up, or was deleted. It’s one of the many mysterious and frustrating Windows errors that occur when you’re using Microsoft Visual Studio

In many cases, it’s better to avoid a NullReferenceException than wait to handle it after it occurs.

So, this article will show you how to fix this error in a few easy steps to get your computer up and running again!

What Is the «Object Reference Not Set to an Instance of an Object» Error in Windows?

The problem «Object reference not set to an instance of an object» is a common Windows error caused by a Microsoft Visual Studio bug. This error code will show when a Microsoft Visual Studio object is missing, categorized as null, or cannot be accessible.

If you receive the «Object reference not set to an instance of an object» error on your Windows computer, it might be caused by a problem with your .NET Framework. This can be fixed by uninstalling and reinstalling the .NET Framework.

If you still see the error after trying this fix, it might be caused by a corrupt registry key. To fix this, you can use a registry cleaner tool to scan for and fix any corrupted keys.

What Causes the «Object Reference Not Set to an Instance of an Object» Error?

As it turns out, this problem isn’t limited to Microsoft Visual Studio developers; other apps that rely on Microsoft Visual Studio dependencies can also cause problems. Here’s a list of suspects who are most likely to blame for the problem:

  • Windows 10 Update 1803 isn’t installed: If you’re using Windows 10, the issue is most likely caused by a conflict between some of your system drivers and some of the touchscreen devices you have installed (most commonly experienced with Surface devices).
  • Corrupted data in Visual Studio: If you’re having trouble using Microsoft Visual Studio, it’s likely due to your current user data corruption. You’ll need to reset the user data connected to your account to fix this issue.
  • Missing Microsoft Visual Studio permissions: This issue can occur if the Microsoft Visual Studio application lacks the requisite permissions to override files. To fix this problem, you’ll need to force the application to open with administrator privileges.
  • Microsoft Visual Studio extensions: Make sure all of your Visual Studio extensions are up to date if you’re using them in your projects. Several users have confirmed that they were able to resolve the issue by updating or disabling all Visual Studio extensions in use.
  • Interference from an antivirus or firewall: In some situations, you may encounter this issue if your active antivirus prevents the execution of another executable from the Vault environment. In this situation, you may either whitelist the flagged executable or remove the overprotective suite to fix the problem.

These are some of the main causes of the «Object reference not set to an instance of an object» error in Windows. If you still see the error after trying all these fixes or need detailed steps, continue reading to troubleshoot further!

Solved: «Object Reference Not Set to an Instance of an Object» Error in Windows

Let’s get started on fixing this problem! Check out each potential fix and try them out to resolve «Object reference not set to an instance of an object.»

Method 1. Make Sure the 1803 Update is Installed on Windows 10

If you’re using Windows 10, you should first make sure that you have the 1803 update installed. This update from Microsoft has been known to resolve conflicts between drivers and touchscreen devices, which can cause the «Object reference not set to an instance of an object» error.

  1. Click on the Windows icon in the bottom left of your screen to bring up the Start menu. Choose Settings, or use the Windows + I shortcut.
    Windows settings
  2. Click on the Update & Security tile. This is where you can find most of your Windows Update settings and choose when to receive updates.
    Update and Security
  3. Make sure to stay on the default Windows Update tab. Click on the Check for updates button and wait for Windows to find available updates.
    Check for Updates
  4. If any updates are displayed, click on the View all optional updates link to see and install them.
    View all optional Updates
  5. When Windows finds a new update, it automatically starts installing on your computer. Wait for Windows to download and apply the necessary updates.

Method 2. Run Microsoft Visual Studio as an Administrator

If you’re having trouble using Microsoft Visual Studio, it might be because the application doesn’t have the necessary permissions to access certain files. To fix this, you should try running Microsoft Visual Studio as an administrator.

To do this, right-click on the Microsoft Visual Studio shortcut and select «Run as administrator» from the drop-down menu.

Run Microsoft Visual Studio as an Admin

If you’re still having trouble, try resetting the user data associated with your account. This will delete all of your current settings and preferences, but it will also clear any corruption that might be causing problems.

Method 3. Reset Your Visual Studio User Data

If you’re still having trouble with the «Object reference not set to an instance of an object» error, it’s likely because there is corruption in your current user data. It can also mean you have some general application bugs within your installation.

Don’t worry, this is normal! Application bugs may happen if you’ve been using your software for a long time. You can fix this by resetting the user data associated with your account.

  1. Open Visual Studio and go to Tools > Import and Export Settings.
  2. Select «Reset all settings» in the window that appears and click «Next
  3. On the next screen, select «No, just reset settings, overwriting my current settings» and click «Finish

This will delete all of your current Visual Studio settings and preferences, but it will also clear any corruption that might be causing problems.

Method 4. Update Microsoft Visual Studio to the Latest Version

If you’re still having trouble with Microsoft Visual Studio, you may be using an outdated software version. You should update Microsoft Visual Studio to the latest version to fix this.

To do this, open the Microsoft Visual Studio installer and click «Update.» Microsoft Visual Studio will now check for updates and install them automatically. Here are the step-by-step instructions:

  1. On your PC, look for the Visual Studio Installer. Search for «installer» in the Windows Start menu and select Visual Studio Installer from the results.
    Visual Studio Installer
  2. Look for the Visual Studio installation that you want to upgrade in the Visual Studio Installer. Click on the Update button to download and install the update.
    Update

The Visual Studio Installer may prompt you to reboot your system after completing the upgrade.

If you aren’t prompted to restart your computer, select Launch from the Visual Studio Installer to launch Visual Studio.

Method 5. Update Your Microsoft Visual Studio Extensions

The «Object reference not set to an instance of an object» error message may also appear due to outdated extensions. You should update your Microsoft Visual Studio extensions to the latest version to fix this.

  1. Open Microsoft Visual Studio and go to Tools > Extensions and Updates.
  2. Select «Updates» from the left-hand sidebar in the window that appears.
  3. If any updates are available, they will be listed here. Select the extension that you want to update and click «Update

Once the updates are finished, restart your computer and use Microsoft Visual Studio again.

Method 6. Disable Touch Keyboard and Handwriting Panel (if Applicable)

If you’re using a touchscreen device, the «Object reference not set to an instance of an object» error message may be caused by the Touch Keyboard and Handwriting Panel service. This service is known to cause conflicts with drivers and can cause problems with certain applications.

To disable this service, follow the steps below:

  1. On your keyboard, press the Windows + R keys. This will launch the Run application.
  2. Without quotation marks, type «services.msc» and hit the Enter key on your keyboard. The Services application will be launched as a result of this.
    services.msc
  3. Scroll down until you see the Touch Keyboard and Handwriting Panel service in the alphabetical list. Right-click on it, and then choose Properties from the context menu.
    Touch keyboard and handwriting panel
  4. Use the drop-down menu to change the Startup type to Disabled. When done, click Apply, close the pop-up window, and reboot your computer.
  5. After restarting your computer, see if the problem has been resolved by doing the same action that caused the «Object reference not set to an instance of an object» error.

Method 7. Temporarily Disable Your Antivirus Software

If you’re still having trouble with Microsoft Visual Studio, your antivirus software may be causing the problem. To fix this, you should temporarily disable your antivirus software and try using Microsoft Visual Studio again.

To disable your antivirus, follow these steps:

  1. Right-click on an empty space in your taskbar and choose Task Manager from the context menu.
    Task Manager
  2. Switch to the Startup tab using the header menu located at the top of the window. Here, find your antivirus application from the list and select it by clicking on it once.
  3. Click on the Disable button now visible in the bottom-right of the window. This will disable the application from launching when you start your device.
    Disable startup
  4. Restart your computer and see if you can use Visual Studio in your next startup.

TL;DR

  • Suppose you’re having trouble using Microsoft Visual Studio because of the «Object reference not set to an instance of an object» error. In that case, it might be because the application doesn’t have the necessary permissions to access certain files.
  • If you haven’t upgraded to Windows 11 yet, update your system to the latest available version!
  • To fix «Object reference not set to an instance of an object,» you should try running Microsoft Visual Studio as an administrator.
  • You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version. This will make sure no application bugs are interfering with your installation.
  • If you’re still having trouble, try updating your Microsoft Visual Studio extensions or disabling the Touch Keyboard and Handwriting Panel service (if applicable).
  • Finally, if all else fails, you can try temporarily disabling your antivirus software.

Conclusion

We hope this article was helpful in resolving the «Object reference not set to an instance of an object» error and preventing future errors similar to it. If you are still experiencing difficulties, please read more articles on our Blog or contact us for assistance.

Our team is here to help you keep your business running smoothly with the best software and technology available. Thanks for reading!

That’s all for this article on how to fix the «Object reference not set to an instance of an object» error when trying to use Microsoft Visual Studio. Be sure to check out our Blog for more great content like this!

One More Thing

Looking for more tips? Check out our other guides in our Blog or visit our Help Center for a wealth of information on how to troubleshoot various issues.

Sign up for our newsletter and access our blog posts, promotions, and discount codes early. Plus, you’ll be the first to know about our latest guides, deals, and other exciting updates!

Recommended Articles

» Process Exited With Code 1 in Command Prompt? Here’s How To Fix It
» Fix: «explorer.exe Class Not Registered» on Windows 11/10
» Fixed: Bluetooth Is Not Available on This Device on Windows 10

Feel free to reach out with questions or requests you’d like us to cover.

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

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.

Table Of Contents

  • What Is Object Reference Not Set to an Instance of an Object Error?
  • A Popular Video Fix
  • How to Fix the Object Reference Not Set to an Instance of an Object
    •  1st Fix
    • 2nd Fix
    • 3rd Fix
    • 4th Fix
    • 5th Fix
  •  Forum Feedback
  • Summing Up
    • Related Posts:

In this post, we provide 5+ fixes for the Object Reference Not Set To An Instance Of An Object Error

An extremely troublesome error that you may experience if you’re using Windows 7 is known as the object reference not set to an instance of an object error.

If ever you open up a program such as the Autodesk Data Management Server and the “object reference not set to an instance of an object” window appears, it most likely means that there’s an inconsistency in the programming. It can be fixed pretty easily if you know what to do. However, you need to know what is the root cause of the error first and work from there.

With that, we’ll discuss the main causes of the object reference not set to an instance of an object error and how to fix it. But first- check out social media and you’ll see a lot of frustrated users who are in the same boat as you:

1. World peace
2. Solve hunger
3. Give better error messages than «Object reference not set to an instance of an object»

— Troy Hunt (@troyhunt) September 29, 2016

Anyone out there using win-simple/win-acme for their letsencrypt certs and knows what this error message means when renewing? «System.NullReferenceException: Object reference not set to an instance of an object.» pic.twitter.com/D5weG5jOXu

— Scott Williams (@ip1) March 8, 2018

Object reference not set to an instance of an object is the most worthless error code to give a user

— Superkick Paulty (@paulbensonsucks) September 28, 2017

Before going to the fixes, you must first know what the error is and what causes it. Now just to give you an idea, this error is usually only shown to programmers. Non-programmers don’t usually see this error since it is usually programming related. However, non-programmers may also see them if ever there are programs used with unreferenced objects.

The main issue with this error lies in the main software trying to tell you that there is an object that it is trying to reference. However, the object can’t seem to be referenced by the software because the object doesn’t seem to exist. This could be because of certain corrupt data that has been erased. Another cause for an object not to be referenced would be a change in the settings that you weren’t aware of.

In any case, the very nature of this error is actually quite broad which means that you can’t really pinpoint the cause until you really diagnosed the software. But the general cause would be an unreferenced object.

To fix the error, we have provided several methods on how to go about it. All of these fixes are based on common, specific situations that may happen to you. Let’s check out a few of them.

A Popular Video Fix

How to Fix the Object Reference Not Set to an Instance of an Object

 1st Fix

Let’s say that you have an XML project that made the error. If that is the case, then you need to fix some of the characters in the coding. Here’s what Microsoft Support suggests that you do:

  1. Open the project that has the inherited user control
  2. Look for the characters “&” and “#”
  3. Take out these characters and use valid XML attribute characters

2nd Fix

This fix can be used if you’re using a GPMC to connect to a Windows 7 Server and use a GPO for auditing settings only to come up with the object reference not set to an instance of an object error. If this is the situation, then Microsoft Support suggests that these are the steps to take:

  1. Download a supported hotfix from the Microsoft website
  2. Open up the GPO settings
  3. Apply the hotfix on the GPMC

3rd Fix

This next fix is applicable to when you are using Autodesk Vault Products. The first thing that you have to do is try to make a diagnosis from where the error is specifically. Once you make your diagnosis, it’ll be easy to make a fix. Here’s what Autodesk Support suggests that you do:

  1. Make sure that the applications are all downloaded in a supported computer.
  2. Make sure to install all the latest updates for all Vault applications.
  3. Scan your computer to make sure that a virus isn’t the cause of the error.

4th Fix

If you think that the error is happening in the Autodesk Data Management Server (ADMS) Console, then you need to first do a diagnosis and then do a short fix. Autodesk Support also suggests some fixes that can be done:

  1. Check if all the vault servers are running properly and are properly configured
  2. Set the SQL Security settings on the database properly by ensuring that the databases are detached from the AUTODESKVAULT SQL using the ADMS Console
  3. Search for CMD in your computer, right click on it, and Run as Administrator then use the code:

C:WindowsMicrosoft.NETFramework64v4.0.30319aspnet_regiis.exe -i -enable

If you follow all these diagnosis methods and fixes, you should be able to solve the error without much trouble.

5th Fix

If ever the error is happening only with certain CAD data files, then you need to open up the Inventor and try to check the links. Autodesk Support also has some ways on how to fix these kinds of situations:

  1. Boot up the file that’s located in the Inventor.
  2. Click on the Tools tab and then click on the Links option.
  3. Click on the specific linked file and click on the Break Link option.
  4. Scan the Autoloader again.

 Forum Feedback

To find out more about the object reference is not set to an instance of an object we looked through different forums and message boards. In general, people were interested in object reference is not set to an instance of an object #C, object reference is not set to an instance of an object Unity/Trados/ #C array, and object reference is not set to an instance of an object connection string.

c What is a NullReferenceException and how do I fix it Stack Overflow

A novice to programming said that he kept getting the same mistake that an object reference not set to an instance of an object. He didn’t know how to fix it, so he reached out to the community.

They explained that he had run into a case of NullReferenceException. In simple words, he was trying to use something that was null and didn’t exist.

Another poster explained that if you get the object reference not set to an instance of an object you might have forgotten to assign a value to your variables. As a result, your code wouldn’t execute because the variable wasn’t initialized. The solution would be to debug and check which line would throw the exception. Then you should change your variables so that they don’t point to something that doesn’t exist.

A computer expert observes that the object reference not set to an instance of an object error almost always means that the user is trying to use a reference that hasn’t been initialized. He advises that you should follow the general rules of debugging when you’re using Visual Studio. In other words, you should inspect your variables by hovering with the mouse over the names or use debugging panels. The other thing you can do to avoid object reference errors is to place breakpoints so that you can check the values of your variables easily.

If I could go the rest of my life without seeing another NullReferenceException/NullPointerException «Object reference not set to an instance of an object» error… I’d be really really happy.

— Eaglebutt (@colinstu) March 7, 2019

Another forum member states that you can avoid the object reference not set to an instance of an object by explicitly checking for null and providing a default value to return when the object can’t be found. He also advised that you work with Debug.Assert when you use values that should never return null so that you can catch the issues immediately.

A person says that when you encounter “Object reference not set to an instance of an object,” it doesn’t necessarily mean that you haven’t initialized an object.

  • He explains that it’s possible that you have declared and initialized the object, but something in your code has invalidated the object.
  • Another possible explanation would be that something in the code should have initialized an object, but it didn’t.
  • However, he adds that you can find the culprit easily by hovering over the valuables because Visual Studio gives you their values.
  • You just have to look for the one labeled “Nothing” and take care of that value.

@nodexl @marc_smith I am getting an error on startup for NodeXL Pro. After the initial pop-up it says «Object reference not set to an instance of this object.» I have removed the old license file and put in a new one as recommend on the webpage, but nothing changes.

— Nick Watanabe (@watanabe2k) October 8, 2018

Another user commented that to debug object reference not set to an instance of an object you can use Debug -> Windows -> Locals. It allows you to examine your objects and find the ones that are throwing the exception. He also mentions that you should use “New” to initiate an instance when you’re declaring one. The poster explains that a lot of the object reference error he sees are due to the lack of “New” operator.

An individual also points out that you might get that mistake if you’re working with arrays and you haven’t instantiated them. He says that declaring an array doesn’t create it so that you have to initialize it afterward. The user clarifies that lists and collections also must be created or instantiated or you’ll get an object reference error. He advises that you pay special attention to classes, which use a collection “Type” because that’s very common oversight.

A forum user also remarks that another way to get the object reference not set to an instance of an object is if you have assigned a value to a null object. He recommends that you always check if an object that could be null is null. The person also says that you might have made a function in your code that had set the variable of the object to null and that you have to check the lines where the error has been thrown.

A person also remarks that incorrect use of the “as” might also result in NullReferenceException. The user comments that such errors are easy to fix in Visual Studio thanks to the Visual Studio Debugger and recommends that you read how to use it.

Summing Up

Those are some of the most common situations in which you might encounter the object reference not set to an instance of an object error. In the event that you experience any of the situations that we have mentioned above, you may use some of the fixes and diagnosis tips provided per fix. These fixes are suggested by both support teams of Microsoft and Autodesk, so they are proven to work.

If the problem still continues to persist no matter what fix you try to do, then the best thing to do would be to call in an expert to help you. As mentioned above, this type of error is an extremely broad and generic error which is caused by the individual application that you’re using. The root cause would really depend on what happened inside that application.

So the best way would be to contact the support service behind the application and ask them for assistance. They will be the best people to help you with the problem in the event that a DIY diagnosis and a DIY fix can’t seem to work.

Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Object reference not set to an instance of an object tarkov как исправить
  • Object reference not set to an instance of an object cities skylines ошибка
  • Object prototype may only be an object or null wink ошибка как исправить
  • Object processing error касперский
  • Object of type int has no len python ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии