{"id":3835,"date":"2022-08-20T19:18:22","date_gmt":"2022-08-20T13:48:22","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/"},"modified":"2022-08-20T19:18:22","modified_gmt":"2022-08-20T13:48:22","slug":"solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/","title":{"rendered":"(Solved) What is a NullReferenceException, and how do I fix it?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-4660186\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"4660186\" data-parentid=\"4660142\" data-score=\"2633\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<h1>What is the cause?<\/h1>\n<h2>Bottom Line<\/h2>\n<p>You are trying to use something that is <code>null<\/code> (or <code>Nothing<\/code> in VB.NET). This means you either set it to <code>null<\/code>, or you never set it to anything at all.<\/p>\n<p>Like anything else, <code>null<\/code> gets passed around. If it is <code>null<\/code> <em>in<\/em> method &#8220;A&#8221;, it could be that method &#8220;B&#8221; passed a <code>null<\/code> <em>to<\/em> method &#8220;A&#8221;.<\/p>\n<p><code>null<\/code> can have different meanings:<\/p>\n<ol>\n<li>Object variables that are <strong>uninitialized<\/strong> and hence <strong>point to nothing.<\/strong> In this case, if you access members of such objects, it causes a <code>NullReferenceException<\/code>.<\/li>\n<li>The developer is <strong>using <code>null<\/code> intentionally to indicate there is no meaningful value available.<\/strong> Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) &#8211; you can assign <code>null<\/code> to them to indicate there is no value stored in it, for example <code>int? a = null;<\/code> (which is a shortcut for <code>Nullable&lt;int&gt; a = null;<\/code>) where the question mark indicates it is allowed to store <code>null<\/code> in variable <code>a<\/code>. You can check that either with <code>if (a.HasValue) {...}<\/code> or with <code>if (a==null) {...}<\/code>. Nullable variables, like <code>a<\/code> this example, allow to access the value via <code>a.Value<\/code> explicitly, or just as normal via <code>a<\/code>. <br \/><strong>Note<\/strong> that accessing it via <code>a.Value<\/code> throws an <code>InvalidOperationException<\/code> instead of a <code>NullReferenceException<\/code> if <code>a<\/code> is <code>null<\/code> &#8211; you should do the check beforehand, i.e. if you have another non-nullable variable <code>int b;<\/code> then you should do assignments like <code>if (a.HasValue) { b = a.Value; }<\/code> or shorter <code>if (a != null) { b = a; }<\/code>.<\/li>\n<\/ol>\n<p>The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a <code>NullReferenceException<\/code>.<\/p>\n<h2>More Specifically<\/h2>\n<p>The <code>runtime<\/code> throwing a <code>NullReferenceException<\/code> <strong>always<\/strong> means the same thing: you are trying to use a reference, and the reference is not initialized (or it was <em>once<\/em> initialized, but is <em>no longer<\/em> initialized).<\/p>\n<p>This means the reference is <code>null<\/code>, and you cannot access members (such as methods) through a <code>null<\/code> reference. The simplest case:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>string foo = null;\nfoo.ToUpper();\n<\/code><\/pre>\n<p>This will throw a <code>NullReferenceException<\/code> at the second line because you can&#8217;t call the instance method <code>ToUpper()<\/code> on a <code>string<\/code> reference pointing to <code>null<\/code>.<\/p>\n<h1>Debugging<\/h1>\n<p>How do you find the source of a <code>NullReferenceException<\/code>? 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 <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.microsoft.com\/en-us\/visualstudio\/debugger\/debugger-windows\">inspect your variables<\/a>, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.<\/p>\n<p>If you want to find out where the reference is or isn&#8217;t set, right-click its name and select &#8220;Find All References&#8221;. 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.<\/p>\n<p>By following the program flow this way, you can find the location where the instance should not be null, and why it isn&#8217;t properly set.<\/p>\n<h1>Examples<\/h1>\n<p>Some common scenarios where the exception can be thrown:<\/p>\n<h3>Generic<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>ref1.ref2.ref3.member\n<\/code><\/pre>\n<p>If ref1 or ref2 or ref3 is null, then you&#8217;ll get a <code>NullReferenceException<\/code>. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>var r1 = ref1;\nvar r2 = r1.ref2;\nvar r3 = r2.ref3;\nr3.member\n<\/code><\/pre>\n<p>Specifically, in <code>HttpContext.Current.User.Identity.Name<\/code>, the <code>HttpContext.Current<\/code> could be null, or the <code>User<\/code> property could be null, or the <code>Identity<\/code> property could be null.<\/p>\n<h3>Indirect<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Person \n{\n    public int Age { get; set; }\n}\npublic class Book \n{\n    public Person Author { get; set; }\n}\npublic class Example \n{\n    public void Foo() \n    {\n        Book b1 = new Book();\n        int authorAge = b1.Author.Age; \/\/ You never initialized the Author property.\n                                       \/\/ there is no Person to get an Age from.\n    }\n}\n<\/code><\/pre>\n<p>If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object&#8217;s constructor.<\/p>\n<h3>Nested Object Initializers<\/h3>\n<p>The same applies to nested object initializers:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>Book b1 = new Book \n{ \n   Author = { Age = 45 } \n};\n<\/code><\/pre>\n<p>This translates to:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>Book b1 = new Book();\nb1.Author.Age = 45;\n<\/code><\/pre>\n<p>While the <code>new<\/code> keyword is used, it only creates a new instance of <code>Book<\/code>, but not a new instance of <code>Person<\/code>, so the <code>Author<\/code> the property is still <code>null<\/code>.<\/p>\n<h3>Nested Collection Initializers<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Person \n{\n    public ICollection&lt;Book&gt; Books { get; set; }\n}\npublic class Book \n{\n    public string Title { get; set; }\n}\n<\/code><\/pre>\n<p>The nested collection <code>Initializers<\/code> behave the same:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>Person p1 = new Person \n{\n    Books = {\n         new Book { Title = \"Title1\" },\n         new Book { Title = \"Title2\" },\n    }\n};\n<\/code><\/pre>\n<p>This translates to:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>Person p1 = new Person();\np1.Books.Add(new Book { Title = \"Title1\" });\np1.Books.Add(new Book { Title = \"Title2\" });\n<\/code><\/pre>\n<p>The <code>new Person<\/code> only creates an instance of <code>Person<\/code>, but the <code>Books<\/code> collection is still <code>null<\/code>. The collection <code>Initializer<\/code> syntax does not create a collection<br \/>\nfor <code>p1.Books<\/code>, it only translates to the <code>p1.Books.Add(...)<\/code> statements.<\/p>\n<h3>Array<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>int[] numbers = null;\nint n = numbers[0]; \/\/ numbers is null. There is no array to index.\n<\/code><\/pre>\n<h3>Array Elements<\/h3>\n<pre><code>Person[] people = new Person[5];\npeople[0].Age = 20 \/\/ people[0] is null. The array was allocated but not\n                   \/\/ initialized. There is no Person to set the Age for.\n<\/code><\/pre>\n<h3>Jagged Arrays<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>long[][] array = new long[1][];\narray[0][0] = 3; \/\/ is null because only the first dimension is yet initialized.\n                 \/\/ Use array[0] = new long[2]; first.\n<\/code><\/pre>\n<h3>Collection\/List\/Dictionary<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>Dictionary&lt;string, int&gt; agesForNames = null;\nint age = agesForNames[\"Bob\"]; \/\/ agesForNames is null.\n                               \/\/ There is no Dictionary to perform the lookup.\n<\/code><\/pre>\n<h3>Range Variable (Indirect\/Deferred)<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Person \n{\n    public string Name { get; set; }\n}\nvar people = new List&lt;Person&gt;();\npeople.Add(null);\nvar names = from p in people select p.Name;\nstring firstName = names.First(); \/\/ Exception is thrown here, but actually occurs\n                                  \/\/ on the line above.  \"p\" is null because the\n                                  \/\/ first element we added to the list is null.\n<\/code><\/pre>\n<h3>Events (C#)<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Demo\n{\n    public event EventHandler StateChanged;\n    \n    protected virtual void OnStateChanged(EventArgs e)\n    {        \n        StateChanged(this, e); \/\/ Exception is thrown here \n                               \/\/ if no event handlers have been attached\n                               \/\/ to StateChanged event\n    }\n}\n<\/code><\/pre>\n<p>(Note: The VB.NET compiler inserts null checks for event usage, so it&#8217;s not necessary to check events for <code>Nothing<\/code> in VB.NET.)<\/p>\n<h3>Bad Naming Conventions:<\/h3>\n<p>If you named fields differently from locals, you might have realized that you never initialized the field.<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Form1\n{\n    private Customer customer;\n    \n    private void Form1_Load(object sender, EventArgs e) \n    {\n        Customer customer = new Customer();\n        customer.Name = \"John\";\n    }\n    \n    private void Button_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show(customer.Name);\n    }\n}\n<\/code><\/pre>\n<p>This can be solved by following the convention to prefix fields with an underscore:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>    private Customer _customer;\n<\/code><\/pre>\n<h3>ASP.NET Page Life cycle:<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public partial class Issues_Edit : System.Web.UI.Page\n{\n    protected TestIssue myIssue;\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!IsPostBack)\n        {\n             \/\/ Only called on first load, not when button clicked\n             myIssue = new TestIssue(); \n        }\n    }\n        \n    protected void SaveButton_Click(object sender, EventArgs e)\n    {\n        myIssue.Entry = \"NullReferenceException here!\";\n    }\n}\n<\/code><\/pre>\n<h3>ASP.NET Session Values<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>\/\/ if the \"FirstName\" session value has not yet been set,\n\/\/ then this line will throw a NullReferenceException\nstring firstName = Session[\"FirstName\"].ToString();\n<\/code><\/pre>\n<h3>ASP.NET MVC empty view models<\/h3>\n<p>If the exception occurs when referencing a property of <code>@Model<\/code> in an <code>ASP.NET MVC View<\/code>, you need to understand that the <code>Model<\/code> gets set in your action method, when you <code>return<\/code> a view. When you return an empty model (or model property) from your controller, the exception occurs when the views access it:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>\/\/ Controller\npublic class Restaurant:Controller\n{\n    public ActionResult Search()\n    {\n        return View();  \/\/ Forgot the provide a Model here.\n    }\n}\n\n\/\/ Razor view \n@foreach (var restaurantSearch in Model.RestaurantSearch)  \/\/ Throws.\n{\n}\n    \n&lt;p&gt;@Model.somePropertyName&lt;\/p&gt; &lt;!-- Also throws --&gt;\n<\/code><\/pre>\n<h3>WPF Control Creation Order and Events<\/h3>\n<p><code>WPF<\/code> controls are created during the call to <code>InitializeComponent<\/code> in the order they appear in the visual tree.  A <code>NullReferenceException<\/code> will be raised in the case of early-created controls with event handlers, etc., that fire during <code>InitializeComponent<\/code> which reference late-created controls.<\/p>\n<p>For example:<\/p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Grid&gt;\n    &lt;!-- Combobox declared first --&gt;\n    &lt;ComboBox Name=\"comboBox1\" \n              Margin=\"10\"\n              SelectedIndex=\"0\" \n              SelectionChanged=\"comboBox1_SelectionChanged\"&gt;\n       &lt;ComboBoxItem Content=\"Item 1\" \/&gt;\n       &lt;ComboBoxItem Content=\"Item 2\" \/&gt;\n       &lt;ComboBoxItem Content=\"Item 3\" \/&gt;\n    &lt;\/ComboBox&gt;\n        \n    &lt;!-- Label declared later --&gt;\n    &lt;Label Name=\"label1\" \n           Content=\"Label\"\n           Margin=\"10\" \/&gt;\n&lt;\/Grid&gt;\n<\/code><\/pre>\n<p>Here <code>comboBox1<\/code> is created before <code>label1<\/code>. If <code>comboBox1_SelectionChanged<\/code> attempts to reference `label1, it will not yet have been created.<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    label1.Content = comboBox1.SelectedIndex.ToString(); \/\/ NullReferenceException here!!\n}\n<\/code><\/pre>\n<p>Changing the order of the declarations in the <code>XAML<\/code> (i.e., listing <code>label1<\/code> before <code>comboBox1<\/code>, ignoring issues of design philosophy) would at least resolve the <code>NullReferenceException<\/code> here.<\/p>\n<h3>Cast with <code>as<\/code><\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>var myThing = someObject as Thing;\n<\/code><\/pre>\n<p>This doesn&#8217;t throw an <code>InvalidCastException<\/code> but returns a <code>null<\/code> when the cast fails (and when <code>someObject<\/code> is itself null). So be aware of that.<\/p>\n<h3>LINQ <code>FirstOrDefault()<\/code> and <code>SingleOrDefault()<\/code><\/h3>\n<p>The plain versions <code>First()<\/code> and <code>Single()<\/code> throw exceptions when there is nothing. The &#8220;OrDefault&#8221; versions return <code>null<\/code> in that case. So be aware of that.<\/p>\n<h3>foreach<\/h3>\n<p><code>foreach<\/code> throws when you try to iterate on a <code>null<\/code> collection. Usually caused by unexpected <code>null<\/code> result from methods that return collections.<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>List&lt;int&gt; list = null;    \nforeach(var v in list) { } \/\/ NullReferenceException here\n<\/code><\/pre>\n<p>More realistic example &#8211; select nodes from XML document. Will throw if nodes are not found but initial debugging shows that all properties valid:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var node in myData.MyXml.DocumentNode.SelectNodes(\"\/\/Data\"))\n<\/code><\/pre>\n<hr>\n<h1>Ways to Avoid<\/h1>\n<h3>Explicitly check for <code>null<\/code> and ignore <code>null<\/code> values.<\/h3>\n<p>If you expect the reference sometimes to be <code>null<\/code>, you can check for it being <code>null<\/code> before accessing instance members:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>void PrintName(Person p)\n{\n    if (p != null) \n    {\n        Console.WriteLine(p.Name);\n    }\n}\n<\/code><\/pre>\n<h3>Explicitly check for <code>null<\/code> and provide a default value.<\/h3>\n<p>Methods you call expecting an instance can return <code>null<\/code>, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>string GetCategory(Book b) \n{\n    if (b == null)\n        return \"Unknown\";\n    return b.Category;\n}\n<\/code><\/pre>\n<h3>Explicitly check for <code>null<\/code> from method calls and throw a custom exception.<\/h3>\n<p>You can also throw a custom exception, only to catch it in the calling code:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>string GetCategory(string bookTitle) \n{\n    var book = library.FindBook(bookTitle);  \/\/ This may return null\n    if (book == null)\n        throw new BookNotFoundException(bookTitle);  \/\/ Your custom exception\n    return book.Category;\n}\n<\/code><\/pre>\n<h3>Use <code>Debug.Assert<\/code> if a value should never be <code>null<\/code>, to catch the problem earlier than the exception occurs.<\/h3>\n<p>When you know during development that a method could, but never should return <code>null<\/code>, you can use <code>Debug.Assert()<\/code> to break as soon as possible when it does occur:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>string GetTitle(int knownBookID) \n{\n    \/\/ You know this should never return null.\n    var book = library.GetBook(knownBookID);  \n\n    \/\/ Exception will occur on the next line instead of at the end of this method.\n    Debug.Assert(book != null, \"Library didn't return a book for known book ID.\");\n\n    \/\/ Some other code\n\n    return book.Title; \/\/ Will never throw NullReferenceException in Debug mode.\n}\n<\/code><\/pre>\n<p>Though this check will not end up in your release build, causing it to throw the <code>NullReferenceException<\/code> again when <code>book == null<\/code> at runtime in release mode.<\/p>\n<h3>Use <code>GetValueOrDefault()<\/code> for <code>nullable<\/code> value types to provide a default value when they are <code>null<\/code>.<\/h3>\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime? appointment = null;\nConsole.WriteLine(appointment.GetValueOrDefault(DateTime.Now));\n\/\/ Will display the default value provided (DateTime.Now), because appointment is null.\n\nappointment = new DateTime(2022, 10, 20);\nConsole.WriteLine(appointment.GetValueOrDefault(DateTime.Now));\n\/\/ Will display the appointment date, not the default\n<\/code><\/pre>\n<h3>Use the null coalescing operator: <code>??<\/code> [C#] or <code>If()<\/code> [VB].<\/h3>\n<p>The shorthand to providing a default value when a <code>null<\/code> is encountered:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>IService CreateService(ILogger log, Int32? frobPowerLevel)\n{\n   var serviceImpl = new MyService(log ?? NullLog.Instance);\n \n   \/\/ Note that the above \"GetValueOrDefault()\" can also be rewritten to use\n   \/\/ the coalesce operator:\n   serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;\n}\n<\/code><\/pre>\n<h3>Use the null condition operator: <code>?.<\/code> or <code>?[x]<\/code> for arrays (available in C# 6 and VB.NET 14):<\/h3>\n<p>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:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>var title = person.Title.ToUpper();\n<\/code><\/pre>\n<p>If the person does not have a title, this will throw an exception because it is trying to call <code>ToUpper<\/code> on a property with a null value.<\/p>\n<p>In <code>C# 5<\/code> and below, this can be guarded with:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>var title = person.Title == null ? null : person.Title.ToUpper();\n<\/code><\/pre>\n<p>Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax for this:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>var title = person.Title?.ToUpper();\n<\/code><\/pre>\n<p>This will result in the title variable being <code>null<\/code>, and the call to <code>ToUpper<\/code> is not made if <code>person.Title<\/code> is <code>null<\/code>.<\/p>\n<p>Of course, you <em>still<\/em> have to check <code>title<\/code> for <code>null<\/code> or use the null condition operator together with the null coalescing operator (<code>??<\/code>) to supply a default value:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>\/\/ regular null check\nint titleLength = 0;\nif (title != null)\n    titleLength = title.Length; \/\/ If title is null, this would throw NullReferenceException\n    \n\/\/ combining the `?` and the `??` operator\nint titleLength = title?.Length ?? 0;\n<\/code><\/pre>\n<p>Likewise, for arrays you can use <code>?[i]<\/code> as follows:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>int[] myIntArray = null;\nvar i = 5;\nint? elem = myIntArray?[i];\nif (!elem.HasValue) Console.WriteLine(\"No value\");\n<\/code><\/pre>\n<p>This will do the following: If <code>myIntArray<\/code> is <code>null<\/code>, the expression returns <code>null<\/code> and you can safely check it. If it contains an array, it will do the same as:<br \/>\n<code>elem = myIntArray[i];<\/code> and returns the i<sup>th<\/sup> element.<\/p>\n<h3>Use null context (available in C# 8):<\/h3>\n<p>Introduced in <code>C# 8<\/code>, null contexts and nullable reference types perform static analysis on variables and provide a compiler warning if a value can be potentially <code>null<\/code> or have been set to <code>null<\/code>. The nullable reference types allow types to be explicitly allowed to be <code>null<\/code>.<\/p>\n<p>The nullable annotation context and nullable warning context can be set for a project using the <code>Nullable<\/code> element in your <code>csproj<\/code> file. This element configures how the compiler interprets the nullability of types and what warnings are generated. Valid settings are:<\/p>\n<ul>\n<li><code>enable<\/code>: The nullable annotation context is enabled. The nullable warning context is enabled. Variables of a reference type, string, for example, are non-nullable. All nullability warnings are enabled.<\/li>\n<li><code>disable<\/code>: The nullable annotation context is disabled. The nullable warning context is disabled. Variables of a reference type are oblivious, just like earlier versions of C#. All nullability warnings are disabled.<\/li>\n<li><code>safeonly<\/code>: The nullable annotation context is enabled. The nullable warning context is safeonly. Variables of a reference type are non-nullable. All safety nullability warnings are enabled.<\/li>\n<li><code>warnings<\/code>: The nullable annotation context is disabled. The nullable warning context is enabled. Variables of a reference type are oblivious. All nullability warnings are enabled.<\/li>\n<li><code>safeonlywarnings<\/code>: The nullable annotation context is disabled. The nullable warning context is safeonly.<br \/>\nVariables of a reference type are oblivious. All safety nullability warnings are enabled.<\/li>\n<\/ul>\n<p>A nullable reference type is noted using the same syntax as nullable value types: a <code>?<\/code> is appended to the type of the variable.<\/p>\n<h3>Special techniques for debugging and fixing null derefs in iterators<\/h3>\n<p><code>C#<\/code> supports &#8220;iterator blocks&#8221; (called &#8220;generators&#8221; in some other popular languages). <code>NullReferenceException<\/code> can be particularly tricky to debug in iterator blocks because of deferred execution:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>public IEnumerable&lt;Frob&gt; GetFrobs(FrobFactory f, int count)\n{\n    for (int i = 0; i &lt; count; ++i)\n    yield return f.MakeFrob();\n}\n...\nFrobFactory factory = whatever;\nIEnumerable&lt;Frobs&gt; frobs = GetFrobs();\n...\nforeach(Frob frob in frobs) { ... }\n<\/code><\/pre>\n<p>If <code>whatever<\/code> results in <code>null<\/code> then <code>MakeFrob<\/code> will throw. Now, you might think that the right thing to do is this:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>\/\/ DON'T DO THIS\npublic IEnumerable&lt;Frob&gt; GetFrobs(FrobFactory f, int count)\n{\n   if (f == null) \n      throw new ArgumentNullException(\"f\", \"factory must not be null\");\n   for (int i = 0; i &lt; count; ++i)\n      yield return f.MakeFrob();\n}\n<\/code><\/pre>\n<p>Why is this wrong?  Because the iterator block does not actually <em>run<\/em> until the <code>foreach<\/code>!  The call to <code>GetFrobs<\/code> simply returns an object which <em>when iterated<\/em> will run the iterator block.<\/p>\n<p>By writing a <code>null<\/code> check like this you prevent the <code>NullReferenceException<\/code>, but you move the <code>NullArgumentException<\/code> to the point of the <em>iteration<\/em>, not to the point of the <em>call<\/em>, and that is <em>very confusing to debug<\/em>.<\/p>\n<p>The correct fix is:<\/p>\n<pre class=\"lang-cs prettyprint-override\"><code>\/\/ DO THIS\npublic IEnumerable&lt;Frob&gt; GetFrobs(FrobFactory f, int count)\n{\n   \/\/ No yields in a public method that throws!\n   if (f == null) \n       throw new ArgumentNullException(\"f\", \"factory must not be null\");\n   return GetFrobsForReal(f, count);\n}\nprivate IEnumerable&lt;Frob&gt; GetFrobsForReal(FrobFactory f, int count)\n{\n   \/\/ Yields in a private method\n   Debug.Assert(f != null);\n   for (int i = 0; i &lt; count; ++i)\n        yield return f.MakeFrob();\n}\n<\/code><\/pre>\n<p>That is, make a private helper method that has the iterator block logic and a public surface method that does the <code>null<\/code> check and returns the iterator. Now when <code>GetFrobs<\/code> is called, the <code>null<\/code> check happens immediately, and then <code>GetFrobsForReal<\/code> executes when the sequence is iterated.<\/p>\n<p>If you examine the reference source for <code>LINQ<\/code> 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. <strong>Optimize your code for the convenience of the caller, not the convenience of the author<\/strong>.<\/p>\n<h3>A note on null dereferences in unsafe code<\/h3>\n<p><code>C#<\/code> has an &#8220;unsafe&#8221; mode which is, as the name implies, extremely dangerous because the normal safety mechanisms which provide memory safety and type safety are not enforced. <strong>You should not be writing unsafe code unless you have a thorough and deep understanding of how memory works<\/strong>.<\/p>\n<p>In unsafe mode, you should be aware of two important facts:<\/p>\n<ul>\n<li>dereferencing a null <strong>pointer<\/strong> produces the same exception as dereferencing a null <strong>reference<\/strong><\/li>\n<li>dereferencing an invalid non-null pointer <strong>can<\/strong> produce that exception in some circumstances<\/li>\n<\/ul>\n<p>To understand why that is, it helps to understand how .NET produces <code>NullReferenceException<\/code> in the first place. (These details apply to .NET running on Windows; other operating systems use similar mechanisms.)<\/p>\n<p>Memory is virtualized in <code>Windows<\/code>; each process gets a virtual memory space of many &#8220;pages&#8221; 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 <em>lowest<\/em> page is marked as &#8220;produce an error if ever used in any way&#8221;.<\/p>\n<p>Both a null pointer and a null reference in <code>C#<\/code> are internally represented as the number zero, and so any attempt to dereference it into its corresponding memory storage causes the operating system to produce an error. The .NET runtime then detects this error and turns it into the <code>NullReferenceException<\/code>.<\/p>\n<p>That&#8217;s why dereferencing both a null pointer and a null reference produces the same exception.<\/p>\n<p>What about the second point? Dereferencing <em>any<\/em> invalid pointer that falls in the lowest page of virtual memory causes the same operating system error, and thereby the same exception.<\/p>\n<p>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 <code>CLR<\/code> 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 <em>via<\/em> the null.<\/p>\n<p>If you are working with unsafe code and you get a <code>NullReferenceException<\/code>, 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.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">9<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved What is a NullReferenceException, and how do I fix it? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] What is the cause? Bottom Line You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method &#8220;A&#8221;, it could be that &#8230; <a title=\"(Solved) What is a NullReferenceException, and how do I fix it?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\" aria-label=\"More on (Solved) What is a NullReferenceException, and how do I fix it?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[352,324,354,355,353],"class_list":["post-3835","post","type-post","status-publish","format-standard","hentry","category-solved","tag-net","tag-c","tag-null","tag-nullreferenceexception","tag-vb-net"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] What is the cause? Bottom Line You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method &#8220;A&#8221;, it could be that ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-20T13:48:22+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"16 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"(Solved) What is a NullReferenceException, and how do I fix it?\",\"datePublished\":\"2022-08-20T13:48:22+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\"},\"wordCount\":2175,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\".net\",\"c++\",\"null\",\"nullreferenceexception\",\"vb.net\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\",\"name\":\"(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-08-20T13:48:22+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"(Solved) What is a NullReferenceException, and how do I fix it?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/","og_locale":"en_US","og_type":"article","og_title":"(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb","og_description":"[ad_1] What is the cause? Bottom Line You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method &#8220;A&#8221;, it could be that ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/","og_site_name":"JassWeb","article_published_time":"2022-08-20T13:48:22+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"16 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"(Solved) What is a NullReferenceException, and how do I fix it?","datePublished":"2022-08-20T13:48:22+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/"},"wordCount":2175,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":[".net","c++","null","nullreferenceexception","vb.net"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/","url":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/","name":"(Solved) What is a NullReferenceException, and how do I fix it? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-20T13:48:22+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullreferenceexception-and-how-do-i-fix-it\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"(Solved) What is a NullReferenceException, and how do I fix it?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3835","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=3835"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3835\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=3835"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=3835"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=3835"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}