What is nullreferenceException?
NULLREFERENCEPTION is an abnormal runtime in C#, and it happens when you try to access the members of the empty object. This may happen in the following circumstances:
The method of trying to call the empty object. -
Try to access the attributes of the empty object. -
Try to cancel the reference empty pointer. -
How to solve it?
There are several ways to solve the NULLREFERENCEEXCEUON method:
Check the empty value before visiting the members. - Before accessing any member of the object, you should always check whether the object is empty. You can use if statement, as shown in the following example:
<code class="language-csharp">if (object != null)
{
// 访问对象的成员。
}</code>
Copy after login
Use the air merger operator.
The air merger computing (??) allows you to specify the default values used if the object is empty. For example, if the object is not empty, the value of the name attribute is returned; if the object is empty, return "unknown": -
Use the empty condition operator.
<code class="language-csharp">string name = object?.Name ?? "Unknown";</code>
Copy after login
Conditional operator (?. And? []) Allowed you to access the members of the object without checking the empty value in advance. For example, if the object is not empty, the value of the name attribute is returned; if the object is empty, return null:
You can also use the TRY/CATCH block to process NullReferenceExceptions. For example, the following code will process NULLREFERENCEEXCEUON and print a message to the console:
<code class="language-csharp">string name = object?.Name;</code>
Copy after login
The above is the detailed content of How Can I Prevent and Handle NullReferenceExceptions in C#?. For more information, please follow other related articles on the PHP Chinese website!