Skip to content

Commit 34b0da6

Browse files
authored
Addition to Null Reference Exception (#10967)
1 parent 130639c commit 34b0da6

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// <Snippet12>
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Collections;
5+
using System.Runtime.Serialization;
6+
7+
public class NullReferenceExample
8+
{
9+
public static void Main()
10+
{
11+
var listType = GetListType();
12+
_ = GetList(listType);
13+
}
14+
15+
private static Type GetListType()
16+
{
17+
return typeof(List<int>);
18+
}
19+
20+
private static IList GetList(Type type)
21+
{
22+
var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor
23+
var value = 1;
24+
emptyList.Add(value);
25+
return emptyList;
26+
}
27+
}
28+
// The example displays output like the following:
29+
// Unhandled Exception: System.NullReferenceException: 'Object reference
30+
// not set to an instance of an object.'
31+
// at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
32+
// at NullReferenceExample.GetList(Type type): line 24
33+
// </Snippet12>

xml/System/NullReferenceException.xml

+6
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,12 @@ A <xref:System.NullReferenceException> exception is thrown when you try to acces
154154
155155
To address this issue, make sure that the argument passed to the method is not `null`, or handle the thrown exception in a `try…catch…finally` block. For more information, see [Exceptions](/dotnet/standard/exceptions/).
156156
157+
- A list is created without knowing the type, and the list was not initialized. The `GetList` method in the following example throws the exception at the line `emptyList.Add(value)`.
158+
159+
:::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/example3.cs" id="Snippet12":::
160+
161+
To address this issue, make sure that the list is initialized (one way to do this is to call `Activator.CreateInstance` instead of `FormatterServices.GetUninitializedObject`), or handle the thrown exception in a `try…catch…finally` block. For more information, see [Exceptions](/dotnet/standard/exceptions/).
162+
157163
The following Microsoft intermediate language (MSIL) instructions throw <xref:System.NullReferenceException>: `callvirt`, `cpblk`, `cpobj`, `initblk`, `ldelem.<type>`, `ldelema`, `ldfld`, `ldflda`, `ldind.<type>`, `ldlen`, `stelem.<type>`, `stfld`, `stind.<type>`, `throw`, and `unbox`.
158164
159165
<xref:System.NullReferenceException> uses the HRESULT `COR_E_NULLREFERENCE`, which has the value 0x80004003.

0 commit comments

Comments
 (0)