Nullreferenceexception rust как исправить

Обновлено: 18.05.2024

I have some code and when it executes, it throws a NullReferenceException , saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do to fix this error?

Dear future visitors, the answers to this question equally apply to an ArgumentNullException. If your question has been closed as a duplicate of this one, and you are experiencing an ANE, please follow the directions in the answers to debug and fix your problem. @will ANE should only happen if a null is passed as a parameter. Can you give an example if an ANE question closed as a duplicate of this one? Comments disabled on deleted / locked posts / reviews |

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

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

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

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

What is the cause?

Debugging

How do you find the source of a NullReferenceException ? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable, and verify that it points to an instance when you expect it to.

By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.

More Specifically

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).

This means the reference is null , and you cannot access members (such as methods) through a null reference. The simplest case:

This will throw a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null .

Examples

Some common scenarios where the exception can be thrown:

Generic

If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException . If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:

Indirect

If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.

Nested Object Initializers

The same applies to nested object initializers:

This translates to:

While the new keyword is used, it only creates a new instance of Book , but not a new instance of Person , so the Author the property is still null .

Nested Collection Initializers

The nested collection Initializers behave the same:

This translates to:

The new Person only creates an instance of Person , but the Books collection is still null . The collection Initializer syntax does not create a collection for p1.Books , it only translates to the p1.Books.Add(. ) statements.

Array

Array Elements

Jagged Arrays

Collection/List/Dictionary

Range Variable (Indirect/Deferred)

Bad Naming Conventions:

If you named fields differently from locals, you might have realized that you never initialized the field.

WPF Control Creation Order and Events

WPF controls are created during the call to InitializeComponent in the order they appear in the visual tree. A NullReferenceException will be raised in the case of early-created controls with event handlers, etc., that fire during InitializeComponent which reference late-created controls.

