diff --git a/snippets/csharp/System/NullReferenceException/Overview/example3.cs b/snippets/csharp/System/NullReferenceException/Overview/example3.cs new file mode 100644 index 00000000000..2ce0700f112 --- /dev/null +++ b/snippets/csharp/System/NullReferenceException/Overview/example3.cs @@ -0,0 +1,33 @@ +// +using System; +using System.Collections.Generic; +using System.Collections; +using System.Runtime.Serialization; + +public class NullReferenceExample +{ + public static void Main() + { + var listType = GetListType(); + _ = GetList(listType); + } + + private static Type GetListType() + { + return typeof(List); + } + + private static IList GetList(Type type) + { + var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor + var value = 1; + emptyList.Add(value); + return emptyList; + } +} +// The example displays output like the following: +// Unhandled Exception: System.NullReferenceException: 'Object reference +// not set to an instance of an object.' +// at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item) +// at NullReferenceExample.GetList(Type type): line 24 +// diff --git a/xml/System/NullReferenceException.xml b/xml/System/NullReferenceException.xml index 5b6186724c3..4512cc05ae3 100644 --- a/xml/System/NullReferenceException.xml +++ b/xml/System/NullReferenceException.xml @@ -154,6 +154,12 @@ A exception is thrown when you try to acces 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/). +- 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)`. + + :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/example3.cs" id="Snippet12"::: + + 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/). + The following Microsoft intermediate language (MSIL) instructions throw : `callvirt`, `cpblk`, `cpobj`, `initblk`, `ldelem.`, `ldelema`, `ldfld`, `ldflda`, `ldind.`, `ldlen`, `stelem.`, `stfld`, `stind.`, `throw`, and `unbox`. uses the HRESULT `COR_E_NULLREFERENCE`, which has the value 0x80004003.