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

Причина

Вкратце

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

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.

What does «Object reference not set to an instance of an object» mean? [duplicate]

I am receiving this error and I’m not sure what it means?

Object reference not set to an instance of an object.

8 Answers 8

Variables in .NET are either reference types or value types. Value types are primitives such as integers and booleans or structures (and can be identified because they inherit from System.ValueType). Boolean variables, when declared, have a default value:

Reference types, when declared, do not have a default value:

If you try to access a member of a class instance using a null reference then you get a System.NullReferenceException. Which is the same as Object reference not set to an instance of an object.

The following code is a simple way of reproducing this:

This is a very common error and can occur because of all kinds of reasons. The root cause really depends on the specific scenario that you’ve encountered.

If you are using an API or invoking methods that may return null then it’s important to handle this gracefully. The main method above can be modified in such a way that the NullReferenceException should never be seen by a user:

All of the above really just hints of .NET Type Fundamentals, for further information I’d recommend either picking up CLR via C# or reading this MSDN article by the same author — Jeffrey Richter. Also check out, much more complex, example of when you can encounter a NullReferenceException.

Some teams using Resharper make use of JetBrains attributes to annotate code to highlight where nulls are (not) expected.

5+ Fixes For The Object Reference Not Set To An Instance Of An Object Error

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

What Is Object Reference Not Set to an Instance of an Object Error?

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.

Что означает «Объектная ссылка, не установленная на экземпляр объекта»?

Ссылка на объект не установлена ​​в экземпляр объекта.

ОТВЕТЫ

Ответ 1

Переменные в .NET являются либо ссылочными типами, либо типами значений. Типы значений — это примитивы, такие как целые числа и booleans или структуры ( и их можно идентифицировать, поскольку они наследуют от System.ValueType). Логические переменные, объявленные, имеют значение по умолчанию:

Типы ссылок, если они объявлены, не имеют значения по умолчанию:

Если вы попытаетесь получить доступ к члену экземпляра класса с использованием нулевой ссылки, вы получите System.NullReferenceException. Это то же самое, что и ссылка объекта, не установленная на экземпляр объекта.

Следующий код является простым способом воспроизведения этого:

Это очень распространенная ошибка и может возникнуть из-за всех причин. Основная причина действительно зависит от конкретного сценария, с которым вы столкнулись.

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

Все вышесказанное на самом деле просто подсказывает основы .NET Type. Для получения дополнительной информации я бы рекомендовал либо собрать CLR через С#, либо прочитать это статья MSDN того же автора — Джеффри Рихтера. Также проверьте, намного сложнее пример, когда вы можете встретить исключение NullReferenceException.

Некоторые команды, использующие Resharper, используют атрибуты JetBrains для комментирования кода, чтобы выделить, где ожидаются (не) нули.

Ответ 2

Еще один простой способ получить это:

Ответ 3

Не быть тупым, но это означает именно то, что он говорит. Одна из ваших ссылок на объекты — NULL. Вы увидите это при попытке доступа к свойству или методу объекта NULL’d.

Ответ 4

В двух словах это означает, что вы пытаетесь получить доступ к объекту, не создавая его. Возможно, вам нужно будет использовать ключевое слово «new», чтобы создать его экземпляр вначале. Создайте его экземпляр.

Вам нужно будет использовать:

Надеюсь, я дал понять.

Ответ 5

Это означает, что вы сделали что-то вроде этого.

И без делать

if(myObject!=null) , вы продолжаете делать myObject.Method();

Ответ 6

что означает эта ошибка? Ссылка на объект не установлена ​​в экземпляр объекта.

точно, что он говорит, вы пытаетесь использовать нулевой объект, как если бы он был правильно ссылочный объект.

Ответ 7

В большинстве случаев, когда вы пытаетесь определить значение в объекте, а если значение равно null, возникает такое исключение. Пожалуйста, проверьте эту ссылку.

для самообучения вы можете поместить некоторые условия проверки. как

Ответ 8

Я столкнулся с проблемой, пока я пытался работать с приложением Smartcard, у нее есть один компонент COM, который скомпилирован с помощью платформы dot net 2.0 нашими старшими разработчиками, когда я пытался использовать эти компоненты DLL с моим проектом, который был разработан в рамках 4.0. Когда VS 2010 конвертирует это приложение vs2008 в vs2010, я получил ссылку «Ссылка на объект», не установленную в экземпляр объекта.. Когда я попытался отслеживать, я обнаружил, что ошибка находится на нескольких формах, которые используя эту ссылочную dll (которая скомпилирована с фреймворком 2.0).

Я открыл файл resx этих форм и изменил строку ниже

Итак, что я изменил здесь, я просто изменил его версию 4.0.0.0 на 2.0.0.0, и он отлично работает.

Я думаю, что это понижающий, но не весь проект, только несколько форм находятся под фреймворком 2.0, и это вообще не повлияет на проект.

Ответ 9

Если у меня есть класс:

а затем выполните:

Вторая строка вызывает это исключение, потому что я вызываю метод на ссылочном типе, который null (т.е. созданный путем вызова myClass = new MyClass() )

Ошибка «Object reference not set to an instance of an object» расшифровывается как «Ссылка не указывает на экземпляр объекта».

Данная ошибка означает, что происходит попытка обратиться к null, т.е. к тому, чего не существует. Рассмотрим пример:

using System;

public class Program

{

static string someString;

public static void Main()

{

Console.WriteLine(someString[0]);

}

}

При попытке запустить такую программу в среде разработки получаем ошибку

Run-time exception (line 8): Object reference not set to an instance of an object.

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.]
at Program.Main() :line 8

