Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// <Snippet12>
using System;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.Serialization;

public class NullReferenceExample
{
public static void Main()
{
var listType = GetListType();
var listObj = GetList(listType);
}

private static Type GetListType()
{
return typeof(List<int>);
}

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 Example.GetList(Type type): line 24
// </Snippet12>
6 changes: 6 additions & 0 deletions xml/System/NullReferenceException.xml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,12 @@ A <xref:System.NullReferenceException> 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 <xref:System.NullReferenceException>: `callvirt`, `cpblk`, `cpobj`, `initblk`, `ldelem.<type>`, `ldelema`, `ldfld`, `ldflda`, `ldind.<type>`, `ldlen`, `stelem.<type>`, `stfld`, `stind.<type>`, `throw`, and `unbox`.

<xref:System.NullReferenceException> uses the HRESULT `COR_E_NULLREFERENCE`, which has the value 0x80004003.
Expand Down