Here comboBox1 is created before label1 . If comboBox1_SelectionChanged attempts to reference `label1, it will not yet have been created.

Changing the order of the declarations in the XAML (i.e., listing label1 before comboBox1 , ignoring issues of design philosophy) would at least resolve the NullReferenceException here.

Cast with as

This doesn't throw an InvalidCastException but returns a null when the cast fails (and when someObject is itself null). So be aware of that.

LINQ FirstOrDefault() and SingleOrDefault()

The plain versions First() and Single() throw exceptions when there is nothing. The "OrDefault" versions return null in that case. So be aware of that.

foreach

foreach throws when you try to iterate on a null collection. Usually caused by unexpected null result from methods that return collections.

More realistic example - select nodes from XML document. Will throw if nodes are not found but initial debugging shows that all properties valid:

Ways to Avoid

Explicitly check for null and ignore null values.

If you expect the reference sometimes to be null , you can check for it being null before accessing instance members:

Explicitly check for null and provide a default value.

Methods you call expecting an instance can return null , for example when the object being sought cannot be found. You can choose to return a default value when this is the case:

Explicitly check for null from method calls and throw a custom exception.

You can also throw a custom exception, only to catch it in the calling code:

Use Debug.Assert if a value should never be null , to catch the problem earlier than the exception occurs.

When you know during development that a method could, but never should return null , you can use Debug.Assert() to break as soon as possible when it does occur:

Though this check will not end up in your release build, causing it to throw the NullReferenceException again when book == null at runtime in release mode.

Use GetValueOrDefault() for nullable value types to provide a default value when they are null .

The shorthand to providing a default value when a null is encountered:

This is also sometimes called the safe navigation or Elvis (after its shape) operator. If the expression on the left side of the operator is null, then the right side will not be evaluated, and null is returned instead. That means cases like this:

If the person does not have a title, this will throw an exception because it is trying to call ToUpper on a property with a null value.

This will result in the title variable being null , and the call to ToUpper is not made if person.Title is null .

Of course, you still have to check title for null or use the null condition operator together with the null coalescing operator ( ?? ) to supply a default value:

Likewise, for arrays you can use ?[i] as follows:

This will do the following: If myIntArray is null , the expression returns null and you can safely check it. If it contains an array, it will do the same as: elem = myIntArray[i]; and returns the i th element.

A nullable reference type is noted using the same syntax as nullable value types: a ? is appended to the type of the variable.

Special techniques for debugging and fixing null derefs in iterators

If whatever results in null then MakeFrob will throw. Now, you might think that the right thing to do is this:

Why is this wrong? Because the iterator block does not actually run until the foreach ! The call to GetFrobs simply returns an object which when iterated will run the iterator block.

By writing a null check like this you prevent the NullReferenceException , but you move the NullArgumentException to the point of the iteration, not to the point of the call, and that is very confusing to debug.

The correct fix is:

That is, make a private helper method that has the iterator block logic and a public surface method that does the null check and returns the iterator. Now when GetFrobs is called, the null check happens immediately, and then GetFrobsForReal executes when the sequence is iterated.

If you examine the reference source for LINQ to Objects you will see that this technique is used throughout. It is slightly more clunky to write, but it makes debugging nullity errors much easier. Optimize your code for the convenience of the caller, not the convenience of the author.

A note on null dereferences in unsafe code

In unsafe mode, you should be aware of two important facts:

  • dereferencing a null pointer produces the same exception as dereferencing a null reference
  • dereferencing an invalid non-null pointer can produce that exception in some circumstances

Memory is virtualized in Windows ; each process gets a virtual memory space of many "pages" of memory that are tracked by the operating system. Each page of memory has flags set on it that determine how it may be used: read from, written to, executed, and so on. The lowest page is marked as "produce an error if ever used in any way".

That's why dereferencing both a null pointer and a null reference produces the same exception.

What about the second point? Dereferencing any invalid pointer that falls in the lowest page of virtual memory causes the same operating system error, and thereby the same exception.

Why does this make sense? Well, suppose we have a struct containing two ints, and an unmanaged pointer equal to null. If we attempt to dereference the second int in the struct, the CLR will not attempt to access the storage at location zero; it will access the storage at location four. But logically this is a null dereference because we are getting to that address via the null.

If you are working with unsafe code and you get a NullReferenceException , just be aware that the offending pointer need not be null. It can be any location in the lowest page, and this exception will be produced.

30 ноя. 2017 в 17:47

- open your rust console by pressing [f1]
- Type: effects.showoutlines 0
- press [enter]

NOTE: When rust has the update for MAC, it can be that you need to do this again and turn the 0 into 1 to enable the outlines again!

30 ноя. 2017 в 18:24 please comment bellow if this works, so everybody can see this ;) 30 ноя. 2017 в 18:34 i didnt play since the update but is this a thing that pops up in red text and freezes the game? It happened to me 3 times last week. 30 ноя. 2017 в 18:42 i didnt play since the update but is this a thing that pops up in red text and freezes the game? It happened to me 3 times last week.

This is a fix for everybody that got kicked out of the server and shows the "nullreferenceexception" message. It is mostly on Mac, and after this last update.

Do you mean the red text on the left-top corner sometimes?
I also seeing this sometimes almost over a month now and think it's another problem.
Because I was not able to take screenshot or read fast enough I was not able to post this issue.

30 ноя. 2017 в 19:28 30 ноя. 2017 в 19:35 30 ноя. 2017 в 19:42

THANK YOU ILL LET YOU KNOW IF IT WORKS

30 ноя. 2017 в 19:47

it works.. this guy is smarter than facepunch studios

30 ноя. 2017 в 22:00 30 ноя. 2017 в 22:09 I got the same problem here, but what do you mean by "open rust console by pressing f1"? sorry i don't it bro. Mac user as well here

Press the "F1" key which opens the console. Or if you've adjusted settings at all for keyboard bindings, press the "fn" and "F1" keys together. Once open, input the text as written above, then press enter.

Confirmed this worked. Thanks for the bandaid!

1 дек. 2017 в 5:13 I'm not smarter than Facepunch studios, I just know my things.
Don't say stupid things please :p 22 сен. 2018 в 4:57 13 окт. 2018 в 7:28 Maybe because this was about an issue half a year ago lol 18 янв. 2019 в 5:15 i didnt play since the update but is this a thing that pops up in red text and freezes the game? It happened to me 3 times last week.

This is a fix for everybody that got kicked out of the server and shows the "nullreferenceexception" message. It is mostly on Mac, and after this last update.

Do you mean the red text on the left-top corner sometimes?
I also seeing this sometimes almost over a month now and think it's another problem.
Because I was not able to take screenshot or read fast enough I was not able to post this issue.
Sending to you a screenshot in the Discord. I'm having this issue with no luck.

Object reference not set to an instance of an object.

В экземпляре объекта не задана ссылка на объект.


55.2k 7 7 золотых знаков 62 62 серебряных знака 134 134 бронзовых знака


30.5k 18 18 золотых знаков 75 75 серебряных знаков 98 98 бронзовых знаков Добавил важный каноничный ответ с английского SO What is a NullReferenceException and how do I fix it?. Теперь можно закрывать большинство вопросов про NRE как дубль, а не ковыряться с каждым отдельным случаем. Всё равно почти всегда одно и то же.

Bottom Line

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

null can have different meanings:

The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException .

Причина

Отладка

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

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

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

Примеры

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

Цепочка

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

Неявно

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

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

Массив

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

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

Collection/List/Dictionary

События

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


30.5k 18 18 золотых знаков 75 75 серебряных знаков 98 98 бронзовых знаков @VladD Есть слишком много случаев, когда null — допустимое значение: ленивая инициализация, отсутствие значения "не задано" у типа и т. п. Не везде получается избавиться от null. Так что рекомендация сводится к "старайтесь не использовать null, если это возможно". Это да, есть случаи, когда null валиден. Тогда, вероятно, первым вопросом должно быть: валиден ли null в этой точке? Если да, нужна проверка на null и адекватная реакция. Если нет, то код верен, а проблема где-то раньше (скорее всего в инициализации).

В дополнение к ответу @Discord @Squidward @Athari @Kyubey, давайте рассмотрим вопрос с другой стороны.

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

а имеет ли право эта ссылка иметь значение null ?

Во многих случаях правильным ответом будет «нет», и значит, исправлять придётся истинную причину ошибки, которая находится в другом месте, и произошла раньше.

Пример: если у вас есть такой класс:

Так вот, мотор у машины быть обязан в любом случае, всегда. А вот водитель может в принципе и не сидеть в машине.

Поэтому если вы видите, что обращение к engine.HorsePower падает с NullReferenceException , реальная проблема состоит в том, что вы забыли инициализировать engine в конструкторе. Поэтому и исправлять ошибку нужно не в точке, где падает, а в том месте, которое реально должно бы обеспечить ненулевое значение engine .

А вот если вылетает обращение driver.Age , то здесь уже проблема прямо в точке обращения, вам необходимо сначала проверить, что driver != null , а потом уж обращаться.

Если же ссылка имеет право быть null -ом, то в этом случае нужно корректно обработать и этот случай.

Важное замечание: Если вашу функцию вызывает «внешний мир», вы не должны рассчитывать, что вашей функции передадут хорошие, правильные аргументы. Даже если вы требуете, чтобы объект, который вам передан, не был null -ом, всё равно вам могут передать неправильный объект. Поэтому для функций, доступных внешним модулям, необходимо проверять аргументы на null сразу же в начале кода, и бросать нужное исключение:

Где именно проводить границу между «внутренним» и «внешним» миром, вопрос достаточно нетривиальный. Обычно эта граница есть граница модуля (сборки), или даже той её логической части, которая находится в вашей ответственности. Слишком мелкое дробление ведёт к повторению бессмысленного кода (одна часть программы не доверяет другой и постоянно перепроверяет её). Слишком крупное дробление ведёт к необходимости держать в голове миллионы зависимостей («могу я тут передавать null или нет?»). Пользуйтесь здравым смыслом и личным опытом.

В этом случае сам компилятор сможет проконтролировать, что вы забыли проинициализировать значение поля engine , и выдать вам предупреждение.

Вкратце

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

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

Ошибка NullReferenceException: Object reference not set to an instance of an object [дубликат]

указывающую на строку

Не понимаю сути ошибки.

11.7k 2 2 золотых знака 13 13 серебряных знаков 26 26 бронзовых знаков 518 1 1 золотой знак 5 5 серебряных знаков 24 24 бронзовых знака

Суть ошибки NullReferenceException - вы пытаетесь что-то сделать со ссылочной переменной, которая имеет значение null. т.е. mContr на момент вашего обращения к ней ничего не назначено и эта переменная указывает в пустоту. Как следствие вызов метода у пустоты выдаёт ошибку.

А раз там пусто, значит нижеприведённая строчка кода ничего не находит. Не стоит делать такие длинные цепочки вызовов, когда вы не уверены, что всё и везде назначено. Как вариант, хотя бы, ставьте проверку, чтобы знать сразу, что всё плохо. Например, так:

5,048 1 1 золотой знак 9 9 серебряных знаков 16 16 бронзовых знаков

27 Answers 27

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