В данном случае происходит попытка обратиться к первому символу строки someString, но поскольку там нет никакого значения, а отсутствие значения означает null для string, поэтому происходит ошибка Nullreferenceexception «Object reference not set to an instance of an object».

Попробуем пофиксить ошибку «Ссылка не указывает на экземпляр объекта», присвоим значение строке someString:

using System;

public class Program

{

static string someString;

public static void Main()

{

someString = «some»;

Console.WriteLine(someString[0]);

}

}

Запустим программу и увидим результат, как мы и хотели — получили первый символ строки someString, в данном случае был выведен результат — первая буква s.

Я получаю эту ошибку, и я не уверен, что это значит?

Ссылка на объект не установлена ​​в экземпляр объекта.

Ответ 1

Переменные в .NET являются либо ссылочными типами, либо типами значений. Типы значений — это примитивы, такие как целые числа и booleans или структуры ( и их можно идентифицировать, поскольку они наследуют от System.ValueType). Логические переменные, объявленные, имеют значение по умолчанию:

bool mybool;
//mybool == false

Типы ссылок, если они объявлены, не имеют значения по умолчанию:

class ExampleClass
{
}

ExampleClass exampleClass; //== null

Если вы попытаетесь получить доступ к члену экземпляра класса с использованием нулевой ссылки, вы получите System.NullReferenceException. Это то же самое, что и ссылка объекта, не установленная на экземпляр объекта.

Следующий код является простым способом воспроизведения этого:

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();
    returnedClass.AnotherExampleMethod(); //NullReferenceException here.
}

class ExampleClass
{
    public ReturnedClass ExampleMethod()
    {
        return null;
    }
}

class ReturnedClass
{
    public void AnotherExampleMethod()
    {
    }
}

Это очень распространенная ошибка и может возникнуть из-за всех причин. Основная причина действительно зависит от конкретного сценария, с которым вы столкнулись.

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

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();

    if (returnedClass == null)
    {
        //throw a meaningful exception or give some useful feedback to the user!
        return;
    }

    returnedClass.AnotherExampleMethod();
}

Все вышесказанное на самом деле просто подсказывает основы .NET Type. Для получения дополнительной информации я бы рекомендовал либо собрать CLR через С#, либо прочитать это статья MSDN того же автора — Джеффри Рихтера. Также проверьте, намного сложнее пример, когда вы можете встретить исключение NullReferenceException.

Некоторые команды, использующие Resharper, используют атрибуты JetBrains для комментирования кода, чтобы выделить, где ожидаются (не) нули.

Ответ 2

Еще один простой способ получить это:

 Person myPet = GetPersonFromDatabase();
 // check for myPet == null... AND for myPet.PetType == null
 if ( myPet.PetType == "cat" ) <--- fall down go boom!

Ответ 3

Не быть тупым, но это означает именно то, что он говорит. Одна из ваших ссылок на объекты — NULL. Вы увидите это при попытке доступа к свойству или методу объекта NULL’d.

Ответ 4

В двух словах это означает, что вы пытаетесь получить доступ к объекту, не создавая его. Возможно, вам нужно будет использовать ключевое слово «new», чтобы создать его экземпляр вначале. Создайте его экземпляр.

Например,

public class MyClass
{
   public int Id {get; set;}
}

MyClass myClass;

myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...

Вам нужно будет использовать:

myClass = new MyClass();
myClass.Id = 0;

Надеюсь, я дал понять.

Ответ 5

Это означает, что вы сделали что-то вроде этого.

Class myObject = GetObjectFromFunction();

И без делать

if(myObject!=null), вы продолжаете делать myObject.Method();

Ответ 6

что означает эта ошибка? Ссылка на объект не установлена ​​в экземпляр объекта.

точно, что он говорит, вы пытаетесь использовать нулевой объект, как если бы он был правильно
ссылочный объект.

Ответ 7

В большинстве случаев, когда вы пытаетесь определить значение в объекте, а если значение равно null, возникает такое исключение.
Пожалуйста, проверьте эту ссылку.

для самообучения вы можете поместить некоторые условия проверки. как

if (myObj== null)
Console.Write("myObj is NULL");

Ответ 8

Я столкнулся с проблемой, пока я пытался работать с приложением Smartcard, у нее есть один компонент COM, который скомпилирован с помощью платформы dot net 2.0 нашими старшими разработчиками, когда я пытался использовать эти компоненты DLL с моим проектом, который был разработан в рамках 4.0. Когда VS 2010 конвертирует это приложение vs2008 в vs2010, я получил ссылку «Ссылка на объект», не установленную в экземпляр объекта.. Когда я попытался отслеживать, я обнаружил, что ошибка находится на нескольких формах, которые используя эту ссылочную dll (которая скомпилирована с фреймворком 2.0).

Я открыл файл resx этих форм и изменил строку ниже

    <metadata name="ErrorProvider1.TrayLocation" type="System.Drawing.Point, System.Drawing, **Version=4.0.0.0**, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">

Для

     <metadata name="ErrorProvider1.TrayLocation" type="System.Drawing.Point, System.Drawing, **Version=2.0.0.0**, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">

Итак, что я изменил здесь, я просто изменил его версию 4.0.0.0 на 2.0.0.0, и он отлично работает.

Я думаю, что это понижающий, но не весь проект, только несколько форм находятся под фреймворком 2.0, и это вообще не повлияет на проект.

Ответ 9

Если у меня есть класс:

public class MyClass
{
   public void MyMethod()
   {

   }
}

а затем выполните:

MyClass myClass = null;
myClass.MyMethod();

Вторая строка вызывает это исключение, потому что я вызываю метод на ссылочном типе, который null (т.е. созданный путем вызова myClass = new MyClass())

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