From 1f36747a9a38ed1fa2c938f9e96a425f7332fc32 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 18 Feb 2025 15:44:29 -0800 Subject: [PATCH 1/4] add project file and modernize code --- .../NullReferenceException/Overview/Array1.cs | 18 +-- .../NullReferenceException/Overview/Array2.cs | 20 +-- .../NullReferenceException/Overview/Array3.cs | 18 +-- .../NullReferenceException/Overview/Array4.cs | 18 +-- .../NullReferenceException/Overview/Chain1.cs | 119 ++++++++++-------- .../NullReferenceException/Overview/Chain2.cs | 97 +++++++------- .../Overview/Program.cs | 4 + .../Overview/Project.csproj | 8 ++ .../Overview/example1.cs | 19 ++- .../Overview/example1a.cs | 12 +- .../Overview/example2.cs | 34 ++--- .../Overview/nullreturn2.cs | 64 +++++----- .../Overview/nullreturn2a.cs | 67 +++++----- xml/System/NullReferenceException.xml | 2 +- 14 files changed, 266 insertions(+), 234 deletions(-) create mode 100644 snippets/csharp/System/NullReferenceException/Overview/Program.cs create mode 100644 snippets/csharp/System/NullReferenceException/Overview/Project.csproj diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs index fdf4155a3ac..d6946b1f6c3 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs @@ -1,16 +1,16 @@ // using System; -public class Example +public class Array1Example { - public static void Main() - { - String[] values = { "one", null, "two" }; - for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) - Console.Write("{0}{1}", values[ctr].Trim(), - ctr == values.GetUpperBound(0) ? "" : ", "); - Console.WriteLine(); - } + public static void Main() + { + string[] values = { "one", null, "two" }; + for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) + Console.Write("{0}{1}", values[ctr].Trim(), + ctr == values.GetUpperBound(0) ? "" : ", "); + Console.WriteLine(); + } } // The example displays the following output: // Unhandled Exception: diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs index c83b8fabdb5..fb37481e6ac 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs @@ -1,17 +1,17 @@ // using System; -public class Example +public class Array2Example { - public static void Main() - { - String[] values = { "one", null, "two" }; - for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) - Console.Write("{0}{1}", - values[ctr] != null ? values[ctr].Trim() : "", - ctr == values.GetUpperBound(0) ? "" : ", "); - Console.WriteLine(); - } + public static void Main() + { + string[] values = { "one", null, "two" }; + for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) + Console.Write("{0}{1}", + values[ctr] != null ? values[ctr].Trim() : "", + ctr == values.GetUpperBound(0) ? "" : ", "); + Console.WriteLine(); + } } // The example displays the following output: // one, , two diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array3.cs b/snippets/csharp/System/NullReferenceException/Overview/Array3.cs index 5eb2409b230..e90b72567db 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array3.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array3.cs @@ -1,17 +1,17 @@ // using System; -public class Example +public class Array3Example { - public static void Main() - { - int[] values = null; - for (int ctr = 0; ctr <= 9; ctr++) - values[ctr] = ctr * 2; + public static void Main() + { + int[] values = null; + for (int ctr = 0; ctr <= 9; ctr++) + values[ctr] = ctr * 2; - foreach (var value in values) - Console.WriteLine(value); - } + foreach (int value in values) + Console.WriteLine(value); + } } // The example displays the following output: // Unhandled Exception: diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array4.cs b/snippets/csharp/System/NullReferenceException/Overview/Array4.cs index 1a73df7c04b..f7e0dea6040 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array4.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array4.cs @@ -1,17 +1,17 @@ // using System; -public class Example +public class Array4Example { - public static void Main() - { - int[] values = new int[10]; - for (int ctr = 0; ctr <= 9; ctr++) - values[ctr] = ctr * 2; + public static void Main() + { + int[] values = new int[10]; + for (int ctr = 0; ctr <= 9; ctr++) + values[ctr] = ctr * 2; - foreach (var value in values) - Console.WriteLine(value); - } + foreach (int value in values) + Console.WriteLine(value); + } } // The example displays the following output: // 0 diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs index e4b5a79e937..18cff5a6882 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs @@ -1,62 +1,71 @@ -// -using System; +using System; -public class Example +namespace Chain1 { - public static void Main() - { - var pages = new Pages(); - if (!String.IsNullOrEmpty(pages.CurrentPage.Title)) { - String title = pages.CurrentPage.Title; - Console.WriteLine("Current title: '{0}'", title); - } - } -} + // + public class Chain1Example + { + public static void Main() + { + var pages = new Pages(); + if (!string.IsNullOrEmpty(pages.CurrentPage.Title)) + { + string title = pages.CurrentPage.Title; + Console.WriteLine("Current title: '{0}'", title); + } + } + } -public class Pages -{ - Page[] page = new Page[10]; - int ctr = 0; + public class Pages + { + readonly Page[] _page = new Page[10]; + int _ctr = 0; - public Page CurrentPage - { - get { return page[ctr]; } - set { - // Move all the page objects down to accommodate the new one. - if (ctr > page.GetUpperBound(0)) { - for (int ndx = 1; ndx <= page.GetUpperBound(0); ndx++) - page[ndx - 1] = page[ndx]; - } - page[ctr] = value; - if (ctr < page.GetUpperBound(0)) - ctr++; - } - } + public Page CurrentPage + { + get { return _page[_ctr]; } + set + { + // Move all the page objects down to accommodate the new one. + if (_ctr > _page.GetUpperBound(0)) + { + for (int ndx = 1; ndx <= _page.GetUpperBound(0); ndx++) + _page[ndx - 1] = _page[ndx]; + } + _page[_ctr] = value; + if (_ctr < _page.GetUpperBound(0)) + _ctr++; + } + } - public Page PreviousPage - { - get { - if (ctr == 0) { - if (page[0] == null) - return null; - else - return page[0]; - } - else { - ctr--; - return page[ctr + 1]; - } - } - } -} + public Page PreviousPage + { + get + { + if (_ctr == 0) + { + if (_page[0] == null) + return null; + else + return _page[0]; + } + else + { + _ctr--; + return _page[_ctr + 1]; + } + } + } + } -public class Page -{ - public Uri URL; - public String Title; + public class Page + { + public Uri URL; + public string Title; + } + // The example displays the following output: + // Unhandled Exception: + // System.NullReferenceException: Object reference not set to an instance of an object. + // at Example.Main() + // } -// The example displays the following output: -// Unhandled Exception: -// System.NullReferenceException: Object reference not set to an instance of an object. -// at Example.Main() -// diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs index 8a261bfa129..43168c00a20 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs @@ -1,20 +1,22 @@ // using System; -public class Example +public class Chain2Example { - public static void Main() - { - var pages = new Pages(); - Page current = pages.CurrentPage; - if (current != null) { - String title = current.Title; - Console.WriteLine("Current title: '{0}'", title); - } - else { - Console.WriteLine("There is no page information in the cache."); - } - } + public static void Main() + { + var pages = new Pages(); + Page current = pages.CurrentPage; + if (current != null) + { + string title = current.Title; + Console.WriteLine("Current title: '{0}'", title); + } + else + { + Console.WriteLine("There is no page information in the cache."); + } + } } // The example displays the following output: // There is no page information in the cache. @@ -22,43 +24,48 @@ public static void Main() public class Pages { - Page[] page = new Page[10]; - int ctr = 0; + readonly Page[] _page = new Page[10]; + int _ctr = 0; - public Page CurrentPage - { - get { return page[ctr]; } - set { - // Move all the page objects down to accommodate the new one. - if (ctr > page.GetUpperBound(0)) { - for (int ndx = 1; ndx <= page.GetUpperBound(0); ndx++) - page[ndx - 1] = page[ndx]; - } - page[ctr] = value; - if (ctr < page.GetUpperBound(0)) - ctr++; - } - } + public Page CurrentPage + { + get { return _page[_ctr]; } + set + { + // Move all the page objects down to accommodate the new one. + if (_ctr > _page.GetUpperBound(0)) + { + for (int ndx = 1; ndx <= _page.GetUpperBound(0); ndx++) + _page[ndx - 1] = _page[ndx]; + } + _page[_ctr] = value; + if (_ctr < _page.GetUpperBound(0)) + _ctr++; + } + } - public Page PreviousPage - { - get { - if (ctr == 0) { - if (page[0] == null) - return null; + public Page PreviousPage + { + get + { + if (_ctr == 0) + { + if (_page[0] == null) + return null; + else + return _page[0]; + } else - return page[0]; - } - else { - ctr--; - return page[ctr + 1]; - } - } - } + { + _ctr--; + return _page[_ctr + 1]; + } + } + } } public class Page { - public Uri URL; - public String Title; + public Uri URL; + public string Title; } diff --git a/snippets/csharp/System/NullReferenceException/Overview/Program.cs b/snippets/csharp/System/NullReferenceException/Overview/Program.cs new file mode 100644 index 00000000000..aa9513016f6 --- /dev/null +++ b/snippets/csharp/System/NullReferenceException/Overview/Program.cs @@ -0,0 +1,4 @@ +// Do something +using System; + +Console.WriteLine("Hello World"); diff --git a/snippets/csharp/System/NullReferenceException/Overview/Project.csproj b/snippets/csharp/System/NullReferenceException/Overview/Project.csproj new file mode 100644 index 00000000000..92e46ddaccf --- /dev/null +++ b/snippets/csharp/System/NullReferenceException/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net9.0 + + + diff --git a/snippets/csharp/System/NullReferenceException/Overview/example1.cs b/snippets/csharp/System/NullReferenceException/Overview/example1.cs index ddc1d52a6d0..67006d95bd9 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example1.cs @@ -1,18 +1,17 @@ // -using System; using System.Collections.Generic; -public class Example +public class UseBeforeAssignExample { - public static void Main(string[] args) - { - int value = Int32.Parse(args[0]); - List names; - if (value > 0) - names = new List(); + public static void Main(string[] args) + { + int value = int.Parse(args[0]); + List names; + if (value > 0) + names = []; - names.Add("Major Major Major"); - } + //names.Add("Major Major Major"); + } } // Compilation displays a warning like the following: // Example1.cs(10) : warning BC42104: Variable //names// is used before it diff --git a/snippets/csharp/System/NullReferenceException/Overview/example1a.cs b/snippets/csharp/System/NullReferenceException/Overview/example1a.cs index 29f01321962..d83ee39e134 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example1a.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example1a.cs @@ -1,13 +1,11 @@ // -using System; using System.Collections.Generic; -public class Example +public class AnotherExample { - public static void Main() - { - List names = new List(); - names.Add("Major Major Major"); - } + public static void Main() + { + List names = ["Major Major Major"]; + } } // diff --git a/snippets/csharp/System/NullReferenceException/Overview/example2.cs b/snippets/csharp/System/NullReferenceException/Overview/example2.cs index 9d485a1113c..a946f297807 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example2.cs @@ -2,26 +2,26 @@ using System; using System.Collections.Generic; -public class Example +public class NRE2Example { - public static void Main() - { - List names = GetData(); - PopulateNames(names); - } + public static void Main() + { + List names = GetData(); + PopulateNames(names); + } - private static void PopulateNames(List names) - { - String[] arrNames = { "Dakota", "Samuel", "Nikita", - "Koani", "Saya", "Yiska", "Yumaevsky" }; - foreach (var arrName in arrNames) - names.Add(arrName); - } + private static void PopulateNames(List names) + { + string[] arrNames = [ "Dakota", "Samuel", "Nikita", + "Koani", "Saya", "Yiska", "Yumaevsky" ]; + foreach (string arrName in arrNames) + names.Add(arrName); + } - private static List GetData() - { - return null; - } + private static List GetData() + { + return null; + } } // The example displays output like the following: // Unhandled Exception: System.NullReferenceException: Object reference diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs index 67945a81828..fc8449c8f61 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs @@ -1,39 +1,43 @@ -// + using System; -public class Example +namespace NullReturn { - public static void Main() - { - Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra", + public class NullReturnExample + { + // + public static void Main() + { + Person[] persons = Person.AddRange([ "Abigail", "Abra", "Abraham", "Adrian", "Ariella", - "Arnold", "Aston", "Astor" } ); - String nameToFind = "Robert"; - Person found = Array.Find(persons, p => p.FirstName == nameToFind); - Console.WriteLine(found.FirstName); - } -} + "Arnold", "Aston", "Astor" ]); + string nameToFind = "Robert"; + Person found = Array.Find(persons, p => p.FirstName == nameToFind); + Console.WriteLine(found.FirstName); + } + } -public class Person -{ - public static Person[] AddRange(String[] firstNames) - { - Person[] p = new Person[firstNames.Length]; - for (int ctr = 0; ctr < firstNames.Length; ctr++) - p[ctr] = new Person(firstNames[ctr]); + public class Person + { + public static Person[] AddRange(string[] firstNames) + { + Person[] p = new Person[firstNames.Length]; + for (int ctr = 0; ctr < firstNames.Length; ctr++) + p[ctr] = new Person(firstNames[ctr]); - return p; - } + return p; + } - public Person(String firstName) - { - this.FirstName = firstName; - } + public Person(string firstName) + { + FirstName = firstName; + } - public String FirstName; + public string FirstName; + } + // The example displays the following output: + // Unhandled Exception: System.NullReferenceException: + // Object reference not set to an instance of an object. + // at Example.Main() + // } -// The example displays the following output: -// Unhandled Exception: System.NullReferenceException: -// Object reference not set to an instance of an object. -// at Example.Main() -// \ No newline at end of file diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs index f3bc4380217..740804e542b 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs @@ -1,40 +1,43 @@ -// -using System; +using System; -public class Example +namespace NullReturn2 { - public static void Main() - { - Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra", + // + public class NullReturn2Example + { + public static void Main() + { + Person[] persons = Person.AddRange([ "Abigail", "Abra", "Abraham", "Adrian", "Ariella", - "Arnold", "Aston", "Astor" } ); - String nameToFind = "Robert"; - Person found = Array.Find(persons, p => p.FirstName == nameToFind); - if (found != null) - Console.WriteLine(found.FirstName); - else - Console.WriteLine("{0} not found.", nameToFind); - } -} + "Arnold", "Aston", "Astor" ]); + string nameToFind = "Robert"; + Person found = Array.Find(persons, p => p.FirstName == nameToFind); + if (found != null) + Console.WriteLine(found.FirstName); + else + Console.WriteLine("{0} not found.", nameToFind); + } + } -public class Person -{ - public static Person[] AddRange(String[] firstNames) - { - Person[] p = new Person[firstNames.Length]; - for (int ctr = 0; ctr < firstNames.Length; ctr++) - p[ctr] = new Person(firstNames[ctr]); + public class Person + { + public static Person[] AddRange(string[] firstNames) + { + Person[] p = new Person[firstNames.Length]; + for (int ctr = 0; ctr < firstNames.Length; ctr++) + p[ctr] = new Person(firstNames[ctr]); - return p; - } + return p; + } - public Person(String firstName) - { - this.FirstName = firstName; - } + public Person(string firstName) + { + FirstName = firstName; + } - public String FirstName; + public string FirstName; + } + // The example displays the following output: + // Robert not found + // } -// The example displays the following output: -// Robert not found -// \ No newline at end of file diff --git a/xml/System/NullReferenceException.xml b/xml/System/NullReferenceException.xml index 2305d4c30bc..24fe317274d 100644 --- a/xml/System/NullReferenceException.xml +++ b/xml/System/NullReferenceException.xml @@ -74,7 +74,7 @@ ## Remarks A exception is thrown when you try to access a member on a type whose value is `null`. A exception typically reflects developer error and is thrown in the following scenarios: -- You've forgotten to instantiate a reference type. In the following example, `names` is declared but never instantiated: +- You've forgotten to instantiate a reference type. In the following example, `names` is declared but never instantiated (the affected line is commented out in the C# example since it doesn't compile): :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/example1.cs" id="Snippet1"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/example1.fs" id="Snippet1"::: From cb62b49da055abce2eac9121527e893c61a2078c Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Wed, 19 Feb 2025 10:23:24 -0800 Subject: [PATCH 2/4] Apply suggestions from code review Co-authored-by: Bill Wagner --- .../csharp/System/NullReferenceException/Overview/Array1.cs | 2 +- .../csharp/System/NullReferenceException/Overview/Array2.cs | 2 +- .../csharp/System/NullReferenceException/Overview/Chain1.cs | 4 ++-- .../csharp/System/NullReferenceException/Overview/Chain2.cs | 2 +- .../System/NullReferenceException/Overview/nullreturn2.cs | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs index d6946b1f6c3..008c4c3568d 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs @@ -5,7 +5,7 @@ public class Array1Example { public static void Main() { - string[] values = { "one", null, "two" }; + string[] values = [ "one", null, "two" ]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) Console.Write("{0}{1}", values[ctr].Trim(), ctr == values.GetUpperBound(0) ? "" : ", "); diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs index fb37481e6ac..bfd8a03102f 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs @@ -5,7 +5,7 @@ public class Array2Example { public static void Main() { - string[] values = { "one", null, "two" }; + string[] values = [ "one", null, "two" ]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) Console.Write("{0}{1}", values[ctr] != null ? values[ctr].Trim() : "", diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs index 18cff5a6882..6683a70a73f 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs @@ -11,7 +11,7 @@ public static void Main() if (!string.IsNullOrEmpty(pages.CurrentPage.Title)) { string title = pages.CurrentPage.Title; - Console.WriteLine("Current title: '{0}'", title); + Console.WriteLine($"Current title: '{title}'"); } } } @@ -44,7 +44,7 @@ public Page PreviousPage { if (_ctr == 0) { - if (_page[0] == null) + if (_page[0] is null) return null; else return _page[0]; diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs index 43168c00a20..12e007a3c2e 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs @@ -10,7 +10,7 @@ public static void Main() if (current != null) { string title = current.Title; - Console.WriteLine("Current title: '{0}'", title); + Console.WriteLine($"Current title: '{title}'"); } else { diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs index fc8449c8f61..e6395844837 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs @@ -19,7 +19,7 @@ public static void Main() public class Person { - public static Person[] AddRange(string[] firstNames) + public static Person[] AddRange(params string[] firstNames) { Person[] p = new Person[firstNames.Length]; for (int ctr = 0; ctr < firstNames.Length; ctr++) From 3a1ca10d4aa71926106a9a9b43c84e159d9aeb5b Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Wed, 19 Feb 2025 11:46:06 -0800 Subject: [PATCH 3/4] respond to feedback; add note about nullable context --- .../NullReferenceException/Overview/Array1.cs | 14 ++-- .../NullReferenceException/Overview/Array2.cs | 11 +-- .../NullReferenceException/Overview/Array3.cs | 15 ++-- .../NullReferenceException/Overview/Array4.cs | 29 ++++---- .../NullReferenceException/Overview/Chain1.cs | 3 +- .../NullReferenceException/Overview/Chain2.cs | 11 +-- .../Overview/Program.cs | 6 +- .../Overview/Project.csproj | 1 + .../Overview/example1.cs | 5 +- .../Overview/example2.cs | 6 +- .../Overview/nullreturn2.cs | 71 +++++++++++-------- .../Overview/nullreturn2a.cs | 43 ----------- xml/System/NullReferenceException.xml | 44 ++++++------ 13 files changed, 120 insertions(+), 139 deletions(-) delete mode 100644 snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs index 008c4c3568d..599029a2be9 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs @@ -1,19 +1,19 @@ -// -using System; +using System; public class Array1Example { public static void Main() { + // string[] values = [ "one", null, "two" ]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) Console.Write("{0}{1}", values[ctr].Trim(), ctr == values.GetUpperBound(0) ? "" : ", "); Console.WriteLine(); + + // The example displays the following output: + // Unhandled Exception: + // System.NullReferenceException: Object reference not set to an instance of an object. + // } } -// The example displays the following output: -// Unhandled Exception: -// System.NullReferenceException: Object reference not set to an instance of an object. -// at Example.Main() -// diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs index bfd8a03102f..756e52f450b 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs @@ -1,18 +1,19 @@ -// -using System; +using System; public class Array2Example { public static void Main() { + // string[] values = [ "one", null, "two" ]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) Console.Write("{0}{1}", values[ctr] != null ? values[ctr].Trim() : "", ctr == values.GetUpperBound(0) ? "" : ", "); Console.WriteLine(); + + // The example displays the following output: + // one, , two + // } } -// The example displays the following output: -// one, , two -// diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array3.cs b/snippets/csharp/System/NullReferenceException/Overview/Array3.cs index e90b72567db..45bc07360b2 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array3.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array3.cs @@ -1,20 +1,21 @@ -// -using System; +using System; public class Array3Example { public static void Main() { + // int[] values = null; for (int ctr = 0; ctr <= 9; ctr++) values[ctr] = ctr * 2; foreach (int value in values) Console.WriteLine(value); + + // The example displays the following output: + // Unhandled Exception: + // System.NullReferenceException: Object reference not set to an instance of an object. + // at Array3Example.Main() + // } } -// The example displays the following output: -// Unhandled Exception: -// System.NullReferenceException: Object reference not set to an instance of an object. -// at Example.Main() -// diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array4.cs b/snippets/csharp/System/NullReferenceException/Overview/Array4.cs index f7e0dea6040..cc4c40e91cb 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array4.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array4.cs @@ -1,27 +1,28 @@ -// -using System; +using System; public class Array4Example { public static void Main() { + // int[] values = new int[10]; for (int ctr = 0; ctr <= 9; ctr++) values[ctr] = ctr * 2; foreach (int value in values) Console.WriteLine(value); + + // The example displays the following output: + // 0 + // 2 + // 4 + // 6 + // 8 + // 10 + // 12 + // 14 + // 16 + // 18 + // } } -// The example displays the following output: -// 0 -// 2 -// 4 -// 6 -// 8 -// 10 -// 12 -// 14 -// 16 -// 18 -// diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs index 6683a70a73f..31f69e53c3e 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs @@ -63,9 +63,10 @@ public class Page public Uri URL; public string Title; } + // The example displays the following output: // Unhandled Exception: // System.NullReferenceException: Object reference not set to an instance of an object. - // at Example.Main() + // at Chain1Example.Main() // } diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs index 12e007a3c2e..2034ef1efb6 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs @@ -1,10 +1,10 @@ -// -using System; +using System; public class Chain2Example { public static void Main() { + // var pages = new Pages(); Page current = pages.CurrentPage; if (current != null) @@ -16,11 +16,12 @@ public static void Main() { Console.WriteLine("There is no page information in the cache."); } + + // The example displays the following output: + // There is no page information in the cache. + // } } -// The example displays the following output: -// There is no page information in the cache. -// public class Pages { diff --git a/snippets/csharp/System/NullReferenceException/Overview/Program.cs b/snippets/csharp/System/NullReferenceException/Overview/Program.cs index aa9513016f6..7710f02b42b 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Program.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Program.cs @@ -1,4 +1,2 @@ -// Do something -using System; - -Console.WriteLine("Hello World"); +//NullReturnExample.NoCheckExample(); +NullReturnExample.ExampleWithNullCheck(); diff --git a/snippets/csharp/System/NullReferenceException/Overview/Project.csproj b/snippets/csharp/System/NullReferenceException/Overview/Project.csproj index 92e46ddaccf..80f35861282 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Project.csproj +++ b/snippets/csharp/System/NullReferenceException/Overview/Project.csproj @@ -2,6 +2,7 @@ Exe + disable net9.0 diff --git a/snippets/csharp/System/NullReferenceException/Overview/example1.cs b/snippets/csharp/System/NullReferenceException/Overview/example1.cs index 67006d95bd9..2d6cd6cf38a 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example1.cs @@ -13,8 +13,9 @@ public static void Main(string[] args) //names.Add("Major Major Major"); } } + // Compilation displays a warning like the following: -// Example1.cs(10) : warning BC42104: Variable //names// is used before it +// warning BC42104: Variable //names// is used before it // has been assigned a value. A null reference exception could result // at runtime. // @@ -23,5 +24,5 @@ public static void Main(string[] args) // The example displays output like the following output: // Unhandled Exception: System.NullReferenceException: Object reference // not set to an instance of an object. -// at Example.Main() +// at UseBeforeAssignExample.Main() // diff --git a/snippets/csharp/System/NullReferenceException/Overview/example2.cs b/snippets/csharp/System/NullReferenceException/Overview/example2.cs index a946f297807..41dfb78ede0 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example2.cs @@ -1,5 +1,4 @@ // -using System; using System.Collections.Generic; public class NRE2Example @@ -23,9 +22,10 @@ private static List GetData() return null; } } + // The example displays output like the following: // Unhandled Exception: System.NullReferenceException: Object reference // not set to an instance of an object. -// at Example.PopulateNames(List`1 names) -// at Example.Main() +// at NRE2Example.PopulateNames(List`1 names) +// at NRE2Example.Main() // diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs index e6395844837..2c6dd285739 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs @@ -1,43 +1,58 @@  using System; -namespace NullReturn +public class NullReturnExample { - public class NullReturnExample + // + public static void NoCheckExample() { - // - public static void Main() - { - Person[] persons = Person.AddRange([ "Abigail", "Abra", + Person[] persons = Person.AddRange([ "Abigail", "Abra", "Abraham", "Adrian", "Ariella", "Arnold", "Aston", "Astor" ]); - string nameToFind = "Robert"; - Person found = Array.Find(persons, p => p.FirstName == nameToFind); - Console.WriteLine(found.FirstName); - } + string nameToFind = "Robert"; + Person found = Array.Find(persons, p => p.FirstName == nameToFind); + Console.WriteLine(found.FirstName); } - public class Person + // The example displays the following output: + // Unhandled Exception: System.NullReferenceException: + // Object reference not set to an instance of an object. + // + + // + public static void ExampleWithNullCheck() { - public static Person[] AddRange(params string[] firstNames) - { - Person[] p = new Person[firstNames.Length]; - for (int ctr = 0; ctr < firstNames.Length; ctr++) - p[ctr] = new Person(firstNames[ctr]); + Person[] persons = Person.AddRange([ "Abigail", "Abra", + "Abraham", "Adrian", "Ariella", + "Arnold", "Aston", "Astor" ]); + string nameToFind = "Robert"; + Person found = Array.Find(persons, p => p.FirstName == nameToFind); + if (found != null) + Console.WriteLine(found.FirstName); + else + Console.WriteLine($"'{nameToFind}' not found."); + } + + // The example displays the following output: + // 'Robert' not found + // +} - return p; - } +public class Person +{ + public static Person[] AddRange(params string[] firstNames) + { + Person[] p = new Person[firstNames.Length]; + for (int ctr = 0; ctr < firstNames.Length; ctr++) + p[ctr] = new Person(firstNames[ctr]); - public Person(string firstName) - { - FirstName = firstName; - } + return p; + } - public string FirstName; + public Person(string firstName) + { + FirstName = firstName; } - // The example displays the following output: - // Unhandled Exception: System.NullReferenceException: - // Object reference not set to an instance of an object. - // at Example.Main() - // + + public string FirstName; } diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs deleted file mode 100644 index 740804e542b..00000000000 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; - -namespace NullReturn2 -{ - // - public class NullReturn2Example - { - public static void Main() - { - Person[] persons = Person.AddRange([ "Abigail", "Abra", - "Abraham", "Adrian", "Ariella", - "Arnold", "Aston", "Astor" ]); - string nameToFind = "Robert"; - Person found = Array.Find(persons, p => p.FirstName == nameToFind); - if (found != null) - Console.WriteLine(found.FirstName); - else - Console.WriteLine("{0} not found.", nameToFind); - } - } - - public class Person - { - public static Person[] AddRange(string[] firstNames) - { - Person[] p = new Person[firstNames.Length]; - for (int ctr = 0; ctr < firstNames.Length; ctr++) - p[ctr] = new Person(firstNames[ctr]); - - return p; - } - - public Person(string firstName) - { - FirstName = firstName; - } - - public string FirstName; - } - // The example displays the following output: - // Robert not found - // -} diff --git a/xml/System/NullReferenceException.xml b/xml/System/NullReferenceException.xml index 24fe317274d..bbe543dff23 100644 --- a/xml/System/NullReferenceException.xml +++ b/xml/System/NullReferenceException.xml @@ -72,9 +72,13 @@ exception is thrown when you try to access a member on a type whose value is `null`. A exception typically reflects developer error and is thrown in the following scenarios: -- You've forgotten to instantiate a reference type. In the following example, `names` is declared but never instantiated (the affected line is commented out in the C# example since it doesn't compile): +A exception is thrown when you try to access a member on a type whose value is `null`. A exception typically reflects developer error and is thrown in the following scenarios: + +> [!NOTE] +> You can avoid most `NullReferenceException` exceptions in C# by using the [null-conditional operator](/dotnet/csharp/language-reference/operators/null-conditional-operator) (`?.`) or the [null-coalescing operator](/dotnet/csharp/language-reference/operators/null-coalescing-operator) (`??`). For more information, see [Nullable reference types](/dotnet/csharp/whats-new/csharp-8#nullable-reference-types). The following C# examples assume the nullable context is disabled (not recommended). + +- You forgot to instantiate a reference type. In the following example, `names` is declared but never instantiated (the affected line is commented out in the C# example since it doesn't compile): :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/example1.cs" id="Snippet1"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/example1.fs" id="Snippet1"::: @@ -86,7 +90,7 @@ :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/example1a.fs" id="Snippet2"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/example1a.vb" id="Snippet2"::: -- You've forgotten to dimension an array before initializing it. In the following example, `values` is declared to be an integer array, but the number of elements that it contains is never specified. The attempt to initialize its values therefore thrown a exception. +- You forgot to dimension an array before initializing it. In the following example, `values` is declared to be an integer array, but the number of elements that it contains is never specified. The attempt to initialize its values therefore throws a exception. :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/Array3.cs" id="Snippet10"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/Array3.fs" id="Snippet10"::: @@ -100,7 +104,7 @@ For more information on declaring and initializing arrays, see [Arrays](/dotnet/csharp/programming-guide/arrays/) and [Arrays](/dotnet/visual-basic/programming-guide/language-features/arrays/). -- You get a **null** return value from a method, and then call a method on the returned type. This sometimes is the result of a documentation error; the documentation fails to note that a method call can return `null`. In other cases, your code erroneously assumes that the method will always return a non-**null** value. +- You get a **null** return value from a method, and then call a method on the returned type. This sometimes is the result of a documentation error; the documentation fails to note that a method call can return `null`. In other cases, your code erroneously assumes that the method will always return a non-null value. The code in the following example assumes that the method always returns `Person` object whose `FirstName` field matches a search string. Because there is no match, the runtime throws a exception. @@ -108,27 +112,27 @@ :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/nullreturn2.fs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/nullreturn2.vb" id="Snippet4"::: - To address this problem, test the method's return value to ensure that it is not `null` before calling any of its members, as the following example does. + To address this problem, test the method's return value to ensure that it's not `null` before calling any of its members, as the following example does. :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs" id="Snippet5"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/nullreturn2a.fs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/nullreturn2a.vb" id="Snippet5"::: -- You're using an expression (for example, you're chaining a list of methods or properties together) to retrieve a value and, although you're checking whether the value is `null`, the runtime still throws a exception. This occurs because one of the intermediate values in the expression returns `null`. As a result, your test for `null` is never evaluated. +- You're using an expression (for example, you chained a list of methods or properties together) to retrieve a value and, although you're checking whether the value is `null`, the runtime still throws a exception. This occurs because one of the intermediate values in the expression returns `null`. As a result, your test for `null` is never evaluated. - The following example defines a `Pages` object that caches information about web pages, which are presented by `Page` objects. The `Example.Main` method checks whether the current web page has a non-null title and, if it does, displays the title. Despite this check, however, the method throws a exception. + The following example defines a `Pages` object that caches information about web pages, which are presented by `Page` objects. The `Example.Main` method checks whether the current web page has a non-null title and, if it does, displays the title. Despite this check, however, the method throws a exception. :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs" id="Snippet6"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/Chain1.fs" id="Snippet6"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/Chain1.vb" id="Snippet6"::: - The exception is thrown because `pages.CurrentPage` returns `null` if no page information is stored in the cache. This exception can be corrected by testing the value of the `CurrentPage` property before retrieving the current `Page` object's `Title` property, as the following example does: + The exception is thrown because `pages.CurrentPage` returns `null` if no page information is stored in the cache. This exception can be corrected by testing the value of the `CurrentPage` property before retrieving the current `Page` object's `Title` property, as the following example does: :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs" id="Snippet7"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/Chain2.fs" id="Snippet7"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/Chain2.vb" id="Snippet7"::: -- You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a exception. +- You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a exception. The following example defines a string array. A `for` statement enumerates the elements in the array and calls each string's method before displaying the string. @@ -142,7 +146,7 @@ :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/Array2.fs" id="Snippet9"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/Array2.vb" id="Snippet9"::: -- A exception can be thrown by a method when it accesses a member of one of its arguments, but that argument is `null`. The `PopulateNames` method in the following example throws the exception at the line `names.Add(arrName);`. +- A method when it accesses a member of one of its arguments, but that argument is `null`. The `PopulateNames` method in the following example throws the exception at the line `names.Add(arrName);`. :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/example2.cs" id="Snippet3"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/example2.fs" id="Snippet3"::: @@ -150,25 +154,25 @@ 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/). - The following Microsoft intermediate language (MSIL) instructions throw : `callvirt`, `cpblk`, `cpobj`, `initblk`, `ldelem.`, `ldelema`, `ldfld`, `ldflda`, `ldind.`, `ldlen`, `stelem.`, `stfld`, `stind.`, `throw`, and `unbox`. +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. + uses the HRESULT `COR_E_NULLREFERENCE`, which has the value 0x80004003. - For a list of initial property values for an instance of , see the constructors. +For a list of initial property values for an instance of , see the constructors. - **Handling NullReferenceException in release code** +### When to handle NullReferenceException exceptions - It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error. In these cases, letting the exception stop the app might be the best alternative. +It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error. In these cases, letting the exception stop the app might be the best alternative. - However, there are many situations where handling the error can be useful: +However, there are many situations where handling the error can be useful: -- Your app can ignore objects that are null. For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Recording the bad data in a log file or in the application UI might be all you have to do. +- Your app can ignore objects that are null. For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Recording the bad data in a log file or in the application UI might be all you have to do. -- You can recover from the exception. For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again. +- You can recover from the exception. For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again. -- You can restore the state of your app to a valid state. For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app. +- You can restore the state of your app to a valid state. For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app. -- You want to report the exception. For example, if the error was caused by a mistake from the user of your app, you can generate a message to help them supply the correct information. You can also log information about the error to help you fix the problem. Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs. +- You want to report the exception. For example, if the error was caused by a mistake from the user of your app, you can generate a message to help them supply the correct information. You can also log information about the error to help you fix the problem. Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs. ]]> From 27eec15391922847a4b61dcc08b9c4f5b7dcc7a8 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Wed, 19 Feb 2025 12:09:41 -0800 Subject: [PATCH 4/4] fix snippet file path --- xml/System/NullReferenceException.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xml/System/NullReferenceException.xml b/xml/System/NullReferenceException.xml index bbe543dff23..5b6186724c3 100644 --- a/xml/System/NullReferenceException.xml +++ b/xml/System/NullReferenceException.xml @@ -114,7 +114,7 @@ A exception is thrown when you try to acces To address this problem, test the method's return value to ensure that it's not `null` before calling any of its members, as the following example does. - :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/nullreturn2a.cs" id="Snippet5"::: + :::code language="csharp" source="~/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs" id="Snippet5"::: :::code language="fsharp" source="~/snippets/fsharp/System/NullReferenceException/Overview/nullreturn2a.fs" id="Snippet5"::: :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.nullreferenceexception.class/vb/nullreturn2a.vb" id="Snippet5":::