From 160e32e3e975ee97f0c127e19a60c927187001c2 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Sun, 31 Dec 2023 20:27:44 -0800 Subject: [PATCH 01/10] ported remarks for exception types --- .../Exception/Overview/csharp/example.cs | 44 +++ .../Overview/csharp/notprimeexception.cs | 40 +++ .../Overview/csharp/primenumbergenerator.cs | 65 +++++ .../Exception/Overview/csharp/rethrow1.cs | 78 ++++++ .../Exception/Overview/csharp/rethrow3.cs | 91 +++++++ .../Exception/Overview/csharp/usageerrors1.cs | 40 +++ .../Overview/fsharp/catchexception.fs | 19 ++ .../Exception/Overview/fsharp/example.fs | 33 +++ .../Overview/fsharp/notprimeexception.fs | 31 +++ .../Overview/fsharp/primenumbergenerator.fs | 51 ++++ .../Exception/Overview/fsharp/rethrow1.fs | 58 ++++ .../Exception/Overview/fsharp/rethrow3.fs | 46 ++++ .../Exception/Overview/fsharp/usageerrors1.fs | 25 ++ .../Exception/Overview/fsharp/usageerrors2.fs | 28 ++ .../Exception/Overview/vb/catchexception.vb | 21 ++ .../System/Exception/Overview/vb/example.vb | 48 ++++ .../Overview/vb/notprimeexception.vb | 38 +++ .../Overview/vb/primenumbergenerator.vb | 62 +++++ .../System/Exception/Overview/vb/rethrow1.vb | 75 +++++ .../System/Exception/Overview/vb/rethrow3.vb | 88 ++++++ .../Exception/Overview/vb/usageerrors1.vb | 35 +++ .../Exception/Overview/vb/usageerrors2.vb | 39 +++ .../Overview/csharp/Interface1.cs | 20 ++ .../Overview/csharp/ToString1.cs | 13 + .../Overview/fsharp/Interface1.fs | 17 ++ .../Overview/fsharp/ToString1.fs | 7 + .../Overview/fsharp/ToString2.fs | 9 + .../Overview/fsharp/basetoderived1.fs | 35 +++ .../Overview/fsharp/iconvertible1.fs | 23 ++ .../Overview/vb/Interface1.vb | 20 ++ .../Overview/vb/basetoderived1.vb | 67 +++++ .../Overview/vb/iconvertible1.vb | 27 ++ .../Overview/csharp/Enumerable1.cs | 19 ++ .../Overview/csharp/Enumerable3.cs | 22 ++ .../Overview/csharp/Enumerable5.cs | 22 ++ .../Overview/csharp/Enumerable6.cs | 26 ++ .../Overview/csharp/Iterating1.cs | 28 ++ .../Overview/csharp/List_Sort1.cs | 42 +++ .../Overview/csharp/Nullable1.cs | 25 ++ .../Overview/fsharp/Enumerable1.fs | 15 + .../Overview/fsharp/Enumerable2.fs | 19 ++ .../Overview/fsharp/Enumerable3.fs | 18 ++ .../Overview/fsharp/Enumerable4.fs | 18 ++ .../Overview/fsharp/Enumerable5.fs | 19 ++ .../Overview/fsharp/Enumerable6.fs | 22 ++ .../Overview/fsharp/Iterating1.fs | 23 ++ .../Overview/fsharp/Iterating2.fs | 37 +++ .../Overview/fsharp/Iterating3.fs | 25 ++ .../Overview/fsharp/List_Sort1.fs | 27 ++ .../Overview/fsharp/List_Sort2.fs | 24 ++ .../Overview/fsharp/List_Sort3.fs | 26 ++ .../Overview/fsharp/List_Sort4.fs | 25 ++ .../Overview/fsharp/Nullable1.fs | 21 ++ .../Overview/fsharp/Nullable2.fs | 23 ++ .../Overview/vb/Enumerable1.vb | 19 ++ .../Overview/vb/Enumerable2.vb | 23 ++ .../Overview/vb/Enumerable3.vb | 22 ++ .../Overview/vb/Enumerable4.vb | 23 ++ .../Overview/vb/Enumerable5.vb | 23 ++ .../Overview/vb/Enumerable6.vb | 27 ++ .../Overview/vb/Form1.vb | 31 +++ .../Overview/vb/Form11.vb | 42 +++ .../Overview/vb/Iterating1.vb | 30 ++ .../Overview/vb/Iterating2.vb | 44 +++ .../Overview/vb/Iterating3.vb | 31 +++ .../Overview/vb/List_Sort1.vb | 43 +++ .../Overview/vb/List_Sort2.vb | 38 +++ .../Overview/vb/List_Sort3.vb | 41 +++ .../Overview/vb/List_Sort4.vb | 37 +++ .../Overview/vb/MainPage.xaml.vb | 43 +++ .../Overview/vb/MainWindow.xaml.vb | 29 ++ .../Overview/vb/MainWindowDispatcher.xaml.vb | 36 +++ .../Overview/vb/Nullable1.vb | 26 ++ .../Overview/vb/Nullable2.vb | 32 +++ .../Overview/csharp/BadState1.cs | 38 +++ .../Overview/csharp/TestProp1.cs | 58 ++++ .../Overview/csharp/TestProp2.cs | 52 ++++ .../Overview/fsharp/BadState1.fs | 34 +++ .../Overview/fsharp/TestProp1.fs | 55 ++++ .../Overview/fsharp/TestProp2.fs | 48 ++++ .../Overview/vb/BadState1.vb | 37 +++ .../Overview/vb/TestProp1.vb | 70 +++++ .../Overview/vb/TestProp2.vb | 60 ++++ .../Overview/csharp/Missing1.cs | 48 ++++ .../Overview/csharp/Missing1a.cs | 24 ++ .../Overview/csharp/Regex1.cs | 30 ++ .../Overview/csharp/ctorException1.cs | 33 +++ .../Overview/fsharp/Missing1.fs | 27 ++ .../Overview/fsharp/Missing1a.fs | 15 + .../Overview/fsharp/Regex1.fs | 23 ++ .../Overview/vb/CtorException1.vb | 31 +++ .../Overview/vb/GettingVersions1.vb | 64 +++++ .../Overview/vb/Missing1.vb | 43 +++ .../Overview/vb/Missing1a.vb | 23 ++ .../Overview/vb/Regex1.vb | 30 ++ .../system-accessviolationexception.md | 29 ++ .../runtime-libraries/system-exception.md | 224 +++++++++++++++ .../system-invalidcastexception.md | 102 +++++++ .../system-invalidoperationexception.md | 257 ++++++++++++++++++ .../system-notimplementedexception.md | 26 ++ .../system-notsupportedexception.md | 91 +++++++ .../system-typeinitializationexception.md | 111 ++++++++ docs/fundamentals/toc.yml | 24 ++ 103 files changed, 4166 insertions(+) create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/notprimeexception.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/primenumbergenerator.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/catchexception.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/example.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/notprimeexception.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow3.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/catchexception.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/example.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/notprimeexception.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/primenumbergenerator.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow3.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/Interface1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/ToString1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/Interface1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable3.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable5.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable6.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable3.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable4.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable5.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable6.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form11.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating3.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort3.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort4.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainPage.xaml.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindow.xaml.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindowDispatcher.xaml.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/BadState1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/BadState1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp2.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1a.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/ctorException1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1a.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Regex1.fs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/CtorException1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/GettingVersions1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1a.vb create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Regex1.vb create mode 100644 docs/fundamentals/runtime-libraries/system-accessviolationexception.md create mode 100644 docs/fundamentals/runtime-libraries/system-exception.md create mode 100644 docs/fundamentals/runtime-libraries/system-invalidcastexception.md create mode 100644 docs/fundamentals/runtime-libraries/system-invalidoperationexception.md create mode 100644 docs/fundamentals/runtime-libraries/system-notimplementedexception.md create mode 100644 docs/fundamentals/runtime-libraries/system-notsupportedexception.md create mode 100644 docs/fundamentals/runtime-libraries/system-typeinitializationexception.md diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs new file mode 100644 index 0000000000000..bc529ebca065f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs @@ -0,0 +1,44 @@ +// +using System; +using System.Reflection; + +class Example +{ + public static void Main() + { + int limit = 10000000; + PrimeNumberGenerator primes = new PrimeNumberGenerator(limit); + int start = 1000001; + try + { + int[] values = primes.GetPrimesFrom(start); + Console.WriteLine("There are {0} prime numbers from {1} to {2}", + start, limit); + } + catch (NotPrimeException e) + { + Console.WriteLine("{0} is not prime", e.NonPrime); + Console.WriteLine(e); + Console.WriteLine("--------"); + } + + AppDomain domain = AppDomain.CreateDomain("Domain2"); + PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap( + typeof(Example).Assembly.FullName, + "PrimeNumberGenerator", true, + BindingFlags.Default, null, + new object[] { 1000000 }, null, null); + try + { + start = 100; + Console.WriteLine(gen.GetPrimesFrom(start)); + } + catch (NotPrimeException e) + { + Console.WriteLine("{0} is not prime", e.NonPrime); + Console.WriteLine(e); + Console.WriteLine("--------"); + } + } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/notprimeexception.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/notprimeexception.cs new file mode 100644 index 0000000000000..d3e0e6ade3949 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/notprimeexception.cs @@ -0,0 +1,40 @@ +// +using System; +using System.Runtime.Serialization; + +[Serializable()] +public class NotPrimeException : Exception +{ + private int notAPrime; + + protected NotPrimeException() + : base() + { } + + public NotPrimeException(int value) : + base(String.Format("{0} is not a prime number.", value)) + { + notAPrime = value; + } + + public NotPrimeException(int value, string message) + : base(message) + { + notAPrime = value; + } + + public NotPrimeException(int value, string message, Exception innerException) : + base(message, innerException) + { + notAPrime = value; + } + + protected NotPrimeException(SerializationInfo info, + StreamingContext context) + : base(info, context) + { } + + public int NonPrime + { get { return notAPrime; } } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/primenumbergenerator.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/primenumbergenerator.cs new file mode 100644 index 0000000000000..d91516fc2d384 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/primenumbergenerator.cs @@ -0,0 +1,65 @@ +// +using System; +using System.Collections.Generic; + +[Serializable] +public class PrimeNumberGenerator +{ + private const int START = 2; + private int maxUpperBound = 10000000; + private int upperBound; + private bool[] primeTable; + private List primes = new List(); + + public PrimeNumberGenerator(int upperBound) + { + if (upperBound > maxUpperBound) + { + string message = String.Format( + "{0} exceeds the maximum upper bound of {1}.", + upperBound, maxUpperBound); + throw new ArgumentOutOfRangeException(message); + } + this.upperBound = upperBound; + // Create array and mark 0, 1 as not prime (True). + primeTable = new bool[upperBound + 1]; + primeTable[0] = true; + primeTable[1] = true; + + // Use Sieve of Eratosthenes to determine prime numbers. + for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound)); + ctr++) + { + if (primeTable[ctr]) continue; + + for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++) + if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true; + } + // Populate array with prime number information. + int index = START; + while (index != -1) + { + index = Array.FindIndex(primeTable, index, (flag) => !flag); + if (index >= 1) + { + primes.Add(index); + index++; + } + } + } + + public int[] GetAllPrimes() + { + return primes.ToArray(); + } + + public int[] GetPrimesFrom(int prime) + { + int start = primes.FindIndex((value) => value == prime); + if (start < 0) + throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime)); + else + return primes.FindAll((value) => value >= prime).ToArray(); + } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs new file mode 100644 index 0000000000000..f479e5981e585 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs @@ -0,0 +1,78 @@ +// +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +public static class Library +{ + public static int[] FindOccurrences(this String s, String f) + { + var indexes = new List(); + int currentIndex = 0; + try { + while (currentIndex >= 0 && currentIndex < s.Length) { + currentIndex = s.IndexOf(f, currentIndex); + if (currentIndex >= 0) { + indexes.Add(currentIndex); + currentIndex++; + } + } + } + catch (ArgumentNullException e) { + // Perform some action here, such as logging this exception. + + throw; + } + return indexes.ToArray(); + } +} +// + +// +public class Example +{ + public static void Main() + { + String s = "It was a cold day when..."; + int[] indexes = s.FindOccurrences("a"); + ShowOccurrences(s, "a", indexes); + Console.WriteLine(); + + String toFind = null; + try { + indexes = s.FindOccurrences(toFind); + ShowOccurrences(s, toFind, indexes); + } + catch (ArgumentNullException e) { + Console.WriteLine("An exception ({0}) occurred.", + e.GetType().Name); + Console.WriteLine("Message:\n {0}\n", e.Message); + Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace); + } + } + + private static void ShowOccurrences(String s, String toFind, int[] indexes) + { + Console.Write("'{0}' occurs at the following character positions: ", + toFind); + for (int ctr = 0; ctr < indexes.Length; ctr++) + Console.Write("{0}{1}", indexes[ctr], + ctr == indexes.Length - 1 ? "" : ", "); + + Console.WriteLine(); + } +} +// The example displays the following output: +// 'a' occurs at the following character positions: 4, 7, 15 +// +// An exception (ArgumentNullException) occurred. +// Message: +// Value cannot be null. +// Parameter name: value +// +// Stack Trace: +// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri +// ngComparison comparisonType) +// at Library.FindOccurrences(String s, String f) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs new file mode 100644 index 0000000000000..06cbeb49ee7fe --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +public static class Library +{ + public static int[] FindOccurrences(this String s, String f) + { + var indexes = new List(); + int currentIndex = 0; + try { + while (currentIndex >= 0 && currentIndex < s.Length) { + currentIndex = s.IndexOf(f, currentIndex); + if (currentIndex >= 0) { + indexes.Add(currentIndex); + currentIndex++; + } + } + } + catch (ArgumentNullException e) { + // Perform some action here, such as logging this exception. +// + throw new ArgumentNullException("You must supply a search string.", + e); +// + } + return indexes.ToArray(); + } +} + +public class Example +{ + public static void Main() + { + String s = "It was a cold day when..."; + int[] indexes = s.FindOccurrences("a"); + ShowOccurrences(s, "a", indexes); + Console.WriteLine(); + + String toFind = null; + // + try { + indexes = s.FindOccurrences(toFind); + ShowOccurrences(s, toFind, indexes); + } + catch (ArgumentNullException e) { + Console.WriteLine("An exception ({0}) occurred.", + e.GetType().Name); + Console.WriteLine(" Message:\n{0}", e.Message); + Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace); + Exception ie = e.InnerException; + if (ie != null) { + Console.WriteLine(" The Inner Exception:"); + Console.WriteLine(" Exception Name: {0}", ie.GetType().Name); + Console.WriteLine(" Message: {0}\n", ie.Message); + Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace); + } + } + // The example displays the following output: + // 'a' occurs at the following character positions: 4, 7, 15 + // + // An exception (ArgumentNullException) occurred. + // Message: You must supply a search string. + // + // Stack Trace: + // at Library.FindOccurrences(String s, String f) + // at Example.Main() + // + // The Inner Exception: + // Exception Name: ArgumentNullException + // Message: Value cannot be null. + // Parameter name: value + // + // Stack Trace: + // at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri + // ngComparison comparisonType) + // at Library.FindOccurrences(String s, String f) + // + } + + private static void ShowOccurrences(String s, String toFind, int[] indexes) + { + Console.Write("'{0}' occurs at the following character positions: ", + toFind); + for (int ctr = 0; ctr < indexes.Length; ctr++) + Console.Write("{0}{1}", indexes[ctr], + ctr == indexes.Length - 1 ? "" : ", "); + + Console.WriteLine(); + } +} diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs new file mode 100644 index 0000000000000..f5d28a8667514 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs @@ -0,0 +1,40 @@ +// +using System; + +public class Person +{ + private string _name; + + public string Name + { + get { return _name; } + set { _name = value; } + } + + public override int GetHashCode() + { + return this.Name.GetHashCode(); + } + + public override bool Equals(object obj) + { + // This implementation contains an error in program logic: + // It assumes that the obj argument is not null. + Person p = (Person) obj; + return this.Name.Equals(p.Name); + } +} + +public class Example +{ + public static void Main() + { + Person p1 = new Person(); + p1.Name = "John"; + Person p2 = null; + + // The following throws a NullReferenceException. + Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); + } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/catchexception.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/catchexception.fs new file mode 100644 index 0000000000000..0c4ad82ea0c20 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/catchexception.fs @@ -0,0 +1,19 @@ +// +module ExceptionTestModule + +open System + +let x = 0 +try + let y = 100 / x + () +with +| :? ArithmeticException as e -> + printfn $"ArithmeticException Handler: {e}" +| e -> + printfn $"Generic Exception Handler: {e}" + +// This code example produces the following results: +// ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. +// at .$ExceptionTestModule.main@() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/example.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/example.fs new file mode 100644 index 0000000000000..34091a6ed741e --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/example.fs @@ -0,0 +1,33 @@ +module example + +// +open System +open System.Reflection + +let limit = 10000000 +let primes = PrimeNumberGenerator limit +let start = 1000001 +try + let values = primes.GetPrimesFrom start + printfn $"There are {values.Length} prime numbers from {start} to {limit}" +with :? NotPrimeException as e -> + printfn $"{e.NonPrime} is not prime" + printfn $"{e}" + printfn "--------" + +let domain = AppDomain.CreateDomain "Domain2" +let gen = + domain.CreateInstanceAndUnwrap( + typeof.Assembly.FullName, + "PrimeNumberGenerator", true, + BindingFlags.Default, null, + [| box 1000000 |], null, null) + :?> PrimeNumberGenerator +try + let start = 100 + printfn $"{gen.GetPrimesFrom start}" +with :? NotPrimeException as e -> + printfn $"{e.NonPrime} is not prime" + printfn $"{e}" + printfn "--------" +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/notprimeexception.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/notprimeexception.fs new file mode 100644 index 0000000000000..2abd864b56884 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/notprimeexception.fs @@ -0,0 +1,31 @@ +// +namespace global + +open System +open System.Runtime.Serialization + +[] +type NotPrimeException = + inherit Exception + val notAPrime: int + + member this.NonPrime = + this.notAPrime + + new (value) = + { inherit Exception($"%i{value} is not a prime number."); notAPrime = value } + + new (value, message) = + { inherit Exception(message); notAPrime = value } + + new (value, message, innerException: Exception) = + { inherit Exception(message, innerException); notAPrime = value } + + // F# does not support protected members + new () = + { inherit Exception(); notAPrime = 0 } + + new (info: SerializationInfo, context: StreamingContext) = + { inherit Exception(info, context); notAPrime = 0 } + +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs new file mode 100644 index 0000000000000..e984dca606990 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs @@ -0,0 +1,51 @@ +// +namespace global + +open System + +[] +type PrimeNumberGenerator(upperBound) = + let start = 2 + let maxUpperBound = 10000000 + let primes = ResizeArray() + let primeTable = + upperBound + 1 + |> Array.zeroCreate + + do + if upperBound > maxUpperBound then + let message = $"{upperBound} exceeds the maximum upper bound of {maxUpperBound}." + raise (ArgumentOutOfRangeException message) + + // Create array and mark 0, 1 as not prime (True). + primeTable[0] <- true + primeTable[1] <- true + + // Use Sieve of Eratosthenes to determine prime numbers. + for i = start to float upperBound |> sqrt |> ceil |> int do + if not primeTable[i] then + for multiplier = i to upperBound / i do + if i * multiplier <= upperBound then + primeTable[i * multiplier] <- true + + // Populate array with prime number information. + let mutable index = start + while index <> -1 do + index <- Array.FindIndex(primeTable, index, fun flag -> not flag) + if index >= 1 then + primes.Add index + index <- index + 1 + + member _.GetAllPrimes() = + primes.ToArray() + + member _.GetPrimesFrom(prime) = + let start = + Seq.findIndex ((=) prime) primes + + if start < 0 then + raise (NotPrimeException(prime, $"{prime} is not a prime number.") ) + else + Seq.filter ((>=) prime) primes + |> Seq.toArray +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow1.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow1.fs new file mode 100644 index 0000000000000..df59a6f6e893c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow1.fs @@ -0,0 +1,58 @@ +module rethrow1 + +// +open System + +module Library = + let findOccurrences (s: string) (f: string) = + let indexes = ResizeArray() + let mutable currentIndex = 0 + try + while currentIndex >= 0 && currentIndex < s.Length do + currentIndex <- s.IndexOf(f, currentIndex) + if currentIndex >= 0 then + indexes.Add currentIndex + currentIndex <- currentIndex + 1 + with :? ArgumentNullException -> + // Perform some action here, such as logging this exception. + reraise () + indexes.ToArray() +// + +// +open Library + +let showOccurrences toFind (indexes: int[]) = + printf $"'{toFind}' occurs at the following character positions: " + for i = 0 to indexes.Length - 1 do + printf $"""{indexes[i]}{if i = indexes.Length - 1 then "" else ", "}""" + printfn "" + +let s = "It was a cold day when..." +let indexes = findOccurrences s "a" +showOccurrences "a" indexes +printfn "" + +let toFind: string = null +try + let indexes = findOccurrences s toFind + showOccurrences toFind indexes + +with :? ArgumentNullException as e -> + printfn $"An exception ({e.GetType().Name}) occurred." + printfn $"Message:\n {e.Message}\n" + printfn $"Stack Trace:\n {e.StackTrace}\n" + +// The example displays the following output: +// 'a' occurs at the following character positions: 4, 7, 15 +// +// An exception (ArgumentNullException) occurred. +// Message: +// Value cannot be null. (Parameter 'value') +// +// Stack Trace: +// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri +// ngComparison comparisonType) +// at Library.findOccurrences(String s, String f) +// at .main@() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow3.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow3.fs new file mode 100644 index 0000000000000..b0c505c0ba40e --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/rethrow3.fs @@ -0,0 +1,46 @@ +module rethrow3 + +open System +open rethrow1 +open rethrow1.Library + +let e = Exception() +// +raise (ArgumentNullException("You must supply a search string.", e) ) +// + +let s = "It was a cold day when..." +// +try + let indexes = findOccurrences s toFind + showOccurrences toFind indexes +with :? ArgumentNullException as e -> + printfn $"An exception ({e.GetType().Name}) occurred." + printfn $" Message:\n{e.Message}" + printfn $" Stack Trace:\n {e.StackTrace}" + let ie = e.InnerException + if ie <> null then + printfn " The Inner Exception:" + printfn $" Exception Name: {ie.GetType().Name}" + printfn $" Message: {ie.Message}\n" + printfn $" Stack Trace:\n {ie.StackTrace}\n" +// The example displays the following output: +// 'a' occurs at the following character positions: 4, 7, 15 +// +// An exception (ArgumentNullException) occurred. +// Message: You must supply a search string. +// +// Stack Trace: +// at Library.FindOccurrences(String s, String f) +// at Example.Main() +// +// The Inner Exception: +// Exception Name: ArgumentNullException +// Message: Value cannot be null. +// Parameter name: value +// +// Stack Trace: +// at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri +// ngComparison comparisonType) +// at Library.FindOccurrences(String s, String f) +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors1.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors1.fs new file mode 100644 index 0000000000000..dbe43af381411 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors1.fs @@ -0,0 +1,25 @@ +module usageerrors1 + +// +// In F#, null is not a valid state for declared types +// without 'AllowNullLiteralAttribute' +[] +type Person() = + member val Name = "" with get, set + + override this.GetHashCode() = + this.Name.GetHashCode() + + override this.Equals(obj) = + // This implementation contains an error in program logic: + // It assumes that the obj argument is not null. + let p = obj :?> Person + this.Name.Equals p.Name + +let p1 = Person() +p1.Name <- "John" +let p2: Person = null + +// The following throws a NullReferenceException. +printfn $"p1 = p2: {p1.Equals p2}" +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors2.fs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors2.fs new file mode 100644 index 0000000000000..967988cb35d81 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/fsharp/usageerrors2.fs @@ -0,0 +1,28 @@ +module usageerrors2 + +// +// In F#, null is not a valid state for declared types +// without 'AllowNullLiteralAttribute' +[] +type Person() = + member val Name = "" with get, set + + override this.GetHashCode() = + this.Name.GetHashCode() + + override this.Equals(obj) = + // This implementation handles a null obj argument. + match obj with + | :? Person as p -> + this.Name.Equals p.Name + | _ -> + false + +let p1 = Person() +p1.Name <- "John" +let p2: Person = null + +printfn $"p1 = p2: {p1.Equals p2}" +// The example displays the following output: +// p1 = p2: False +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/catchexception.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/catchexception.vb new file mode 100644 index 0000000000000..5c7c271bc3af9 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/catchexception.vb @@ -0,0 +1,21 @@ +' +Class ExceptionTestClass + + Public Shared Sub Main() + Dim x As Integer = 0 + Try + Dim y As Integer = 100 / x + Catch e As ArithmeticException + Console.WriteLine("ArithmeticException Handler: {0}", e.ToString()) + Catch e As Exception + Console.WriteLine("Generic Exception Handler: {0}", e.ToString()) + End Try + End Sub +End Class +' +'This code example produces the following results: +' +'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow. +' at ExceptionTestClass.Main() +' +' \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/example.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/example.vb new file mode 100644 index 0000000000000..91ebfa1e56e8d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/example.vb @@ -0,0 +1,48 @@ +Option Strict Off + +' +Imports System.Reflection + +Module Example + Sub Main() + Dim limit As Integer = 10000000 + Dim primes As New PrimeNumberGenerator(limit) + Dim start As Integer = 1000001 + Try + Dim values() As Integer = primes.GetPrimesFrom(start) + Console.WriteLine("There are {0} prime numbers from {1} to {2}", + start, limit) + Catch e As NotPrimeException + Console.WriteLine("{0} is not prime", e.NonPrime) + Console.WriteLine(e) + Console.WriteLine("--------") + End Try + + Dim domain As AppDomain = AppDomain.CreateDomain("Domain2") + Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap( + GetType(Example).Assembly.FullName, + "PrimeNumberGenerator", True, + BindingFlags.Default, Nothing, + {1000000}, Nothing, Nothing) + Try + start = 100 + Console.WriteLine(gen.GetPrimesFrom(start)) + Catch e As NotPrimeException + Console.WriteLine("{0} is not prime", e.NonPrime) + Console.WriteLine(e) + Console.WriteLine("--------") + End Try + End Sub +End Module +' The example displays the following output: +' 1000001 is not prime +' NotPrimeException: 1000001 is not a prime number. +' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime) +' at Example.Main() +' -------- +' 100 is not prime +' NotPrimeException: 100 is not a prime number. +' at PrimeNumberGenerator.GetPrimesFrom(Int32 prime) +' at Example.Main() +' -------- +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/notprimeexception.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/notprimeexception.vb new file mode 100644 index 0000000000000..ee0d31fc20824 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/notprimeexception.vb @@ -0,0 +1,38 @@ +' +Imports System.Runtime.Serialization + + _ +Public Class NotPrimeException : Inherits Exception + Private notAPrime As Integer + + Protected Sub New() + MyBase.New() + End Sub + + Public Sub New(value As Integer) + MyBase.New(String.Format("{0} is not a prime number.", value)) + notAPrime = value + End Sub + + Public Sub New(value As Integer, message As String) + MyBase.New(message) + notAPrime = value + End Sub + + Public Sub New(value As Integer, message As String, innerException As Exception) + MyBase.New(message, innerException) + notAPrime = value + End Sub + + Protected Sub New(info As SerializationInfo, + context As StreamingContext) + MyBase.New(info, context) + End Sub + + Public ReadOnly Property NonPrime As Integer + Get + Return notAPrime + End Get + End Property +End Class +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/primenumbergenerator.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/primenumbergenerator.vb new file mode 100644 index 0000000000000..1d0f191d15b26 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/primenumbergenerator.vb @@ -0,0 +1,62 @@ +' +Imports System.Collections.Generic + + Public Class PrimeNumberGenerator + Private Const START As Integer = 2 + Private maxUpperBound As Integer = 10000000 + Private upperBound As Integer + Private primeTable() As Boolean + Private primes As New List(Of Integer) + + Public Sub New(upperBound As Integer) + If upperBound > maxUpperBound Then + Dim message As String = String.Format( + "{0} exceeds the maximum upper bound of {1}.", + upperBound, maxUpperBound) + Throw New ArgumentOutOfRangeException(message) + End If + Me.upperBound = upperBound + ' Create array and mark 0, 1 as not prime (True). + ReDim primeTable(upperBound) + primeTable(0) = True + primeTable(1) = True + + ' Use Sieve of Eratosthenes to determine prime numbers. + For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound))) + If primeTable(ctr) Then Continue For + + For multiplier As Integer = ctr To CInt(upperBound \ ctr) + If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True + Next + Next + ' Populate array with prime number information. + Dim index As Integer = START + Do While index <> -1 + index = Array.FindIndex(primeTable, index, Function(flag) + Return Not flag + End Function) + If index >= 1 Then + primes.Add(index) + index += 1 + End If + Loop + End Sub + + Public Function GetAllPrimes() As Integer() + Return primes.ToArray() + End Function + + Public Function GetPrimesFrom(prime As Integer) As Integer() + Dim start As Integer = primes.FindIndex(Function(value) + Return value = prime + End Function) + If start < 0 Then + Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime)) + Else + Return primes.FindAll(Function(value) + Return value >= prime + End Function).ToArray() + End If + End Function +End Class +' \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow1.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow1.vb new file mode 100644 index 0000000000000..99e3ec2c9e185 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow1.vb @@ -0,0 +1,75 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic +Imports System.Runtime.CompilerServices + +Public Module Library + + Public Function FindOccurrences(s As String, f As String) As Integer() + Dim indexes As New List(Of Integer) + Dim currentIndex As Integer = 0 + Try + Do While currentIndex >= 0 And currentIndex < s.Length + currentIndex = s.IndexOf(f, currentIndex) + If currentIndex >= 0 Then + indexes.Add(currentIndex) + currentIndex += 1 + End If + Loop + Catch e As ArgumentNullException + ' Perform some action here, such as logging this exception. + + Throw + End Try + Return indexes.ToArray() + End Function +End Module +' + +' +Module Example + Public Sub Main() + Dim s As String = "It was a cold day when..." + Dim indexes() As Integer = s.FindOccurrences("a") + ShowOccurrences(s, "a", indexes) + Console.WriteLine() + + Dim toFind As String = Nothing + Try + indexes = s.FindOccurrences(toFind) + ShowOccurrences(s, toFind, indexes) + Catch e As ArgumentNullException + Console.WriteLine("An exception ({0}) occurred.", + e.GetType().Name) + Console.WriteLine("Message:{0} {1}{0}", vbCrLf, e.Message) + Console.WriteLine("Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace) + End Try + End Sub + + Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer()) + Console.Write("'{0}' occurs at the following character positions: ", + toFind) + For ctr As Integer = 0 To indexes.Length - 1 + Console.Write("{0}{1}", indexes(ctr), + If(ctr = indexes.Length - 1, "", ", ")) + Next + Console.WriteLine() + End Sub +End Module +' The example displays the following output: +' 'a' occurs at the following character positions: 4, 7, 15 +' +' An exception (ArgumentNullException) occurred. +' Message: +' Value cannot be null. +' Parameter name: value +' +' Stack Trace: +' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri +' ngComparison comparisonType) +' at Library.FindOccurrences(String s, String f) +' at Example.Main() +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow3.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow3.vb new file mode 100644 index 0000000000000..ea7db159ee27c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/rethrow3.vb @@ -0,0 +1,88 @@ +' Visual Basic .NET Document +Option Strict On + +Imports System.Collections.Generic +Imports System.Runtime.CompilerServices + +Public Module Library + + Public Function FindOccurrences(s As String, f As String) As Integer() + Dim indexes As New List(Of Integer) + Dim currentIndex As Integer = 0 + Try + Do While currentIndex >= 0 And currentIndex < s.Length + currentIndex = s.IndexOf(f, currentIndex) + If currentIndex >= 0 Then + indexes.Add(currentIndex) + currentIndex += 1 + End If + Loop + Catch e As ArgumentNullException + ' Perform some action here, such as logging this exception. + + ' + Throw New ArgumentNullException("You must supply a search string.", + e) + ' + End Try + Return indexes.ToArray() + End Function +End Module + +Module Example + Public Sub Main() + Dim s As String = "It was a cold day when..." + Dim indexes() As Integer = s.FindOccurrences("a") + ShowOccurrences(s, "a", indexes) + Console.WriteLine() + + Dim toFind As String = Nothing + ' + Try + indexes = s.FindOccurrences(toFind) + ShowOccurrences(s, toFind, indexes) + Catch e As ArgumentNullException + Console.WriteLine("An exception ({0}) occurred.", + e.GetType().Name) + Console.WriteLine(" Message: {1}{0}", vbCrLf, e.Message) + Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace) + Dim ie As Exception = e.InnerException + If ie IsNot Nothing Then + Console.WriteLine(" The Inner Exception:") + Console.WriteLine(" Exception Name: {0}", ie.GetType().Name) + Console.WriteLine(" Message: {1}{0}", vbCrLf, ie.Message) + Console.WriteLine(" Stack Trace:{0} {1}{0}", vbCrLf, ie.StackTrace) + End If + End Try + ' The example displays the following output: + ' 'a' occurs at the following character positions: 4, 7, 15 + ' + ' An exception (ArgumentNullException) occurred. + ' Message: You must supply a search string. + ' + ' Stack Trace: + ' at Library.FindOccurrences(String s, String f) + ' at Example.Main() + ' + ' The Inner Exception: + ' Exception Name: ArgumentNullException + ' Message: Value cannot be null. + ' Parameter name: value + ' + ' Stack Trace: + ' at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri + ' ngComparison comparisonType) + ' at Library.FindOccurrences(String s, String f) + ' + End Sub + + Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer()) + Console.Write("'{0}' occurs at the following character positions: ", + toFind) + For ctr As Integer = 0 To indexes.Length - 1 + Console.Write("{0}{1}", indexes(ctr), + If(ctr = indexes.Length - 1, "", ", ")) + Next + Console.WriteLine() + End Sub +End Module diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors1.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors1.vb new file mode 100644 index 0000000000000..b55c87af3f3c4 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors1.vb @@ -0,0 +1,35 @@ +' Visual Basic .NET Document +Option Strict On + +' +Public Class Person + Private _name As String + + Public Property Name As String + Get + Return _name + End Get + Set + _name = value + End Set + End Property + + Public Overrides Function Equals(obj As Object) As Boolean + ' This implementation contains an error in program logic: + ' It assumes that the obj argument is not null. + Dim p As Person = CType(obj, Person) + Return Me.Name.Equals(p.Name) + End Function +End Class + +Module Example + Public Sub Main() + Dim p1 As New Person() + p1.Name = "John" + Dim p2 As Person = Nothing + + ' The following throws a NullReferenceException. + Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) + End Sub +End Module +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors2.vb b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors2.vb new file mode 100644 index 0000000000000..06b54f86011e6 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/usageerrors2.vb @@ -0,0 +1,39 @@ +' Visual Basic .NET Document +Option Strict On + +' +Public Class Person + Private _name As String + + Public Property Name As String + Get + Return _name + End Get + Set + _name = value + End Set + End Property + + Public Overrides Function Equals(obj As Object) As Boolean + ' This implementation handles a null obj argument. + Dim p As Person = TryCast(obj, Person) + If p Is Nothing Then + Return False + Else + Return Me.Name.Equals(p.Name) + End If + End Function +End Class + +Module Example + Public Sub Main() + Dim p1 As New Person() + p1.Name = "John" + Dim p2 As Person = Nothing + + Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)) + End Sub +End Module +' The example displays the following output: +' p1 = p2: False +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/Interface1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/Interface1.cs new file mode 100644 index 0000000000000..614b8a40d420b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/Interface1.cs @@ -0,0 +1,20 @@ +// +using System; +using System.Globalization; + +public class Example +{ + public static void Main() + { + var culture = CultureInfo.InvariantCulture; + IFormatProvider provider = culture; + + DateTimeFormatInfo dt = (DateTimeFormatInfo) provider; + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidCastException: +// Unable to cast object of type //System.Globalization.CultureInfo// to +// type //System.Globalization.DateTimeFormatInfo//. +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/ToString1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/ToString1.cs new file mode 100644 index 0000000000000..6b248a2cb827e --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/ToString1.cs @@ -0,0 +1,13 @@ +// +using System; + +public class Example +{ + public static void Main() + { + object value = 12; + // Cast throws an InvalidCastException exception. + string s = (string) value; + } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs new file mode 100644 index 0000000000000..68ac52ee72d82 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs @@ -0,0 +1,17 @@ +module Interface1 + +// +open System +open System.Globalization + +let culture = CultureInfo.InvariantCulture +let provider: IFormatProvider = culture + +let dt = provider :?> DateTimeFormatInfo + +// The example displays the following output: +// Unhandled Exception: System.InvalidCastException: +// Unable to cast object of type //System.Globalization.CultureInfo// to +// type //System.Globalization.DateTimeFormatInfo//. +// at Example.main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs new file mode 100644 index 0000000000000..a5ac598ee018f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs @@ -0,0 +1,7 @@ +module ToString1 + +// +let value: obj = 12 +// Cast throws an InvalidCastException exception. +let s = value :?> string +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs new file mode 100644 index 0000000000000..07f9dddbe0e61 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs @@ -0,0 +1,9 @@ +module ToString2 + +// +let value: obj = 12 +let s = value.ToString() +printfn $"{s}" +// The example displays the following output: +// 12 +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs new file mode 100644 index 0000000000000..c31c43898844c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs @@ -0,0 +1,35 @@ +module basetoderived1 + +// +open System + +type Person() = + member val Name = String.Empty with get, set + +type PersonWithId() = + inherit Person() + member val Id = String.Empty with get, set + + +let p = Person() +p.Name <- "John" +try + let pid = p :?> PersonWithId + printfn "Conversion succeeded." +with :? InvalidCastException -> + printfn "Conversion failed." + +let pid1 = PersonWithId() +pid1.Name <- "John" +pid1.Id <- "246" +let p1: Person = pid1 +try + let pid1a = p1 :?> PersonWithId + printfn "Conversion succeeded." +with :? InvalidCastException -> + printfn "Conversion failed." + +// The example displays the following output: +// Conversion failed. +// Conversion succeeded. +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs new file mode 100644 index 0000000000000..eccfe171f3021 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs @@ -0,0 +1,23 @@ +module iconvertible1 + +// +open System + +let flag = true +try + let conv: IConvertible = flag + let ch = conv.ToChar null + printfn "Conversion succeeded." +with :? InvalidCastException -> + printfn "Cannot convert a Boolean to a Char." + +try + let ch = Convert.ToChar flag + printfn "Conversion succeeded." +with :? InvalidCastException -> + printfn "Cannot convert a Boolean to a Char." + +// The example displays the following output: +// Cannot convert a Boolean to a Char. +// Cannot convert a Boolean to a Char. +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/Interface1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/Interface1.vb new file mode 100644 index 0000000000000..1898c8bc1c7c5 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/Interface1.vb @@ -0,0 +1,20 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Globalization + +Module Example + Public Sub Main() + Dim culture As CultureInfo = CultureInfo.InvariantCulture + Dim provider As IFormatProvider = culture + + Dim dt As DateTimeFormatInfo = CType(provider, DateTimeFormatInfo) + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidCastException: +' Unable to cast object of type 'System.Globalization.CultureInfo' to +' type 'System.Globalization.DateTimeFormatInfo'. +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb new file mode 100644 index 0000000000000..bff02c1e44619 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb @@ -0,0 +1,67 @@ +' Visual Basic .NET Document +Option Strict On + +' +Public Class Person + Dim _name As String + + Public Property Name As String + Get + Return _name + End Get + Set + _name = value + End Set + End Property +End Class + +Public Class PersonWithID : Inherits Person + Dim _id As String + + Public Property Id As String + Get + Return _id + End Get + Set + _id = value + End Set + End Property +End Class + +Module Example + Public Sub Main() + Dim p As New Person() + p.Name = "John" + Try + Dim pid As PersonWithId = CType(p, PersonWithId) + Console.WriteLine("Conversion succeeded.") + Catch e As InvalidCastException + Console.WriteLine("Conversion failed.") + End Try + + Dim pid1 As New PersonWithId() + pid1.Name = "John" + pid1.Id = "246" + Dim p1 As Person = pid1 + + Try + Dim pid1a As PersonWithId = CType(p1, PersonWithId) + Console.WriteLine("Conversion succeeded.") + Catch e As InvalidCastException + Console.WriteLine("Conversion failed.") + End Try + + Dim p2 As Person = Nothing + Try + Dim pid2 As PersonWithId = CType(p2, PersonWithId) + Console.WriteLine("Conversion succeeded.") + Catch e As InvalidCastException + Console.WriteLine("Conversion failed.") + End Try + End Sub +End Module +' The example displays the following output: +' Conversion failed. +' Conversion succeeded. +' Conversion succeeded. +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb new file mode 100644 index 0000000000000..e6d2f0a59ad8d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb @@ -0,0 +1,27 @@ +' Visual Basic .NET Document +Option Strict On + +' +Module Example + Public Sub Main() + Dim flag As Boolean = True + Try + Dim conv As IConvertible = flag + Dim ch As Char = conv.ToChar(Nothing) + Console.WriteLine("Conversion succeeded.") + Catch e As InvalidCastException + Console.WriteLine("Cannot convert a Boolean to a Char.") + End Try + + Try + Dim ch As Char = Convert.ToChar(flag) + Console.WriteLine("Conversion succeeded.") + Catch e As InvalidCastException + Console.WriteLine("Cannot convert a Boolean to a Char.") + End Try + End Sub +End Module +' The example displays the following output: +' Cannot convert a Boolean to a Char. +' Cannot convert a Boolean to a Char. +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable1.cs new file mode 100644 index 0000000000000..c642bbfa5b2b3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable1.cs @@ -0,0 +1,19 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] data = { 1, 2, 3, 4 }; + var average = data.Where(num => num > 4).Average(); + Console.Write("The average of numbers greater than 4 is {0}", + average); + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: Sequence contains no elements +// at System.Linq.Enumerable.Average(IEnumerable`1 source) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable3.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable3.cs new file mode 100644 index 0000000000000..404c72634abc6 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable3.cs @@ -0,0 +1,22 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] dbQueryResults = { 1, 2, 3, 4 }; + + var firstNum = dbQueryResults.First(n => n > 4); + + Console.WriteLine("The first value greater than 4 is {0}", + firstNum); + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains no matching element +// at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable5.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable5.cs new file mode 100644 index 0000000000000..1a84c9ebabeb2 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable5.cs @@ -0,0 +1,22 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] dbQueryResults = { 1, 2, 3, 4 }; + + var singleObject = dbQueryResults.Single(value => value > 4); + + // Display results. + Console.WriteLine("{0} is the only value greater than 4", singleObject); + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains no matching element +// at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable6.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable6.cs new file mode 100644 index 0000000000000..a00ff0fe7e16b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable6.cs @@ -0,0 +1,26 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] dbQueryResults = { 1, 2, 3, 4 }; + + var singleObject = dbQueryResults.SingleOrDefault(value => value > 2); + + if (singleObject != 0) + Console.WriteLine("{0} is the only value greater than 2", + singleObject); + else + // Handle an empty collection. + Console.WriteLine("No value is greater than 2"); + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains more than one matching element +// at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating1.cs new file mode 100644 index 0000000000000..643a1c1ce7e9f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating1.cs @@ -0,0 +1,28 @@ +// +using System; +using System.Collections.Generic; + +public class Example +{ + public static void Main() + { + var numbers = new List() { 1, 2, 3, 4, 5 }; + foreach (var number in numbers) { + int square = (int) Math.Pow(number, 2); + Console.WriteLine("{0}^{1}", number, square); + Console.WriteLine("Adding {0} to the collection...\n", square); + numbers.Add(square); + } + } +} +// The example displays the following output: +// 1^1 +// Adding 1 to the collection... +// +// +// Unhandled Exception: System.InvalidOperationException: Collection was modified; +// enumeration operation may not execute. +// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +// at System.Collections.Generic.List`1.Enumerator.MoveNextRare() +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort1.cs new file mode 100644 index 0000000000000..dd25bd14336d3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort1.cs @@ -0,0 +1,42 @@ +// +using System; +using System.Collections.Generic; + +public class Person +{ + public Person(String fName, String lName) + { + FirstName = fName; + LastName = lName; + } + + public String FirstName { get; set; } + public String LastName { get; set; } +} + +public class Example +{ + public static void Main() + { + var people = new List(); + + people.Add(new Person("John", "Doe")); + people.Add(new Person("Jane", "Doe")); + people.Sort(); + foreach (var person in people) + Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + } +} +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> +// System.ArgumentException: At least one object must implement IComparable. +// at System.Collections.Comparer.Compare(Object a, Object b) +// at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) +// at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit) +// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +// --- End of inner exception stack trace --- +// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +// at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) +// at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable1.cs new file mode 100644 index 0000000000000..f9965bcf10886 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable1.cs @@ -0,0 +1,25 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + var queryResult = new int?[] { 1, 2, null, 4 }; + var map = queryResult.Select(nullableInt => (int)nullableInt); + + // Display list. + foreach (var num in map) + Console.Write("{0} ", num); + Console.WriteLine(); + } +} +// The example displays the following output: +// 1 2 +// Unhandled Exception: System.InvalidOperationException: Nullable object must have a value. +// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +// at Example.
b__0(Nullable`1 nullableInt) +// at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs new file mode 100644 index 0000000000000..e1816262e3429 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs @@ -0,0 +1,15 @@ +module Enumerable1 + +// +open System +open System.Linq + +let data = [| 1; 2; 3; 4 |] +let average = + data.Where(fun num -> num > 4).Average(); +printfn $"The average of numbers greater than 4 is {average}" +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: Sequence contains no elements +// at System.Linq.Enumerable.Average(IEnumerable`1 source) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs new file mode 100644 index 0000000000000..2d1aafb7a9c09 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs @@ -0,0 +1,19 @@ +module Enumerable2 + +// +open System +open System.Linq + +let dbQueryResults = [| 1; 2; 3; 4 |] +let moreThan4 = + dbQueryResults.Where(fun num -> num > 4) + +if moreThan4.Any() then + printfn $"Average value of numbers greater than 4: {moreThan4.Average()}:" +else + // handle empty collection + printfn "The dataset has no values greater than 4." + +// The example displays the following output: +// The dataset has no values greater than 4. +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs new file mode 100644 index 0000000000000..d1a99e18b0884 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs @@ -0,0 +1,18 @@ +module Enumerable3 + +// +open System +open System.Linq + +let dbQueryResults = [| 1; 2; 3; 4 |] + +let firstNum = dbQueryResults.First(fun n -> n > 4) + +printfn $"The first value greater than 4 is {firstNum}" + +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains no matching element +// at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs new file mode 100644 index 0000000000000..6a6b2dc5a97f8 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs @@ -0,0 +1,18 @@ +module Enumerable4 + +// +open System +open System.Linq + +let dbQueryResults = [| 1; 2; 3; 4 |] + +let firstNum = dbQueryResults.FirstOrDefault(fun n -> n > 4) + +if firstNum = 0 then + printfn "No value is greater than 4." +else + printfn $"The first value greater than 4 is {firstNum}" + +// The example displays the following output: +// No value is greater than 4. +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs new file mode 100644 index 0000000000000..59779225c81ab --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs @@ -0,0 +1,19 @@ +module Enumerable5 + +// +open System +open System.Linq + +let dbQueryResults = [| 1; 2; 3; 4 |] + +let singleObject = dbQueryResults.Single(fun value -> value > 4) + +// Display results. +printfn $"{singleObject} is the only value greater than 4" + +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains no matching element +// at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs new file mode 100644 index 0000000000000..2e8b3f1244f02 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs @@ -0,0 +1,22 @@ +module Enumerable6 + +// +open System +open System.Linq + +let dbQueryResults = [| 1; 2; 3; 4 |] + +let singleObject = dbQueryResults.SingleOrDefault(fun value -> value > 2) + +if singleObject <> 0 then + printfn $"{singleObject} is the only value greater than 2" +else + // Handle an empty collection. + printfn "No value is greater than 2" + +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: +// Sequence contains more than one matching element +// at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs new file mode 100644 index 0000000000000..26da82184be9c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs @@ -0,0 +1,23 @@ +module Iterating1 + +// +open System + +let numbers = ResizeArray [| 1; 2; 3; 4; 5 |] +for number in numbers do + let square = Math.Pow(number, 2) |> int + printfn $"{number}^{square}" + printfn $"Adding {square} to the collection...\n" + numbers.Add square + +// The example displays the following output: +// 1^1 +// Adding 1 to the collection... +// +// +// Unhandled Exception: System.InvalidOperationException: Collection was modified +// enumeration operation may not execute. +// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +// at System.Collections.Generic.List`1.Enumerator.MoveNextRare() +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs new file mode 100644 index 0000000000000..0a066c5c81227 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs @@ -0,0 +1,37 @@ +module Iterating2 + +// +open System +open System.Collections.Generic + +let numbers = ResizeArray [| 1; 2; 3; 4; 5 |] + +let upperBound = numbers.Count - 1 +for i = 0 to upperBound do + let square = Math.Pow(numbers[i], 2) |> int + printfn $"{numbers[i]}^{square}" + printfn $"Adding {square} to the collection...\n" + numbers.Add square + +printfn "Elements now in the collection: " +for number in numbers do + printf $"{number} " +// The example displays the following output: +// 1^1 +// Adding 1 to the collection... +// +// 2^4 +// Adding 4 to the collection... +// +// 3^9 +// Adding 9 to the collection... +// +// 4^16 +// Adding 16 to the collection... +// +// 5^25 +// Adding 25 to the collection... +// +// Elements now in the collection: +// 1 2 3 4 5 1 4 9 16 25 +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs new file mode 100644 index 0000000000000..aa58eb48f1929 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs @@ -0,0 +1,25 @@ +module Iterating3 + +// +open System +open System.Collections.Generic + +let numbers = ResizeArray [| 1; 2; 3; 4; 5 |] +let temp = ResizeArray() + +// Square each number and store it in a temporary collection. +for number in numbers do + let square = Math.Pow(number, 2) |> int + temp.Add square + +// Combine the numbers into a single array. +let combined = Array.zeroCreate (numbers.Count + temp.Count) +Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count) +Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count) + +// Iterate the array. +for value in combined do + printf $"{value} " +// The example displays the following output: +// 1 2 3 4 5 1 4 9 16 25 +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs new file mode 100644 index 0000000000000..c963a34db548b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs @@ -0,0 +1,27 @@ +module List_Sort1 + +// +type Person(firstName: string, lastName: string) = + member val FirstName = firstName with get, set + member val LastName = lastName with get, set + +let people = ResizeArray() + +people.Add(Person("John", "Doe")) +people.Add(Person("Jane", "Doe")) +people.Sort() +for person in people do + printfn $"{person.FirstName} {person.LastName}" +// The example displays the following output: +// Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> +// System.ArgumentException: At least one object must implement IComparable. +// at System.Collections.Comparer.Compare(Object a, Object b) +// at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) +// at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit) +// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +// --- End of inner exception stack trace --- +// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +// at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) +// at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs new file mode 100644 index 0000000000000..84df643b76e54 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs @@ -0,0 +1,24 @@ +module List_Sort2 + +// +open System + +type Person(firstName: string, lastName: string) = + member val FirstName = firstName with get, set + member val LastName = lastName with get, set + + interface IComparable with + member this.CompareTo(other) = + compare $"{this.LastName} {this.FirstName}" $"{other.LastName} {other.FirstName}" + +let people = ResizeArray() + +people.Add(new Person("John", "Doe")) +people.Add(new Person("Jane", "Doe")) +people.Sort() +for person in people do + printfn $"{person.FirstName} {person.LastName}" +// The example displays the following output: +// Jane Doe +// John Doe +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs new file mode 100644 index 0000000000000..cba8d3890269b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs @@ -0,0 +1,26 @@ +module List_Sort3 + +// +open System +open System.Collections.Generic + +type Person(firstName, lastName) = + member val FirstName = firstName with get, set + member val LastName = lastName with get, set + +type PersonComparer() = + interface IComparer with + member _.Compare(x: Person, y: Person) = + $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}" + +let people = ResizeArray() + +people.Add(Person("John", "Doe")) +people.Add(Person("Jane", "Doe")) +people.Sort(PersonComparer()) +for person in people do + printfn $"{person.FirstName} {person.LastName}" +// The example displays the following output: +// Jane Doe +// John Doe +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs new file mode 100644 index 0000000000000..fcc7113db7f6d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs @@ -0,0 +1,25 @@ +module List_Sort4 + +// +open System +open System.Collections.Generic + +type Person(firstName, lastName) = + member val FirstName = firstName with get, set + member val LastName = lastName with get, set + +let personComparison (x: Person) (y: Person) = + $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}" + +let people = ResizeArray() + +people.Add(Person("John", "Doe")) +people.Add(Person("Jane", "Doe")) +people.Sort personComparison +for person in people do + printfn $"{person.FirstName} {person.LastName}" + +// The example displays the following output: +// Jane Doe +// John Doe +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs new file mode 100644 index 0000000000000..0703a1f749936 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs @@ -0,0 +1,21 @@ +module Nullable1 + +// +open System +open System.Linq + +let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |] +let map = queryResult.Select(fun nullableInt -> nullableInt.Value) + +// Display list. +for num in map do + printf $"{num} " +printfn "" +// The example displays the following output: +// 1 2 +// Unhandled Exception: System.InvalidOperationException: Nullable object must have a value. +// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +// at Example.
b__0(Nullable`1 nullableInt) +// at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs new file mode 100644 index 0000000000000..687b360631dcd --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs @@ -0,0 +1,23 @@ +module Nullable2 + +// +open System +open System.Linq + +let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |] +let numbers = queryResult.Select(fun nullableInt -> nullableInt.GetValueOrDefault()) + +// Display list using Nullable.HasValue. +for number in numbers do + printf $"{number} " +printfn "" + +let numbers2 = queryResult.Select(fun nullableInt -> if nullableInt.HasValue then nullableInt.Value else -1) +// Display list using Nullable.GetValueOrDefault. +for number in numbers2 do + printf $"{number} " +printfn "" +// The example displays the following output: +// 1 2 0 4 +// 1 2 -1 4 +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable1.vb new file mode 100644 index 0000000000000..0a2e83e32ffe0 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable1.vb @@ -0,0 +1,19 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim data() As Integer = { 1, 2, 3, 4 } + Dim average = data.Where(Function(num) num > 4).Average() + Console.Write("The average of numbers greater than 4 is {0}", + average) + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidOperationException: Sequence contains no elements +' at System.Linq.Enumerable.Average(IEnumerable`1 source) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable2.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable2.vb new file mode 100644 index 0000000000000..e43000d6a360d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable2.vb @@ -0,0 +1,23 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim dbQueryResults() As Integer = { 1, 2, 3, 4 } + Dim moreThan4 = dbQueryResults.Where(Function(num) num > 4) + + If moreThan4.Any() Then + Console.WriteLine("Average value of numbers greater than 4: {0}:", + moreThan4.Average()) + Else + ' Handle empty collection. + Console.WriteLine("The dataset has no values greater than 4.") + End If + End Sub +End Module +' The example displays the following output: +' The dataset has no values greater than 4. +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable3.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable3.vb new file mode 100644 index 0000000000000..d0e1de9ef526d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable3.vb @@ -0,0 +1,22 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim dbQueryResults() As Integer = { 1, 2, 3, 4 } + + Dim firstNum = dbQueryResults.First(Function(n) n > 4) + + Console.WriteLine("The first value greater than 4 is {0}", + firstNum) + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidOperationException: +' Sequence contains no matching element +' at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable4.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable4.vb new file mode 100644 index 0000000000000..e509c0eca98c9 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable4.vb @@ -0,0 +1,23 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim dbQueryResults() As Integer = { 1, 2, 3, 4 } + + Dim firstNum = dbQueryResults.FirstOrDefault(Function(n) n > 4) + + If firstNum = 0 Then + Console.WriteLIne("No value is greater than 4.") + Else + Console.WriteLine("The first value greater than 4 is {0}", + firstNum) + End If + End Sub +End Module +' The example displays the following output: +' No value is greater than 4. +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable5.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable5.vb new file mode 100644 index 0000000000000..36a4b8c3f6c48 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable5.vb @@ -0,0 +1,23 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim dbQueryResults() As Integer = { 1, 2, 3, 4 } + + Dim singleObject = dbQueryResults.Single(Function(value) value > 4) + + ' Display results. + Console.WriteLine("{0} is the only value greater than 4", + singleObject) + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidOperationException: +' Sequence contains no matching element +' at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable6.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable6.vb new file mode 100644 index 0000000000000..7286139131979 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Enumerable6.vb @@ -0,0 +1,27 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim dbQueryResults() As Integer = { 1, 2, 3, 4 } + + Dim singleObject = dbQueryResults.SingleOrDefault(Function(value) value > 2) + + If singleObject <> 0 Then + Console.WriteLine("{0} is the only value greater than 2", + singleObject) + Else + ' Handle an empty collection. + Console.WriteLine("No value is greater than 2") + End If + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidOperationException: +' Sequence contains more than one matching element +' at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form1.vb new file mode 100644 index 0000000000000..48508e05c3132 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form1.vb @@ -0,0 +1,31 @@ +Imports System.Threading + +Public Class Form1 + ' + Dim lines As New List(Of String)() + Private Async Sub threadExampleBtn_Click(sender As Object, e As EventArgs) Handles threadExampleBtn.Click + textBox1.Text = String.Empty + lines.Clear() + + lines.Add("Simulating work on UI thread.") + textBox1.Lines = lines.ToArray() + DoSomeWork(20) + + lines.Add("Simulating work on non-UI thread.") + textBox1.Lines = lines.ToArray() + Await Task.Run(Sub() DoSomeWork(1000)) + + lines.Add("ThreadsExampleBtn_Click completes. ") + textBox1.Lines = lines.ToArray() + End Sub + + Private Async Sub DoSomeWork(milliseconds As Integer) + ' Simulate work. + Await Task.Delay(milliseconds) + + ' Report completion. + lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds)) + textBox1.Lines = lines.ToArray() + End Sub + ' +End Class diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form11.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form11.vb new file mode 100644 index 0000000000000..dd001ceb45f24 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Form11.vb @@ -0,0 +1,42 @@ +Imports System.Collections.Generic +Imports System.Threading.Tasks + +Public Class Form1 + + Dim lines As New List(Of String)() + + Private Async Sub theadExampleBtn_Click(sender As Object, e As EventArgs) Handles theadExampleBtn.Click + textBox1.Text = String.Empty + lines.Clear() + + lines.Add("Simulating work on UI thread.") + textBox1.Lines = lines.ToArray() + DoSomeWork(20) + + lines.Add("Simulating work on non-UI thread.") + textBox1.Lines = lines.ToArray() + Await Task.Run(Sub() DoSomeWork(1000)) + + lines.Add("ThreadsExampleBtn_Click completes. ") + textBox1.Lines = lines.ToArray() + End Sub + + ' + Private Async Sub DoSomeWork(milliseconds As Integer) + ' Simulate work. + Await Task.Delay(milliseconds) + + ' Report completion. + Dim uiMarshal As Boolean = textBox1.InvokeRequired + Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf, + milliseconds, If(uiMarshal, String.Empty, "non-")) + lines.Add(msg) + + If uiMarshal Then + textBox1.Invoke(New Action(Sub() textBox1.Lines = lines.ToArray())) + Else + textBox1.Lines = lines.ToArray() + End If + End Sub + ' +End Class diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating1.vb new file mode 100644 index 0000000000000..03216fa857dca --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating1.vb @@ -0,0 +1,30 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Module Example + Public Sub Main() + Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) + For Each number In numbers + Dim square As Integer = CInt(Math.Pow(number, 2)) + Console.WriteLine("{0}^{1}", number, square) + Console.WriteLine("Adding {0} to the collection..." + vbCrLf, + square) + numbers.Add(square) + Next + End Sub +End Module +' The example displays the following output: +' 1^1 +' Adding 1 to the collection... +' +' +' Unhandled Exception: System.InvalidOperationException: Collection was modified; +' enumeration operation may not execute. +' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +' at System.Collections.Generic.List`1.Enumerator.MoveNextRare() +' at Example.Main() +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating2.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating2.vb new file mode 100644 index 0000000000000..ca909c64e02f0 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating2.vb @@ -0,0 +1,44 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Module Example + Public Sub Main() + Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) + Dim upperBound = numbers.Count - 1 + + For ctr As Integer = 0 To upperBound + Dim square As Integer = CInt(Math.Pow(numbers(ctr), 2)) + Console.WriteLine("{0}^{1}", numbers(ctr), square) + Console.WriteLine("Adding {0} to the collection..." + vbCrLf, + square) + numbers.Add(square) + Next + + Console.WriteLine("Elements now in the collection: ") + For Each number In numbers + Console.Write("{0} ", number) + Next + End Sub +End Module +' The example displays the following output: +' 1^1 +' Adding 1 to the collection... +' +' 2^4 +' Adding 4 to the collection... +' +' 3^9 +' Adding 9 to the collection... +' +' 4^16 +' Adding 16 to the collection... +' +' 5^25 +' Adding 25 to the collection... +' +' Elements now in the collection: +' 1 2 3 4 5 1 4 9 16 25 +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating3.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating3.vb new file mode 100644 index 0000000000000..32e73a1c73578 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Iterating3.vb @@ -0,0 +1,31 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Module Example + Public Sub Main() + Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) + Dim temp As New List(Of Integer)() + + ' Square each number and store it in a temporary collection. + For Each number In numbers + Dim square As Integer = CInt(Math.Pow(number, 2)) + temp.Add(square) + Next + + ' Combine the numbers into a single array. + Dim combined(numbers.Count + temp.Count - 1) As Integer + Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count) + Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count) + + ' Iterate the array. + For Each value In combined + Console.Write("{0} ", value) + Next + End Sub +End Module +' The example displays the following output: +' 1 2 3 4 5 1 4 9 16 25 +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort1.vb new file mode 100644 index 0000000000000..533c3d5e5cf8a --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort1.vb @@ -0,0 +1,43 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Public Class Person + Public Sub New(fName As String, lName As String) + FirstName = fName + LastName = lName + End Sub + + Public Property FirstName As String + Public Property LastName As String +End Class + +Module Example + Public Sub Main() + Dim people As New List(Of Person)() + + people.Add(New Person("John", "Doe")) + people.Add(New Person("Jane", "Doe")) + people.Sort() + For Each person In people + Console.WriteLine("{0} {1}", person.FirstName, person.LastName) + Next + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> +' System.ArgumentException: At least one object must implement IComparable. +' at System.Collections.Comparer.Compare(Object a, Object b) +' at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) +' at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit) +' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +' --- End of inner exception stack trace --- +' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) +' at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) +' at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer) +' at Example.Main() +' + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort2.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort2.vb new file mode 100644 index 0000000000000..22986ce9a5046 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort2.vb @@ -0,0 +1,38 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Public Class Person : Implements IComparable(Of Person) + Public Sub New(fName As String, lName As String) + FirstName = fName + LastName = lName + End Sub + + Public Property FirstName As String + Public Property LastName As String + + Public Function CompareTo(other As Person) As Integer _ + Implements IComparable(Of Person).CompareTo + Return String.Format("{0} {1}", LastName, FirstName). + CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName)) + End Function +End Class + +Module Example + Public Sub Main() + Dim people As New List(Of Person)() + + people.Add(New Person("John", "Doe")) + people.Add(New Person("Jane", "Doe")) + people.Sort() + For Each person In people + Console.WriteLine("{0} {1}", person.FirstName, person.LastName) + Next + End Sub +End Module +' The example displays the following output: +' Jane Doe +' John Doe +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort3.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort3.vb new file mode 100644 index 0000000000000..1ca02799281d3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort3.vb @@ -0,0 +1,41 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Public Class Person + Public Sub New(fName As String, lName As String) + FirstName = fName + LastName = lName + End Sub + + Public Property FirstName As String + Public Property LastName As String +End Class + +Public Class PersonComparer : Implements IComparer(Of Person) + Public Function Compare(x As Person, y As Person) As Integer _ + Implements IComparer(Of Person).Compare + Return String.Format("{0} {1}", x.LastName, x.FirstName). + CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) + End Function +End Class + +Module Example + Public Sub Main() + Dim people As New List(Of Person)() + + people.Add(New Person("John", "Doe")) + people.Add(New Person("Jane", "Doe")) + people.Sort(New PersonComparer()) + For Each person In people + Console.WriteLine("{0} {1}", person.FirstName, person.LastName) + Next + End Sub +End Module +' The example displays the following output: +' Jane Doe +' John Doe +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort4.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort4.vb new file mode 100644 index 0000000000000..183c3ab9384b9 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/List_Sort4.vb @@ -0,0 +1,37 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Collections.Generic + +Public Class Person + Public Sub New(fName As String, lName As String) + FirstName = fName + LastName = lName + End Sub + + Public Property FirstName As String + Public Property LastName As String +End Class + +Module Example + Public Sub Main() + Dim people As New List(Of Person)() + + people.Add(New Person("John", "Doe")) + people.Add(New Person("Jane", "Doe")) + people.Sort(AddressOf PersonComparison) + For Each person In people + Console.WriteLine("{0} {1}", person.FirstName, person.LastName) + Next + End Sub + + Public Function PersonComparison(x As Person, y As Person) As Integer + Return String.Format("{0} {1}", x.LastName, x.FirstName). + CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) + End Function +End Module +' The example displays the following output: +' Jane Doe +' John Doe +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainPage.xaml.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainPage.xaml.vb new file mode 100644 index 0000000000000..9ec78cbf92b82 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainPage.xaml.vb @@ -0,0 +1,43 @@ +' The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 + +Imports Windows.UI.Core + + +''' +''' An empty page that can be used on its own or navigated to within a Frame. +''' + +Public NotInheritable Class MainPage + Inherits Page + + + ' + Private Async Sub DoSomeWork(milliseconds As Integer) + ' Simulate work. + Await Task.Delay(milliseconds) + + ' Report completion. + Dim uiAccess As Boolean = textBox1.Dispatcher.HasThreadAccess + Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf, + milliseconds, If(uiAccess, String.Empty, "non-")) + If (uiAccess) Then + textBox1.Text += msg + Else + Await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() textBox1.Text += msg) + End If + End Sub + ' + + Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) ' Handles threadExampleBtn.Click + textBox1.Text = String.Empty + + textBox1.Text = "Simulating work on UI thread." + vbCrLf + DoSomeWork(20) + textBox1.Text += "Work completed..." + vbCrLf + + textBox1.Text += "Simulating work on non-UI thread." + vbCrLf + Await Task.Run(Sub() DoSomeWork(1000)) + textBox1.Text += "Work completed.." + vbCrLf + + End Sub +End Class diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindow.xaml.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindow.xaml.vb new file mode 100644 index 0000000000000..836bd1843f680 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindow.xaml.vb @@ -0,0 +1,29 @@ +Imports System.Threading +Imports System.Threading.Tasks + +Class MainWindow + ' + Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) Handles threadExampleBtn.Click + textBox1.Text = String.Empty + + textBox1.Text = "Simulating work on UI thread." + vbCrLf + DoSomeWork(20) + textBox1.Text += "Work completed..." + vbCrLf + + textBox1.Text += "Simulating work on non-UI thread." + vbCrLf + Await Task.Factory.StartNew(Sub() + DoSomeWork(1000) + End Sub) + textBox1.Text += "Work completed..." + vbCrLf + End Sub + + Private Async Sub DoSomeWork(milliseconds As Integer) + ' Simulate work. + Await Task.Delay(milliseconds) + + ' Report completion. + Dim msg = String.Format("Some work completed in {0} ms.", milliseconds) + vbCrLf + textBox1.Text += msg + End Sub + ' +End Class diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindowDispatcher.xaml.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindowDispatcher.xaml.vb new file mode 100644 index 0000000000000..daee610d1f204 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/MainWindowDispatcher.xaml.vb @@ -0,0 +1,36 @@ +Imports System.Threading +Imports System.Threading.Tasks + +Class MainWindow + Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) Handles threadExampleBtn.Click + textBox1.Text = String.Empty + + textBox1.Text = "Simulating work on UI thread." + vbCrLf + DoSomeWork(20) + textBox1.Text += "Work completed..." + + textBox1.Text += "Simulating work on non-UI thread." + vbCrLf + Await Task.Factory.StartNew(Sub() + DoSomeWork(1000) + End Sub) + textBox1.Text += "Work completed..." + vbCrLf + End Sub + + ' + Private Async Sub DoSomeWork(milliseconds As Integer) + ' Simulate work. + Await Task.Delay(milliseconds) + + ' Report completion. + Dim uiAccess As Boolean = textBox1.Dispatcher.CheckAccess() + Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread", + milliseconds, If(uiAccess, String.Empty, "non-")) + + vbCrLf + If uiAccess Then + textBox1.Text += msg + Else + textBox1.Dispatcher.Invoke( Sub() textBox1.Text += msg) + End If + End Sub + ' +End Class diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable1.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable1.vb new file mode 100644 index 0000000000000..a5b2624ce83b2 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable1.vb @@ -0,0 +1,26 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim queryResult = New Integer?() { 1, 2, Nothing, 4 } + Dim map = queryResult.Select(Function(nullableInt) CInt(nullableInt)) + + ' Display list. + For Each num In map + Console.Write("{0} ", num) + Next + Console.WriteLine() + End Sub +End Module +' The example displays thIe following output: +' 1 2 +' Unhandled Exception: System.InvalidOperationException: Nullable object must have a value. +' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +' at Example.
b__0(Nullable`1 nullableInt) +' at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable2.vb b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable2.vb new file mode 100644 index 0000000000000..18446c169ea32 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/Nullable2.vb @@ -0,0 +1,32 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Linq + +Module Example + Public Sub Main() + Dim queryResult = New Integer?() { 1, 2, Nothing, 4 } + Dim numbers = queryResult.Select(Function(nullableInt) _ + CInt(nullableInt.GetValueOrDefault())) + ' Display list. + For Each number In numbers + Console.Write("{0} ", number) + Next + Console.WriteLine() + + ' Use -1 to indicate a missing values. + numbers = queryResult.Select(Function(nullableInt) _ + CInt(If(nullableInt.HasValue, nullableInt, -1))) + ' Display list. + For Each number In numbers + Console.Write("{0} ", number) + Next + Console.WriteLine() + + End Sub +End Module +' The example displays the following output: +' 1 2 0 4 +' 1 2 -1 4 +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/BadState1.cs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/BadState1.cs new file mode 100644 index 0000000000000..431ad2b35c546 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/BadState1.cs @@ -0,0 +1,38 @@ +// +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +public class Example +{ + public static async Task Main() + { + Encoding enc = Encoding.Unicode; + String value = "This is a string to persist."; + Byte[] bytes = enc.GetBytes(value); + + FileStream fs = new FileStream(@".\TestFile.dat", + FileMode.Open, + FileAccess.Read); + Task t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length); + Task t2 = t.ContinueWith( (a) => fs.WriteAsync(bytes, 0, bytes.Length) ); + await t2; + fs.Close(); + } +} +// The example displays the following output: +// Unhandled Exception: System.NotSupportedException: Stream does not support writing. +// at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state +// , Boolean serializeAsynchronously) +// at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta +// teObject) +// at System.IO.Stream.<>c.b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, +// Object state) +// at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet +// hod, Func`3 endMethod) +// at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) +// at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +// at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs new file mode 100644 index 0000000000000..68abcea9a04a3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs @@ -0,0 +1,58 @@ +// +using System; +using System.IO; +using System.Threading.Tasks; + +public class Example +{ + public static async Task Main() + { + String name = @".\TestFile.dat"; + var fs = new FileStream(name, + FileMode.Create, + FileAccess.Write); + Console.WriteLine("Filename: {0}, Encoding: {1}", + name, await FileUtilities.GetEncodingType(fs)); + } +} + +public class FileUtilities +{ + public enum EncodingType + { None = 0, Unknown = -1, Utf8 = 1, Utf16 = 2, Utf32 = 3 } + + public async static Task GetEncodingType(FileStream fs) + { + Byte[] bytes = new Byte[4]; + int bytesRead = await fs.ReadAsync(bytes, 0, 4); + if (bytesRead < 2) + return EncodingType.None; + + if (bytesRead >= 3 & (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)) + return EncodingType.Utf8; + + if (bytesRead == 4) { + var value = BitConverter.ToUInt32(bytes, 0); + if (value == 0x0000FEFF | value == 0xFEFF0000) + return EncodingType.Utf32; + } + + var value16 = BitConverter.ToUInt16(bytes, 0); + if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) + return EncodingType.Utf16; + + return EncodingType.Unknown; + } +} +// The example displays the following output: +// Unhandled Exception: System.NotSupportedException: Stream does not support reading. +// at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback callback, Object state) +// at System.IO.Stream.<>c.b__46_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, Object state) +// at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance, TArgs](TInstance thisRef, TArgs args, Func`5 beginMethod, Func`3 endMethod) +// at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) +// at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +// at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) +// at FileUtilities.GetEncodingType(FileStream fs) in C:\Work\docs\program.cs:line 26 +// at Example.Main() in C:\Work\docs\program.cs:line 13 +// at Example.
() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs new file mode 100644 index 0000000000000..5b65caace076c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Threading.Tasks; + +public class Example +{ + public static async Task Main() + { + String name = @".\TestFile.dat"; + var fs = new FileStream(name, + FileMode.Create, + FileAccess.Write); + Console.WriteLine("Filename: {0}, Encoding: {1}", + name, await FileUtilities.GetEncodingType(fs)); + } +} + +public class FileUtilities +{ + public enum EncodingType + { None = 0, Unknown = -1, Utf8 = 1, Utf16 = 2, Utf32 = 3 } + + // + public static async Task GetEncodingType(FileStream fs) + { + if (!fs.CanRead) + return EncodingType.Unknown; + + Byte[] bytes = new Byte[4]; + int bytesRead = await fs.ReadAsync(bytes, 0, 4); + if (bytesRead < 2) + return EncodingType.None; + + if (bytesRead >= 3 & (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)) + return EncodingType.Utf8; + + if (bytesRead == 4) { + var value = BitConverter.ToUInt32(bytes, 0); + if (value == 0x0000FEFF | value == 0xFEFF0000) + return EncodingType.Utf32; + } + + var value16 = BitConverter.ToUInt16(bytes, 0); + if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) + return EncodingType.Utf16; + + return EncodingType.Unknown; + } +} +// The example displays the following output: +// Filename: .\TestFile.dat, Encoding: Unknown +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs new file mode 100644 index 0000000000000..448563e30e738 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs @@ -0,0 +1,34 @@ +module BadState + +// +open System.IO +open System.Text + +let main = task { + let enc = Encoding.Unicode + let value = "This is a string to persist." + let bytes = enc.GetBytes value + + let fs = new FileStream(@".\TestFile.dat", FileMode.Open, FileAccess.Read) + let t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length) + let t2 = t.ContinueWith(fun a -> fs.WriteAsync(bytes, 0, bytes.Length)) + let! _ = t2 + fs.Close() +} +main.Wait() + +// The example displays the following output: +// Unhandled Exception: System.NotSupportedException: Stream does not support writing. +// at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state +// , Boolean serializeAsynchronously) +// at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta +// teObject) +// at System.IO.Stream.<>c.b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, +// Object state) +// at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet +// hod, Func`3 endMethod) +// at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) +// at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +// at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) +// at .main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs new file mode 100644 index 0000000000000..67c754a2d288b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs @@ -0,0 +1,55 @@ +module TestProp1 + +// +open System +open System.IO + +module FileUtilities = + type EncodingType = + | None = 0 + | Unknown = -1 + | Utf8 = 1 + | Utf16 = 2 + | Utf32 = 3 + + let getEncodingType (fs: FileStream) = + task { + let bytes = Array.zeroCreate 4 + let! bytesRead = fs.ReadAsync(bytes, 0, 4) + if bytesRead < 2 then + return EncodingType.None + + elif bytesRead >= 3 && bytes[0] = 0xEFuy && bytes[1] = 0xBBuy && bytes[2] = 0xBFuy then + return EncodingType.Utf8 + else + let value = BitConverter.ToUInt32(bytes, 0) + if bytesRead = 4 && (value = 0x0000FEFFu || value = 0xFEFF0000u) then + return EncodingType.Utf32 + else + let value16 = BitConverter.ToUInt16(bytes, 0) + if value16 = 0xFEFFus || value16 = 0xFFFEus then + return EncodingType.Utf16 + else + return EncodingType.Unknown + } + +let main _ = + task { + let name = @".\TestFile.dat" + let fs = new FileStream(name, FileMode.Create, FileAccess.Write) + let! et = FileUtilities.getEncodingType fs + printfn $"Filename: {name}, Encoding: {et}" + } + +// The example displays the following output: +// Unhandled Exception: System.NotSupportedException: Stream does not support reading. +// at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback callback, Object state) +// at System.IO.Stream.<>c.b__46_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, Object state) +// at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance, TArgs](TInstance thisRef, TArgs args, Func`5 beginMethod, Func`3 endMethod) +// at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) +// at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +// at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) +// at FileUtilities.GetEncodingType(FileStream fs) +// at Example.Main() +// at Example.
() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs new file mode 100644 index 0000000000000..b5f68d73b68dc --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs @@ -0,0 +1,48 @@ +module TestProp2 + +open System +open System.IO + +module FileUtilities = + type EncodingType = + | None = 0 + | Unknown = -1 + | Utf8 = 1 + | Utf16 = 2 + | Utf32 = 3 + + // + let getEncodingType (fs: FileStream) = + task { + if not fs.CanRead then + return EncodingType.Unknown + else + let bytes = Array.zeroCreate 4 + let! bytesRead = fs.ReadAsync(bytes, 0, 4) + if bytesRead < 2 then + return EncodingType.None + + elif bytesRead >= 3 && bytes[0] = 0xEFuy && bytes[1] = 0xBBuy && bytes[2] = 0xBFuy then + return EncodingType.Utf8 + else + let value = BitConverter.ToUInt32(bytes, 0) + if bytesRead = 4 && (value = 0x0000FEFFu || value = 0xFEFF0000u) then + return EncodingType.Utf32 + else + let value16 = BitConverter.ToUInt16(bytes, 0) + if value16 = 0xFEFFus || value16 = 0xFFFEus then + return EncodingType.Utf16 + else + return EncodingType.Unknown + } + // The example displays the following output: + // Filename: .\TestFile.dat, Encoding: Unknown + // + +let main _ = + task { + let name = @".\TestFile.dat" + let fs = new FileStream(name, FileMode.Create, FileAccess.Write) + let! et = FileUtilities.getEncodingType fs + printfn $"Filename: {name}, Encoding: {et}" + } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/BadState1.vb b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/BadState1.vb new file mode 100644 index 0000000000000..682e15bf30a9b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/BadState1.vb @@ -0,0 +1,37 @@ +' Visual Basic .NET Document +Option Strict On +' +Imports System.IO +Imports System.Text +Imports System.Threading.Tasks + +Module Example + Public Sub Main() + Dim enc As Encoding = Encoding.Unicode + Dim value As String = "This is a string to persist." + Dim bytes() As Byte = enc.GetBytes(value) + + Dim fs As New FileStream(".\TestFile.dat", + FileMode.Open, + FileAccess.Read) + Dim t As Task = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length) + Dim t2 As Task = t.ContinueWith(Sub(a) fs.WriteAsync(bytes, 0, bytes.Length)) + t2.Wait() + fs.Close() + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.NotSupportedException: Stream does not support writing. +' at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state +' , Boolean serializeAsynchronously) +' at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta +' teObject) +' at System.IO.Stream.<>c.b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, +' Object state) +' at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet +' hod, Func`3 endMethod) +' at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) +' at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +' at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp1.vb b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp1.vb new file mode 100644 index 0000000000000..22d368a6e6344 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp1.vb @@ -0,0 +1,70 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.IO +Imports System.Threading.Tasks + +Module Example + Public Sub Main() + Dim name As String = ".\TestFile.dat" + Dim fs As New FileStream(name, + FileMode.Create, + FileAccess.Write) + Console.WriteLine("Filename: {0}, Encoding: {1}", + name, FileUtilities.GetEncodingType(fs)) + End Sub +End Module + +Public Class FileUtilities + Public Enum EncodingType As Integer + None = 0 + Unknown = -1 + Utf8 = 1 + Utf16 = 2 + Utf32 = 3 + End Enum + + Public Shared Function GetEncodingType(fs As FileStream) As EncodingType + Dim bytes(3) As Byte + Dim t As Task(Of Integer) = fs.ReadAsync(bytes, 0, 4) + t.Wait() + Dim bytesRead As Integer = t.Result + If bytesRead < 2 Then Return EncodingType.None + + If bytesRead >= 3 And (bytes(0) = &hEF AndAlso bytes(1) = &hBB AndAlso bytes(2) = &hBF) Then + Return EncodingType.Utf8 + End If + + If bytesRead = 4 Then + Dim value As UInteger = BitConverter.ToUInt32(bytes, 0) + If value = &h0000FEFF Or value = &hFEFF0000 Then + Return EncodingType.Utf32 + End If + End If + + Dim value16 As UInt16 = BitConverter.ToUInt16(bytes, 0) + If value16 = &hFEFF Or value16 = &hFFFE Then + Return EncodingType.Utf16 + End If + + Return EncodingType.Unknown + End Function +End Class +' The example displays the following output: +' Unhandled Exception: System.NotSupportedException: Stream does not support reading. +' at System.IO.Stream.BeginReadInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state, +' Boolean serializeAsynchronously) +' at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stat +' eObject) +' at System.IO.Stream.<>c.b__43_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, O +' bject state) +' at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet +' hod, Func`3 endMethod) +' at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) +' at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) +' at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) +' at FileUtilities.GetEncodingType(FileStream fs) +' at Example.Main() +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp2.vb b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp2.vb new file mode 100644 index 0000000000000..b085354e5f514 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/TestProp2.vb @@ -0,0 +1,60 @@ +' Visual Basic .NET Document +Option Strict On + +Imports System.IO +Imports System.Threading.Tasks + +Module Example + Public Sub Main() + Dim name As String = ".\TestFile.dat" + Dim fs As New FileStream(name, + FileMode.Create, + FileAccess.Write) + Console.WriteLine("Filename: {0}, Encoding: {1}", + name, FileUtilities.GetEncodingType(fs)) + End Sub +End Module + +' +Public Class FileUtilities + Public Enum EncodingType As Integer + None = 0 + Unknown = -1 + Utf8 = 1 + Utf16 = 2 + Utf32 = 3 + End Enum + + Public Shared Function GetEncodingType(fs As FileStream) As EncodingType + If Not fs.CanRead Then + Return EncodingType.Unknown + + Dim bytes(3) As Byte + Dim t As Task(Of Integer) = fs.ReadAsync(bytes, 0, 4) + t.Wait() + Dim bytesRead As Integer = t.Result + If bytesRead < 2 Then Return EncodingType.None + + If bytesRead >= 3 And (bytes(0) = &hEF AndAlso bytes(1) = &hBB AndAlso bytes(2) = &hBF) Then + Return EncodingType.Utf8 + End If + + If bytesRead = 4 Then + Dim value As UInteger = BitConverter.ToUInt32(bytes, 0) + If value = &h0000FEFF Or value = &hFEFF0000 Then + Return EncodingType.Utf32 + End If + End If + + Dim value16 As UInt16 = BitConverter.ToUInt16(bytes, 0) + If value16 = &hFEFF Or value16 = &hFFFE Then + Return EncodingType.Utf16 + End If + + Return EncodingType.Unknown + End Function +End Class +' The example displays the following output: +' Filename: .\TestFile.dat, Encoding: Unknown +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1.cs new file mode 100644 index 0000000000000..b2c1d09a6fb8c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1.cs @@ -0,0 +1,48 @@ +// +using System; + +public class Example +{ + public static void Main() + { + Person p = new Person("John", "Doe"); + Console.WriteLine(p); + } +} + +public class Person +{ + static InfoModule infoModule; + + String fName; + String mName; + String lName; + + static Person() + { + infoModule = new InfoModule(DateTime.UtcNow); + } + + public Person(String fName, String lName) + { + this.fName = fName; + this.lName = lName; + infoModule.Increment(); + } + + public override String ToString() + { + return String.Format("{0} {1}", fName, lName); + } +} +// The example displays the following output if missing1a.dll is renamed or removed: +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'Person' threw an exception. ---> +// System.IO.FileNotFoundException: Could not load file or assembly +// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' +// or one of its dependencies. The system cannot find the file specified. +// at Person..cctor() +// --- End of inner exception stack trace --- +// at Person..ctor(String fName, String lName) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1a.cs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1a.cs new file mode 100644 index 0000000000000..56903779fbaac --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Missing1a.cs @@ -0,0 +1,24 @@ +// +using System; + +public class InfoModule +{ + private DateTime firstUse; + private int ctr = 0; + + public InfoModule(DateTime dat) + { + firstUse = dat; + } + + public int Increment() + { + return ++ctr; + } + + public DateTime GetInitializationTime() + { + return firstUse; + } +} +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs new file mode 100644 index 0000000000000..ce73d8fa914d4 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs @@ -0,0 +1,30 @@ +// +using System; +using System.Text.RegularExpressions; + +public class Example +{ + public static void Main() + { + AppDomain domain = AppDomain.CurrentDomain; + // Set a timeout interval of -2 seconds. + domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2)); + + Regex rgx = new Regex("[aeiouy]"); + Console.WriteLine("Regular expression pattern: {0}", rgx.ToString()); + Console.WriteLine("Timeout interval for this regex: {0} seconds", + rgx.MatchTimeout.TotalSeconds); + } +} +// The example displays the following output: +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> +// System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. +// Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or +// object for specifying a default matching timeout for System.Text.RegularExpressions.Regex. +// at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout() +// at System.Text.RegularExpressions.Regex..cctor() +// --- End of inner exception stack trace --- +// at System.Text.RegularExpressions.Regex..ctor(String pattern) +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/ctorException1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/ctorException1.cs new file mode 100644 index 0000000000000..f8b8e1b478adf --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/ctorException1.cs @@ -0,0 +1,33 @@ +// +using System; + +public class Example +{ + private static TestClass test = new TestClass(3); + + public static void Main() + { + Example ex = new Example(); + Console.WriteLine(test.Value); + } +} + +public class TestClass +{ + public readonly int Value; + + public TestClass(int value) + { + if (value < 0 || value > 1) throw new ArgumentOutOfRangeException(); + Value = value; + } +} +// The example displays the following output: +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'Example' threw an exception. ---> +// System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. +// at TestClass..ctor(Int32 value) +// at Example..cctor() +// --- End of inner exception stack trace --- +// at Example.Main() +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1.fs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1.fs new file mode 100644 index 0000000000000..97310086c979e --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1.fs @@ -0,0 +1,27 @@ +module Missing1 + +open Missing1a +// +open System + +type Person(fName, lName) = + static let infoModule = InfoModule DateTime.UtcNow + + do infoModule.Increment() |> ignore + + override _.ToString() = + $"{fName} {lName}" +let p = Person("John", "Doe") + +printfn $"{p}" +// The example displays the following output if missing1a.dll is renamed or removed: +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'Person' threw an exception. ---> +// System.IO.FileNotFoundException: Could not load file or assembly +// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' +// or one of its dependencies. The system cannot find the file specified. +// at Person..cctor() +// --- End of inner exception stack trace --- +// at Person..ctor(String fName, String lName) +// at Example.Main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1a.fs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1a.fs new file mode 100644 index 0000000000000..39c91e6d9e76f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Missing1a.fs @@ -0,0 +1,15 @@ +module Missing1a + +// +open System + +type InfoModule(firstUse: DateTime) = + let mutable ctr = 0 + + member _.Increment() = + ctr <- ctr + 1 + ctr + + member _.GetInitializationTime() = + firstUse +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Regex1.fs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Regex1.fs new file mode 100644 index 0000000000000..1e3fc8481a766 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/fsharp/Regex1.fs @@ -0,0 +1,23 @@ +// +open System +open System.Text.RegularExpressions + +let domain = AppDomain.CurrentDomain +// Set a timeout interval of -2 seconds. +domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds -2) + +let rgx = Regex "[aeiouy]" +printfn $"Regular expression pattern: {rgx}" +printfn $"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds" +// The example displays the following output: +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> +// System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. +// Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or +// object for specifying a default matching timeout for System.Text.RegularExpressions.Regex. +// at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout() +// at System.Text.RegularExpressions.Regex..cctor() +// --- End of inner exception stack trace --- +// at System.Text.RegularExpressions.Regex..ctor(String pattern) +// at Example.Main() +// \ No newline at end of file diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/CtorException1.vb b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/CtorException1.vb new file mode 100644 index 0000000000000..3a3bebcf579fa --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/CtorException1.vb @@ -0,0 +1,31 @@ +' Visual Basic .NET Document +Option Strict On + +' +Public Class Example + Shared test As New TestClass(3) + + Public Shared Sub Main() + Dim ex As New Example() + Console.WriteLine(test.Value) + End Sub +End Class + +Public Class TestClass + Public ReadOnly Value As Integer + + Public Sub New(value As Integer) + If value < 0 Or value > 1 Then Throw New ArgumentOutOfRangeException() + Value = value + End Sub +End Class +' The example displays the following output: +' Unhandled Exception: System.TypeInitializationException: +' The type initializer for 'Example' threw an exception. ---> +' System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. +' at TestClass..ctor(Int32 value) +' at Example..cctor() +' --- End of inner exception stack trace --- +' at Example.Main() +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/GettingVersions1.vb b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/GettingVersions1.vb new file mode 100644 index 0000000000000..08ffbc670d070 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/GettingVersions1.vb @@ -0,0 +1,64 @@ +' Visual Basic .NET Document +Option Strict On + +Imports System.Reflection + + +Module modMain + + Public Sub Main() + GetOsVersion() + Console.WriteLine() + GetClrVersion() + Console.WriteLine() + GetSpecificAssemblyVersion() + Console.WriteLine() + Example1.GetExecutingAssemblyVersion() + Console.WriteLine() + GetApplicationVersion() + End Sub + + Private Sub GetOsVersion() + ' + ' Get the operating system version. + Dim os As OperatingSystem = Environment.OSVersion + Dim ver As Version = os.Version + Console.WriteLine("Operating System: {0} ({1})", os.VersionString, ver.ToString()) + ' + End Sub + + Private Sub GetClrVersion() + ' + ' Get the common language runtime version. + Dim ver As Version = Environment.Version + Console.WriteLine("CLR Version {0}", ver.ToString()) + ' + End Sub + + Private Sub GetSpecificAssemblyVersion() + ' Get the version of a specific assembly. + Dim filename As String = ".\StringLibrary.dll" + Dim assem As Assembly = Assembly.ReflectionOnlyLoadFrom(filename) + Dim assemName As AssemblyName = assem.GetName() + Dim ver As Version = assemName.Version + Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString()) + End Sub + + Private Sub GetApplicationVersion() + ' Get the version of the executing assembly (that is, this assembly). + Dim assem As Assembly = Assembly.GetEntryAssembly() + Dim assemName As AssemblyName = assem.GetName() + Dim ver As Version = assemName.Version + Console.WriteLine("Application {0}, Version {1}", assemName.Name, ver.ToString()) + End Sub +End Module + +Public Module Example1 + Public Sub GetExecutingAssemblyVersion() + ' Get the version of the current assembly. + Dim assem As Assembly = Assembly.GetExecutingAssembly() + Dim assemName As AssemblyName = assem.GetName() + Dim ver As Version = assemName.Version + Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString()) + End Sub +End Module diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1.vb b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1.vb new file mode 100644 index 0000000000000..311b7c811c391 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1.vb @@ -0,0 +1,43 @@ +' Visual Basic .NET Document +Option Strict On + +' +Module Example + Public Sub Main() + Dim p As New Person("John", "Doe") + Console.WriteLine(p) + End Sub +End Module + +Public Class Person + Shared infoModule As InfoModule + + Dim fName As String + Dim mName As String + Dim lName As String + + Shared Sub New() + infoModule = New InfoModule(DateTime.UtcNow) + End Sub + + Public Sub New(fName As String, lName As String) + Me.fName = fName + Me.lName = lName + infoModule.Increment() + End Sub + + Public Overrides Function ToString() As String + Return String.Format("{0} {1}", fName, lName) + End Function +End Class +' The example displays the following output if missing1a.dll is renamed or removed: +' Unhandled Exception: System.TypeInitializationException: +' The type initializer for 'Person' threw an exception. ---> +' System.IO.FileNotFoundException: Could not load file or assembly +' 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' +' or one of its dependencies. The system cannot find the file specified. +' at Person..cctor() +' --- End of inner exception stack trace --- +' at Person..ctor(String fName, String lName) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1a.vb b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1a.vb new file mode 100644 index 0000000000000..1ee7064e804bf --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Missing1a.vb @@ -0,0 +1,23 @@ +' Visual Basic .NET Document +Option Strict On + +' +Public Class InfoModule + Private firstUse As DateTime + Private ctr As Integer = 0 + + Public Sub New(dat As DateTime) + firstUse = dat + End Sub + + Public Function Increment() As Integer + ctr += 1 + Return ctr + End Function + + Public Function GetInitializationTime() As DateTime + Return firstUse + End Function +End Class +' + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Regex1.vb b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Regex1.vb new file mode 100644 index 0000000000000..e83903eedb891 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/Regex1.vb @@ -0,0 +1,30 @@ +' Visual Basic .NET Document +Option Strict On + +' +Imports System.Text.RegularExpressions + +Module Example + Public Sub Main() + Dim domain As AppDomain = AppDomain.CurrentDomain + ' Set a timeout interval of -2 seconds. + domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2)) + + Dim rgx As New Regex("[aeiouy]") + Console.WriteLine("Regular expression pattern: {0}", rgx.ToString()) + Console.WriteLine("Timeout interval for this regex: {0} seconds", + rgx.MatchTimeout.TotalSeconds) + End Sub +End Module +' The example displays the following output: +' Unhandled Exception: System.TypeInitializationException: +' The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> +' System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. +' Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or +' object for specifying a default matching timeout for System.Text.RegularExpressions.Regex. +' at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout() +' at System.Text.RegularExpressions.Regex..cctor() +' --- End of inner exception stack trace --- +' at System.Text.RegularExpressions.Regex..ctor(String pattern) +' at Example.Main() +' diff --git a/docs/fundamentals/runtime-libraries/system-accessviolationexception.md b/docs/fundamentals/runtime-libraries/system-accessviolationexception.md new file mode 100644 index 0000000000000..6b3d7f80e283f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-accessviolationexception.md @@ -0,0 +1,29 @@ +--- +title: System.AccessViolationException class +description: Learn about the System.AccessViolationException class. +ms.date: 12/31/2023 +--- +# System.AccessViolationException class + +An access violation occurs in unmanaged or unsafe code when the code attempts to read or write to memory that has not been allocated, or to which it does not have access. This usually occurs because a pointer has a bad value. Not all reads or writes through bad pointers lead to access violations, so an access violation usually indicates that several reads or writes have occurred through bad pointers, and that memory might be corrupted. Thus, access violations almost always indicate serious programming errors. An clearly identifies these serious errors. + +In programs consisting entirely of verifiable managed code, all references are either valid or null, and access violations are impossible. Any operation that attempts to reference a null reference in verifiable code throws a exception. An occurs only when verifiable managed code interacts with unmanaged code or with unsafe managed code. + +## Troubleshoot AccessViolationException exceptions + +An exception can occur only in unsafe managed code or when verifiable managed code interacts with unmanaged code: + +- An access violation that occurs in unsafe managed code can be expressed as either a exception or an exception, depending on the platform. +- An access violation in unmanaged code that bubbles up to managed code is always wrapped in an exception. + +In either case, you can identify and correct the cause of the exception as follows: + +- Make sure that the memory that you're attempting to access has been allocated. An exception is always thrown by an attempt to access protected memory—that is, to access memory that's not allocated or that's not owned by a process. + + Automatic memory management is one of the services that the .NET runtime provides. If managed code provides the same functionality as your unmanaged code, you may wish to move to managed code to take advantage of this functionality. For more information, see [Automatic Memory Management](/dotnet/standard/automatic-memory-management). + +- Make sure that the memory that you're attempting to access has not been corrupted. If several read or write operations have occurred through bad pointers, memory might be corrupted. This typically occurs when reading or writing to addresses outside of a predefined buffer. + +## AccessViolationException and try/catch blocks + + exceptions thrown by the .NET runtime aren't handled by the `catch` statement in a structured exception handler if the exception occurs outside of the memory reserved by the runtime. To handle such an exception, apply the attribute to the method in which the exception is thrown. This change does not affect exceptions thrown by user code, which can continue to be caught by a `catch` statement. diff --git a/docs/fundamentals/runtime-libraries/system-exception.md b/docs/fundamentals/runtime-libraries/system-exception.md new file mode 100644 index 0000000000000..fd0427be7143d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-exception.md @@ -0,0 +1,224 @@ +--- +title: System.Exception class +description: Learn about the System.Exception class. +ms.date: 12/31/2023 +--- +# System.Exception class + +This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler. + +## Errors and exceptions + +Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them. + +- **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the method in the following example assumes that the `obj` argument must always be non-null. + + :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors1.cs" id="Snippet4"::: + :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors1.fs" id="Snippet4"::: + :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors1.vb" id="Snippet4"::: + + The exception that results when `obj` is `null` can be eliminated by modifying the source code to explicitly test for null before calling the override and then re-compiling. The following example contains the corrected source code that handles a `null` argument. + + :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors2.cs" interactive="try-dotnet" id="Snippet5"::: + :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors2.fs" id="Snippet5"::: + :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors2.vb" id="Snippet5"::: + + Instead of using exception handling for usage errors, you can use the method to identify usage errors in debug builds, and the method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code). + +- **Program errors.** A program error is a run-time error that cannot necessarily be avoided by writing bug-free code. + + In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the method to check whether the file exists and, if it does not, prompt the user whether they want to create it. + + In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a object or calling the method may throw a exception. In these cases, you should use exception handling to recover from the error. + +- **System failures.** A system failure is a run-time error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. + +## Try/catch blocks + +The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into `try` blocks and `catch` blocks. There can be one or more `catch` blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block. + +If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a `try` statement and is called a `try` block. Application code that handles exceptions thrown by a `try` block is placed within a `catch` statement and is called a `catch` block. Zero or more `catch` blocks are associated with a `try` block, and each `catch` block includes a type filter that determines the types of exceptions it handles. + +When an exception occurs in a `try` block, the system searches the associated `catch` blocks in the order they appear in application code, until it locates a `catch` block that handles the exception. A `catch` block handles an exception of type `T` if the type filter of the catch block specifies `T` or any type that `T` derives from. The system stops searching after it finds the first `catch` block that handles the exception. For this reason, in application code, a `catch` block that handles a type must be specified before a `catch` block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles `System.Exception` is specified last. + +If none of the `catch` blocks associated with the current `try` block handle the exception, and the current `try` block is nested within other `try` blocks in the current call, the `catch` blocks associated with the next enclosing `try` block are searched. If no `catch` block for the exception is found, the system searches previous nesting levels in the current call. If no `catch` block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a `catch` block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a `catch` block that handles the exception, the default exception handler handles it and the application terminates. + +### F# try..with expression + +F# does not use `catch` blocks. Instead, a raised exception is pattern matched using a single `with` block. As this is an expression, rather than a statement, all paths must return the same type. To learn more, see [The try...with Expression](../../fsharp/language-reference/exception-handling/the-try-with-expression.md). + +## Exception type features + +Exception types support the following features: + +- Human-readable text that describes the error. When an exception occurs, the runtime makes a text message available to inform the user of the nature of the error and to suggest action to resolve the problem. This text message is held in the property of the exception object. During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. If no error message argument is supplied to the constructor, the default error message is used. For more information, see the property. + +- The state of the call stack when the exception was thrown. The property carries a stack trace that can be used to determine where the error occurs in the code. The stack trace lists all the called methods and the line numbers in the source file where the calls are made. + +## Exception class properties + +The class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: , , , , , , , and . + +When a causal relationship exists between two or more exceptions, the property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the property. + +The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the class. For more information about localized resources, see the [Creating Satellite Assemblies](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps) and [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) topics. + +To provide the user with extensive information about why the exception occurred, the property can hold a URL (or URN) to a help file. + +The class uses the HRESULT `COR_E_EXCEPTION`, which has the value 0x80131500. + +For a list of initial property values for an instance of the class, see the constructors. + +## Performance considerations + +Throwing or handling an exception consumes a significant amount of system resources and execution time. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Instead, provide a retry mechanism so users can enter valid input. Nor should you use exceptions to handle usage errors. Instead, use [assertions](/visualstudio/debugger/assertions-in-managed-code) to identify and correct usage errors. + +In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing. + +## Re-throw an exception + +In many cases, an exception handler simply wants to pass the exception on to the caller. This most often occurs in: + +- A class library that in turn wraps calls to methods in the .NET class library or other class libraries. + +- An application or library that encounters a fatal exception. The exception handler can log the exception and then re-throw the exception. + +The recommended way to re-throw an exception is to simply use the [throw](/dotnet/csharp/language-reference/keywords/throw) statement in C#, the [reraise](../../fsharp/language-reference/exception-handling/the-raise-function.md#reraising-an-exception) function in F#, and the [Throw](../../visual-basic/language-reference/statements/throw-statement.md) statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, `FindOccurrences`, wraps one or more calls to without validating its arguments beforehand. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet6"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet6"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow1.vb" id="Snippet6"::: + +A caller then calls `FindOccurrences` twice. In the second call to `FindOccurrences`, the caller passes a `null` as the search string, which causes the method to throw an exception. This exception is handled by the `FindOccurrences` method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet7"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet7"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow1.vb" id="Snippet7"::: + +In contrast, if the exception is re-thrown by using this statement: + +```csharp +throw e; +``` + +```vb +Throw e +``` + +```fsharp +raise e +``` + +...then the full call stack is not preserved, and the example would generate the following output: + +```output +'a' occurs at the following character positions: 4, 7, 15 + +An exception (ArgumentNullException) occurred. +Message: + Value cannot be null. +Parameter name: value + +Stack Trace: + at Library.FindOccurrences(String s, String f) + at Example.Main() +``` + +A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. The caller can then use the new exception's property to retrieve stack frame and other information about the original exception. In this case, the throw statement is: + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow3.cs" id="Snippet8"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow3.fs" id="Snippet8"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow3.vb" id="Snippet8"::: + +The user code that handles the exception has to know that the property contains information about the original exception, as the following exception handler illustrates. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow3.cs" id="Snippet9"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow3.fs" id="Snippet9"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow3.vb" id="Snippet9"::: + +## Choose standard exceptions + +When you have to throw an exception, you can often use an existing exception type in .NET instead of implementing a custom exception. You should use a standard exception type under these two conditions: + +- You're throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Typically, you would throw an exception such as , , , or . The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the property. + +- You're handling an error that can be communicated to the caller with an existing .NET exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an (the most derived class) rather than an . + +The following table lists common exception types and the conditions under which you would throw them. + +|Exception|Condition| +|---------------|---------------| +||A non-null argument that is passed to a method is invalid.| +||An argument that is passed to a method is `null`.| +||An argument is outside the range of valid values.| +||Part of a directory path is not valid.| +||The denominator in an integer or division operation is zero.| +||A drive is unavailable or does not exist.| +||A file does not exist.| +||A value is not in an appropriate format to be converted from a string by a conversion method such as `Parse`.| +||An index is outside the bounds of an array or collection.| +||A method call is invalid in an object's current state.| +||The specified key for accessing a member in a collection cannot be found.| +||A method or operation is not implemented.| +||A method or operation is not supported.| +||An operation is performed on an object that has been disposed.| +||An arithmetic, casting, or conversion operation results in an overflow.| +||A path or file name exceeds the maximum system-defined length.| +||The operation is not supported on the current platform.| +||An array with the wrong number of dimensions is passed to a method.| +||The time interval allotted to an operation has expired.| +||An invalid Uniform Resource Identifier (URI) is used.| + +## Implement custom exceptions + +In the following cases, using an existing .NET exception to handle an error condition is not adequate: + +- When the exception reflects a unique program error that cannot be mapped to an existing .NET exception. + +- When the exception requires handling that is different from the handling that is appropriate for an existing .NET exception, or the exception must be disambiguated from a similar exception. For example, if you throw an exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method. + +The class is the base class of all exceptions in .NET. Many derived classes rely on the inherited behavior of the members of the class; they do not override the members of , nor do they define any unique members. + +To define your own exception class: + +1. Define a class that inherits from . If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the class includes a property that specifies the name of the parameter whose argument caused the exception, and the property includes a property that indicates the time-out interval. + +2. If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of do not override the behavior of inherited members. + +3. Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the attribute. + +4. Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors: + + - , which uses default values to initialize the properties of a new exception object. + + - , which initializes a new exception object with a specified error message. + + - , which initializes a new exception object with a specified error message and inner exception. + + - , which is a `protected` constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable. + +The following example illustrates the use of a custom exception class. It defines a `NotPrimeException` exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, `NonPrime`, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with and parameters for serialization, the `NotPrimeException` class defines three additional constructors to support the `NonPrime` property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The `NotPrimeException` class is also marked with the attribute. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/notprimeexception.cs" id="Snippet1"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/notprimeexception.fs" id="Snippet1"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/notprimeexception.vb" id="Snippet1"::: + +The `PrimeNumberGenerator` class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. The `GetPrimesFrom` method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a `NotPrimeException` if that lower limit is not a prime number. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/primenumbergenerator.cs" id="Snippet2"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs" id="Snippet2"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/primenumbergenerator.vb" id="Snippet2"::: + +The following example makes two calls to the `GetPrimesFrom` method with non-prime numbers, one of which crosses application domain boundaries. In both cases, the exception is thrown and successfully handled in client code. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/example.cs" id="Snippet3"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/example.fs" id="Snippet3"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/example.vb" id="Snippet3"::: + +## Examples + +The following example demonstrates a `catch` (`with` in F#) block that is defined to handle errors. This `catch` block also catches errors, because derives from and there is no `catch` block explicitly defined for errors. + +:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/catchexception.cs" interactive="try-dotnet" id="Snippet1"::: +:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/catchexception.fs" id="Snippet1"::: +:::code language="vb" source="./snippets/System/Exception/Overview/vb/catchexception.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-invalidcastexception.md b/docs/fundamentals/runtime-libraries/system-invalidcastexception.md new file mode 100644 index 0000000000000..4299776af72d3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-invalidcastexception.md @@ -0,0 +1,102 @@ +--- +title: System.InvalidCastException class +description: Learn about the System.InvalidCastException class. +ms.date: 12/31/2023 +--- +# System.InvalidCastException class + +.NET supports automatic conversion from derived types to their base types and back to the derived type, as well as from types that present interfaces to interface objects and back. It also includes a variety of mechanisms that support custom conversions. For more information, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md). + +An exception is thrown when the conversion of an instance of one type to another type is not supported. For example, attempting to convert a value to a value throws an exception. It differs from an exception, which is thrown when a conversion of one type to another is supported, but the value of the source type is outside the range of the target type. An exception is caused by developer error and should not be handled in a `try/catch` block. Instead, the cause of the exception should be eliminated. + +For information about conversions supported by the system, see the class. For errors that occur when the destination type can store source type values but is not large enough to store a specific source value, see the exception. + +> [!NOTE] +> In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error. + +Some of the conditions under which an attempted conversion throws an exception are discussed in the following sections. + +For an explicit reference conversion to be successful, the source value must be `null`, or the object type referenced by the source argument must be convertible to the destination type by an implicit reference conversion. + +The following intermediate language (IL) instructions throw an exception: + +- `castclass` +- `refanyval` +- `unbox` + + uses the HRESULT `COR_E_INVALIDCAST`, which has the value 0x80004002. + +For a list of initial property values for an instance of , see the constructors. + +## Primitive types and IConvertible + +You directly or indirectly call a primitive type's implementation that does not support a particular conversion. For example, trying to convert a value to a or a value to an throws an exception. The following example calls both the and methods to convert a value to a . In both cases, the method call throws an exception. + +:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/iconvertible1.cs" interactive="try-dotnet" id="Snippet2"::: +:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs" id="Snippet2"::: +:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb" id="Snippet2"::: + +Because the conversion is not supported, there is no workaround. + +## The Convert.ChangeType method + +You've called the method to convert an object from one type to another, but one or both types don't implement the interface. + +In most cases, because the conversion is not supported, there is no workaround. In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type. + +## Narrowing conversions and IConvertible implementations + +Narrowing operators define the explicit conversions supported by a type. A casting operator in C# or the `CType` conversion method in Visual Basic (if `Option Strict` is on) is required to perform the conversion. + +However, if neither the source type nor the target type defines an explicit or narrowing conversion between the two types, and the implementation of one or both types doesn't support a conversion from the source type to the target type, an exception is thrown. + +In most cases, because the conversion is not supported, there is no workaround. + +## Downcasting + +You're downcasting, that is, trying to convert an instance of a base type to one of its derived types. In the following example, trying to convert a `Person` object to a `PersonWithID` object fails. + +:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/basetoderived1.cs" interactive="try-dotnet" id="Snippet1"::: +:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs" id="Snippet1"::: +:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb" id="Snippet1"::: + +As the example shows, the downcast succeeds only if the `Person` object was created by an upcast from a `PersonWithId` object to a `Person` object, or if the `Person` object is `null`. + +## Conversion from an interface object + +You're attempting to convert an interface object to a type that implements that interface, but the target type is not the same type or a base class of the type from which the interface object was originally derived. The following example throws an exception when it attempts to convert an object to a object. The conversion fails because although the class implements the interface, the object is not related to the class from which the interface object was derived. + +:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/Interface1.cs" id="Snippet3"::: +:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs" id="Snippet3"::: +:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/Interface1.vb" id="Snippet3"::: + +As the exception message indicates, the conversion would succeed only if the interface object is converted back to an instance of the original type, in this case a . The conversion would also succeed if the interface object is converted to an instance of a base type of the original type. + +## String conversions + +You're trying to convert a value or an object to its string representation by using a casting operator in C#. In the following example, both the attempt to cast a value to a string and the attempt to cast an integer to a string throw an exception. + +:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/ToString1.cs" id="Snippet4"::: +:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs" id="Snippet4"::: + +> [!NOTE] +> Using the Visual Basic `CStr` operator to convert a value of a primitive type to a string succeeds. The operation does not throw an exception. + +To successfully convert an instance of any type to its string representation, call its `ToString` method, as the following example does. The `ToString` method is always present, since the method is defined by the class and therefore is either inherited or overridden by all managed types. + +:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/ToString2.cs" interactive="try-dotnet" id="Snippet5"::: +:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs" id="Snippet5"::: + +## Visual Basic 6.0 migration + +You're upgrading a Visual Basic 6.0 application with a call to a custom event in a user control to Visual Basic .NET, and an exception is thrown with the message, "Specified cast is not valid." To eliminate this exception, change the line of code in your form (such as `Form1`) + +```vb +Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5)) +``` + +and replace it with the following line of code: + +```vb +Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5)) +``` diff --git a/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md b/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md new file mode 100644 index 0000000000000..64f10797a8517 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md @@ -0,0 +1,257 @@ +--- +title: System.InvalidOperationException class +description: Learn about the System.InvalidOperationException class. +ms.date: 12/31/2023 +--- +# System.InvalidOperationException class + + is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it's thrown when the state of an object cannot support the method call. For example, an exception is thrown by methods such as: + +- if objects of a collection are modified after the enumerator is created. For more information, see [Changing a collection while iterating it](#changing-a-collection-while-iterating-it). +- if the resource set is closed before the method call is made. +- , if the object or objects to be added would result in an incorrectly structured XML document. +- A method that attempts to manipulate the UI from a thread that is not the main or UI thread. + +> [!IMPORTANT] +> Because the exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the property. + + uses the HRESULT `COR_E_INVALIDOPERATION`, which has the value 0x80131509. + +For a list of initial property values for an instance of , see the constructors. + +## Common causes of InvalidOperationException exceptions + +The following sections show how some common cases in which in exception is thrown in an app. How you handle the issue depends on the specific situation. Most commonly, however, the exception results from developer error, and the exception can be anticipated and avoided. + +### Updating a UI thread from a non-UI thread + +Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. However. most GUI (graphical user interface) application frameworks for .NET, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). An is thrown when you try to access a UI element from a thread other than the UI thread. The text of the exception message is shown in the following table. + +|Application Type|Message| +|----------------------|-------------| +|WPF app|**The calling thread cannot access this object because a different thread owns it.**| +|UWP app|**The application called an interface that was marshaled for a different thread.**| +|Windows Forms app|**Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.**| + +UI frameworks for .NET implement a *dispatcher* pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread: + +- In WPF apps, call the method to determine if a method is running on a non-UI thread. It returns `true` if the method is running on the UI thread and `false` otherwise. Call one of the overloads of the method to schedule the call on the UI thread. +- In UWP apps, check the property to determine if a method is running on a non-UI thread. Call the method to execute a delegate that updates the UI thread. +- In Windows Forms apps, use the property to determine if a method is running on a non-UI thread. Call one of the overloads of the method to execute a delegate that updates the UI thread. + +The following examples illustrate the exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Each example requires that you create two controls: + +- A text box control named `textBox1`. In a Windows Forms app, you should set its property to `true`. +- A button control named `threadExampleBtn`. The example provides a handler, `ThreadsExampleBtn_Click`, for the button's `Click` event. + +In each case, the `threadExampleBtn_Click` event handler calls the `DoSomeWork` method twice. The first call runs synchronously and succeeds. But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. This results in a exception. + +#### WPF and UWP apps + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WPF1/MainWindow.xaml.cs" id="Snippet1"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/MainWindow.xaml.vb" id="Snippet1"::: + +The following version of the `DoSomeWork` method eliminates the exception in a WPF app. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WPF2/MainWindowDispatcher.xaml.cs" id="Snippet3"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/MainWindowDispatcher.xaml.vb" id="Snippet3"::: + +The following version of the `DoSomeWork` method eliminates the exception in a UWP app. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml.cs" id="Snippet4"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/MainPage.xaml.vb" id="Snippet4"::: + +#### Windows Forms apps + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form1.cs" id="Snippet2"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Form1.vb" id="Snippet2"::: + +The following version of the `DoSomeWork` method eliminates the exception in a Windows Forms app. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form11.cs" id="Snippet5"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Form11.vb" id="Snippet5"::: + +### Changing a collection while iterating it + +The `foreach` statement in C#, `for...in` in F#, or `For Each` statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. However, it can't be used to add or remove items from the collection. Doing this throws an exception with a message that is similar to, "**Collection was modified; enumeration operation may not execute.**" + +The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an with the first call to the method. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Iterating1.cs" id="Snippet1"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs" id="Snippet1"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Iterating1.vb" id="Snippet1"::: + +You can eliminate the exception in one of two ways, depending on your application logic: + +- If elements must be added to the collection while iterating it, you can iterate it by index using the `for` (`for..to` in F#) statement instead of `foreach`, `for...in`, or `For Each`. The following example uses the for statement to add the square of numbers in the collection to the collection. + + :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Iterating2.cs" interactive="try-dotnet" id="Snippet2"::: + :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs" id="Snippet2"::: + :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Iterating2.vb" id="Snippet2"::: + + Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropriately, by iterating backward, from `Count` - 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. Otherwise, if an element is added to the collection on every iteration, an endless loop results. + +- If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object. + + :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Iterating3.cs" interactive="try-dotnet" id="Snippet3"::: + :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs" id="Snippet3"::: + :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Iterating3.vb" id="Snippet3"::: + +### Sorting an array or collection whose objects cannot be compared + +General-purpose sorting methods, such as the method or the method, usually require that at least one of the objects to be sorted implement the or the interface. If not, the collection or array cannot be sorted, and the method throws an exception. The following example defines a `Person` class, stores two `Person` objects in a generic object, and attempts to sort them. As the output from the example shows, the call to the method throws an . + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/List_Sort1.cs" id="Snippet12"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs" id="Snippet12"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/List_Sort1.vb" id="Snippet12"::: + +You can eliminate the exception in any of three ways: + +- If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the or the interface. This requires that you implement either the or the method. Adding an interface implementation to an existing type is not a breaking change. + + The following example uses this approach to provide an implementation for the `Person` class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully. + + :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/List_Sort2.cs" interactive="try-dotnet" id="Snippet13"::: + :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs" id="Snippet13"::: + :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/List_Sort2.vb" id="Snippet13"::: + +- If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the interface. You can call an overload of the `Sort` method that includes an parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria. + + The following example uses the approach by developing a custom `PersonComparer` class that is used to sort `Person` collections. It then passes an instance of this class to the method. + + :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/List_Sort3.cs" interactive="try-dotnet" id="Snippet14"::: + :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs" id="Snippet14"::: + :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/List_Sort3.vb" id="Snippet14"::: + +- If you cannot modify the source code for the type you are trying to sort, you can create a delegate to perform the sorting. The delegate signature is + + ```vb + Function Comparison(Of T)(x As T, y As T) As Integer + ``` + + ```csharp + int Comparison(T x, T y) + ``` + + The following example uses the approach by defining a `PersonComparison` method that matches the delegate signature. It then passes this delegate to the method. + + :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/List_Sort4.cs" interactive="try-dotnet" id="Snippet15"::: + :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs" id="Snippet15"::: + :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/List_Sort4.vb" id="Snippet15"::: + +### Casting a Nullable\ that's null to its underlying type + +Attempting to cast a value that is `null` to its underlying type throws an exception and displays the error message, "**Nullable object must have a value.** + +The following example throws an exception when it attempts to iterate an array that includes a `Nullable(Of Integer)` value. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Nullable1.cs" id="Snippet4"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs" id="Snippet4"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Nullable1.vb" id="Snippet4"::: + +To prevent the exception: + +- Use the property to select only those elements that are not `null`. +- Call one of the overloads to provide a default value for a `null` value. + +The following example does both to avoid the exception. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Nullable2.cs" interactive="try-dotnet" id="Snippet5"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs" id="Snippet5"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Nullable2.vb" id="Snippet5"::: + +### Call a System.Linq.Enumerable method on an empty collection + +The , , , , , , , and methods perform operations on a sequence and return a single result. Some overloads of these methods throw an exception when the sequence is empty, while other overloads return `null`. The method also throws an exception when the sequence contains more than one element. + +> [!NOTE] +> Most of the methods that throw an exception are overloads. Be sure that you understand the behavior of the overload that you choose. + +The following table lists the exception messages from the exception objects thrown by calls to some methods. + +|Method|Message| +|------------|-------------| +|`Aggregate`
`Average`
`Last`
`Max`
`Min`|**Sequence contains no elements**| +|`First`|**Sequence contains no matching element**| +|`Single`
`SingleOrDefault`|**Sequence contains more than one matching element**| + +How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call. + +- When you deliberately call one of these methods without checking for an empty sequence, you are assuming that the sequence is not empty, and that an empty sequence is an unexpected occurrence. In this case, catching or rethrowing the exception is appropriate. + +- If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the overload to determine whether a sequence contains any elements. + + > [!TIP] + > Calling the method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive. + +- If you've called a method such as , , or , you can substitute an alternate method, such as , , or , that returns a default value instead of a member of the sequence. + +The examples provide additional detail. + +The following example uses the method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an exception. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable1.cs" id="Snippet6"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs" id="Snippet6"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable1.vb" id="Snippet6"::: + +The exception can be eliminated by calling the method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable2.cs" interactive="try-dotnet" id="Snippet7"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs" id="Snippet7"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable2.vb" id="Snippet7"::: + +The method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an exception. + +In the following example, the method throws an exception because the dbQueryResults array doesn't contain an element greater than 4. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable3.cs" id="Snippet8"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs" id="Snippet8"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable3.vb" id="Snippet8"::: + +You can call the method instead of to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is `null` for a reference type, zero for a numeric data type, and for the type. + +> [!NOTE] +> Interpreting the value returned by the method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the method to determine whether the sequence has valid members before calling the method. + +The following example calls the method to prevent the exception thrown in the previous example. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable4.cs" interactive="try-dotnet" id="Snippet9"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs" id="Snippet9"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable4.vb" id="Snippet9"::: + +### Call Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element + +The method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an exception. + +You can use the method to return a default value instead of throwing an exception when the sequence contains no elements. However, the method still throws an exception when the sequence contains more than one element. + +The following table lists the exception messages from the exception objects thrown by calls to the and methods. + +| Method | Message | +|-----------------------------------|------------------------------------------------------| +| `Single` | **Sequence contains no matching element** | +| `Single`
`SingleOrDefault` | **Sequence contains more than one matching element** | + +In the following example, the call to the method throws an exception because the sequence doesn't have an element greater than 4. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable5.cs" id="Snippet10"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs" id="Snippet10"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable5.vb" id="Snippet10"::: + +The following example attempts to prevent the exception thrown when a sequence is empty by instead calling the method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an exception. + +:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Enumerable6.cs" id="Snippet11"::: +:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs" id="Snippet11"::: +:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Enumerable6.vb" id="Snippet11"::: + +Calling the method assumes that either a sequence or the sequence that meets specified criteria contains only one element. assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other method, such as or . + +### Dynamic cross-application domain field access + +The Microsoft intermediate language (MSIL) instruction throws an exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. The address of a field can only be accessed from the application domain in which it resides. + +## Throw an InvalidOperationException exception + +You should throw an exception only when the state of your object for some reason does not support a particular method call. That is, the method call is valid in some circumstances or contexts, but is invalid in others. + +If the method invocation failure is due to invalid arguments, then or one of its derived classes, or , should be thrown instead. diff --git a/docs/fundamentals/runtime-libraries/system-notimplementedexception.md b/docs/fundamentals/runtime-libraries/system-notimplementedexception.md new file mode 100644 index 0000000000000..051a5af6ba97f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-notimplementedexception.md @@ -0,0 +1,26 @@ + class + +The exception is thrown when a particular method, get accessor, or set accessor is present as a member of a type but is not implemented. + + uses the default implementation, which supports reference equality. For a list of initial values for an instance of , see the constructors. + +## Throw the exception + +You might choose to throw a exception in properties or methods in your own types when the that member is still in development and will only later be implemented in production code. In other words, a exception should be synonymous with "still in development." + +## Handle the exception + +The exception indicates that the method or property that you are attempting to invoke has no implementation and therefore provides no functionality. As a result, you should not handle this error in a `try/catch` block. Instead, you should remove the member invocation from your code. You can include a call to the member when it is implemented in the production version of a library. + +In some cases, a exception may not be used to indicate functionality that is still in development in a pre-production library. However, this still indicates that the functionality is unavailable, and you should remove the member invocation from your code. + +## NotImplementedException and other exception types + +.NET also includes two other exception types, and , that indicate that no implementation exists for a particular member of a type. You should throw one of these instead of a exception under the following conditions: + +- Throw a exception on platforms on which the functionality is not supported if you've designed a type with one or more members that are available on some platforms or versions but not others. +- Throw a exception if the implementation of an interface member or an override to an abstract base class method is not possible. + + For example, the method throws a exception because no meaningful conversion between a date and time and a 32-bit signed integer exists. The method must be present in this case because the class implements the interface. + +You should also throw a exception if you've implemented an abstract base class and add a new member to it that must be overridden by derived classes. In that case, making the member abstract causes existing subclasses to fail to load. diff --git a/docs/fundamentals/runtime-libraries/system-notsupportedexception.md b/docs/fundamentals/runtime-libraries/system-notsupportedexception.md new file mode 100644 index 0000000000000..94713d66a6201 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-notsupportedexception.md @@ -0,0 +1,91 @@ +--- +title: System.NotSupportedException class +description: Learn about the System.NotSupportedException class. +ms.date: 12/31/2023 +--- +# System.NotSupportedException class + + indicates that no implementation exists for an invoked method or property. + + uses the HRESULT `COR_E_NOTSUPPORTED`, which has the value 0x80131515. + +For a list of initial property values for an instance of , see the constructors. + +## Throw a NotSupportedException exception + +You might consider throwing a exception in the following cases: + +- You're implementing a general-purpose interface, and number of the methods have no meaningful implementation. For example, if you are creating a date and time type that implements the interface, you would throw a exception for most of the conversions. + +- You've inherited from an abstract class that requires that you override a number of methods. However, you're only prepared to provide an implementation for a subset of these. For the methods that you decide not to implement, you can choose to throw a . + +- You're defining a general-purpose type with a state that enables operations conditionally. For example, your type can be either read-only or read-write. In that case: + + - If the object is read-only, attempting to assign values to the properties of an instance or call methods that modify instance state should throw a exception. + + - You should implement a property that returns a value that indicates whether particular functionality is available. For example, for a type that can be either read-only or read-write, you could implement a `IsReadOnly` property that indicates whether the set of read-write methods are available or unavailable. + +## Handle a NotSupportedException exception + +The exception indicates that a method has no implementation and that you should not call it. You should not handle the exception. Instead, what you should do depends on the cause of the exception: whether an implementation is completely absent, or the member invocation is inconsistent with the purpose of an object (such as a call to the method on a read-only object). + +**An implementation has not been provided because the operation cannot be performed in a meaningful way.** +This is a common exception when you are calling methods on an object that provides implementations for the methods of an abstract base class, or that implements a general-purpose interface, and the method has no meaningful implementation. + +For example, the class implements the interface, which means that it must include a method to convert every primitive type to every other primitive type. Many of those conversions, however, are not possible. As a result, a call to the method, for instance, throws a exception because there is no possible conversion between a and a value + +To eliminate the exception, you should eliminate the method call. + +**The method call is not supported given the state of the object.** +You're attempting to invoke a member whose functionality is unavailable because of the object's state. You can eliminate the exception in one of three ways: + +- You know the state of the object in advance, but you've invoked an unsupported method or property. In this case, the member invocation is an error, and you can eliminate it. + +- You know the state of the object in advance (usually because your code has instantiated it), but the object is mis-configured. The following example illustrates this issue. It creates a read-only object and then attempts to write to it. + + :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/BadState1.cs" id="Snippet1"::: + :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs" id="Snippet1"::: + :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/BadState1.vb" id="Snippet1"::: + + You can eliminate the exception by ensuring that the instantiated object supports the functionality you intend. The following example addresses the problem of the read-only object by providing the correct arguments to the constructor. + +- You don't know the state of the object in advance, and the object doesn't support a particular operation. In most cases, the object should include a property or method that indicates whether it supports a particular set of operations. You can eliminate the exception by checking the value of the object and invoking the member only if appropriate. + + The following example defines a `DetectEncoding` method that throws a exception when it attempts to read from the beginning of a stream that does not support read access. + + :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs" id="Snippet3"::: + :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs" id="Snippet3"::: + :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/TestProp1.vb" id="Snippet3"::: + + You can eliminate the exception by examining the value of the property and exiting the method if the stream is read-only. + + :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs" id="Snippet4"::: + :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs" id="Snippet4"::: + :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/TestProp2.vb" id="Snippet4"::: + +## Related exception types + +The exception is closely related to two other exception types; + +- + + This exception is thrown when a method could be implemented but is not, either because the member will be implemented in a later version, the member is not available on a particular platform, or the member belongs to an abstract class and a derived class must provide an implementation. + +- + + This exception is thrown in scenarios in which it is generally sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed. + +## .NET Compact Framework notes + +When working with the .NET Compact Framework and using P/Invoke on a native function, this exception may be thrown if: + +- The declaration in managed code is incorrect. +- The .NET Compact Framework does not support what you are trying to do. +- The DLL names are mangled on export. + +If a exception is thrown, check: + +- For any violations of the .NET Compact Framework P/Invoke restrictions. +- For any arguments that require pre-allocated memory. If these exist, you should pass a reference to an existing variable. +- That the names of the exported functions are correct. This can be verified with [DumpBin.exe](/cpp/build/reference/dumpbin-reference). +- That you are not attempting to pass too many arguments. diff --git a/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md b/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md new file mode 100644 index 0000000000000..7518debd8d86d --- /dev/null +++ b/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md @@ -0,0 +1,111 @@ +--- +title: System.TypeInitializationException class +description: Learn about the System.TypeInitializationException class. +ms.date: 12/31/2023 +--- +# System.TypeInitializationException class + +When a class initializer fails to initialize a type, a is created and passed a reference to the exception thrown by the type's class initializer. The property of holds the underlying exception. + +Typically, the exception reflects a catastrophic condition (the runtime is unable to instantiate a type) that prevents an application from continuing. Most commonly, the is thrown in response to some change in the executing environment of the application. Consequently, other than possibly for troubleshooting debug code, the exception should not be handled in a `try`/`catch` block. Instead, the cause of the exception should be investigated and eliminated. + + uses the HRESULT `COR_E_TYPEINITIALIZATION`, which has the value 0x80131534. + +For a list of initial property values for an instance of , see the constructors. + +The following sections describe some of the situations in which a exception is thrown. + +## Static constructors + +A static constructor, if one exists, is called automatically by the runtime before creating a new instance of a type. Static constructors can be explicitly defined by a developer. If a static constructor is not explicitly defined, compilers automatically create one to initialize any `static` (in C# or F#) or `Shared` (in Visual Basic) members of the type. For more information on static constructors, see [Static Constructors](../../csharp/programming-guide/classes-and-structs/static-constructors.md). + +Most commonly, a exception is thrown when a static constructor is unable to instantiate a type. The property indicates why the static constructor was unable to instantiate the type. Some of the more common causes of a exception are: + +- An unhandled exception in a static constructor + + If an exception is thrown in a static constructor, that exception is wrapped in a exception, and the type cannot be instantiated. + + What often makes this exception difficult to troubleshoot is that static constructors are not always explicitly defined in source code. A static constructor exists in a type if: + + - It has been explicitly defined as a member of a type. + + - The type has `static` (in C# or F#) or `Shared` (in Visual Basic) variables that are declared and initialized in a single statement. In this case, the language compiler generates a static constructor for the type. You can inspect it by using a utility such as [IL Disassembler](../../framework/tools/ildasm-exe-il-disassembler.md). For instance, when the C# and VB compilers compile the following example, they generate the IL for a static constructor that is similar to this: + + ```il + .method private specialname rtspecialname static + void .cctor() cil managed + { + // Code size 12 (0xc) + .maxstack 8 + IL_0000: ldc.i4.3 + IL_0001: newobj instance void TestClass::.ctor(int32) + IL_0006: stsfld class TestClass Example::test + IL_000b: ret + } // end of method Example::.cctor + ``` + + The following example shows a exception thrown by a compiler-generated static constructor. The `Example` class includes a `static` (in C#) or `Shared` (in Visual Basic) field of type `TestClass` that is instantiated by passing a value of 3 to its class constructor. That value, however, is illegal; only values of 0 or 1 are permitted. As a result, the `TestClass` class constructor throws an . Since this exception is not handled, it is wrapped in a exception. + + :::code language="csharp" source="./snippets/System/TypeInitializationException/Overview/csharp/ctorException1.cs" id="Snippet3"::: + :::code language="vb" source="./snippets/System/TypeInitializationException/Overview/vb/CtorException1.vb" id="Snippet3"::: + + Note that the exception message displays information about the property. + +- A missing assembly or data file + + A common cause of a exception is that an assembly or data file that was present in an application's development and test environments is missing from its runtime environment. For example, you can compile the following example to an assembly named Missing1a.dll by using this command-line syntax: + + ```csharp + csc -t:library Missing1a.cs + ``` + + ```fsharp + fsc --target:library Missing1a.fs + ``` + + ```vb + vbc Missing1a.vb -t:library + ``` + + :::code language="csharp" source="./snippets/System/TypeInitializationException/Overview/csharp/Missing1a.cs" id="Snippet1"::: + :::code language="fsharp" source="./snippets/System/TypeInitializationException/Overview/fsharp/Missing1a.fs" id="Snippet1"::: + :::code language="vb" source="./snippets/System/TypeInitializationException/Overview/vb/Missing1a.vb" id="Snippet1"::: + + You can then compile the following example to an executable named Missing1.exe by including a reference to Missing1a.dll: + + ```csharp + csc Missing1.cs /r:Missing1a.dll + ``` + + ```vb + vbc Missing1.vb /r:Missing1a.dll + ``` + + However, if you rename, move, or delete Missing1a.dll and run the example, it throws a exception and displays the output shown in the example. Note that the exception message includes information about the property. In this case, the inner exception is a that is thrown because the runtime cannot find the dependent assembly. + + :::code language="csharp" source="./snippets/System/TypeInitializationException/Overview/csharp/Missing1.cs" id="Snippet2"::: + :::code language="fsharp" source="./snippets/System/TypeInitializationException/Overview/fsharp/Missing1.fs" id="Snippet2"::: + :::code language="vb" source="./snippets/System/TypeInitializationException/Overview/vb/Missing1.vb" id="Snippet2"::: + + > [!NOTE] + > In this example, a exception was thrown because an assembly could not be loaded. The exception can also be thrown if a static constructor attempts to open a data file, such as a configuration file, an XML file, or a file containing serialized data, that it cannot find. + +## Regular expression match timeout values + +You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. The timeout is defined by a specifying a value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the method. The time interval must be a valid object that is greater than zero and less than approximately 24 days. If these requirements are not met, the attempt to set the default timeout value throws an , which in turn is wrapped in a exception. + +The following example shows the that is thrown when the value assigned to the "REGEX_DEFAULT_MATCH_TIMEOUT" property is invalid. To eliminate the exception, set the"REGEX_DEFAULT_MATCH_TIMEOUT" property to a value that is greater than zero and less than approximately 24 days. + +:::code language="csharp" source="./snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs" id="Snippet4"::: +:::code language="fsharp" source="./snippets/System/TypeInitializationException/Overview/fsharp/Regex1.fs" id="Snippet4"::: +:::code language="vb" source="./snippets/System/TypeInitializationException/Overview/vb/Regex1.vb" id="Snippet4"::: + +## Calendars and cultural data + +If you attempt to instantiate a calendar but the runtime is unable to instantiate the object that corresponds to that calendar, it throws a exception. This exception can be thrown by the following calendar class constructors: + +- The parameterless constructor of the class. +- The parameterless constructor of the class. +- The parameterless constructor of the class. + +Since cultural data for these cultures should be available on all systems, you should rarely, if ever, encounter this exception. diff --git a/docs/fundamentals/toc.yml b/docs/fundamentals/toc.yml index 1c1f428943152..37f25fe80dc9a 100644 --- a/docs/fundamentals/toc.yml +++ b/docs/fundamentals/toc.yml @@ -1003,6 +1003,30 @@ items: href: ../core/extensions/caching.md - name: Channels href: ../core/extensions/channels.md + - name: Exception types + items: + - name: Supplemental API remarks + items: + - name: System.AccessViolationException class + href: runtime-libraries/system-accessviolationexception.md + - name: System.Exception class + href: runtime-libraries/system-exception.md + - name: System.InvalidCastException class + href: runtime-libraries/system-invalidcastexception.md + - name: System.InvalidOperationException class + href: runtime-libraries/system-invalidoperationexception.md + - name: System.NotImplementedException class + href: runtime-libraries/system-notimplementedexception.md + - name: System.NotSupportedException class + href: runtime-libraries/system-notsupportedexception.md + - name: System.TypeInitializationException class + href: runtime-libraries/system-typeinitializationexception.md + - name: Registry + items: + - name: Supplemental API remarks + items: + - name: Microsoft.Win32.Registry class + href: runtime-libraries/microsoft-win32-registry.md - name: Execution model items: - name: Common Language Runtime (CLR) From 974cbbc32d78c8e81a7724a7e86f6536b1f936e2 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Sun, 31 Dec 2023 20:32:28 -0800 Subject: [PATCH 02/10] add registry --- .../microsoft-win32-registry.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/fundamentals/runtime-libraries/microsoft-win32-registry.md diff --git a/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md b/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md new file mode 100644 index 0000000000000..a37c9732c29f6 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md @@ -0,0 +1,34 @@ +--- +title: Microsoft.Win32.Registry class +description: Learn about the Microsoft.Win32.Registry class. +ms.date: 12/31/2023 +--- +# The Microsoft.Win32.Registry class + +The class provides the set of standard root keys found in the registry on machines running Windows. The registry is a storage facility for information about applications, users, and default system settings. Applications can use the registry for storing information that needs to be preserved after the application is closed, and access that same information when the application is reloaded. For example, you can store color preferences, screen locations, or the size of a window. You can control this data for each user by storing the information in a different location in the registry. + +The base, or root, instances that are exposed by the `Registry` class delineate the basic storage mechanism for subkeys and values in the registry. All keys are read-only because the registry depends on their existence. The keys exposed by `Registry` are: + +| Key | Description | +|-------------------------------------------------|--------------------------------------------------------------------| +| | Stores information about user preferences. | +| | Stores configuration information for the local machine. | +| | Stores information about types (and classes) and their properties. | +| | Stores information about the default user configuration. | +| | Stores performance information for software components. | +| | Stores non-user-specific hardware information. | +| | Stores dynamic data. | + +Once you've identified the root key under which you want to store/retrieve information from the registry, you can use the class to add or remove subkeys and manipulate the values for a given key. + +Hardware devices can place information in the registry automatically using the Plug and Play interface. Software for installing device drivers can place information in the registry by writing to standard APIs. + +## Static methods for getting and setting values + +The class also contains `static` and methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they're used. So when you access a large number of values, they don't perform as well as analogous methods in the class. + +The class also provides methods that allow you to: + +- Set Windows access control security for registry keys. +- Test the data type of a value before retrieving it. +- Delete keys. From bd58bba4b132fb07a05c0a50ccf8de11fe0e3651 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Sun, 31 Dec 2023 20:44:02 -0800 Subject: [PATCH 03/10] add some project files --- .../System/Exception/Overview/csharp/project.csproj | 8 ++++++++ .../snippets/System/Exception/Overview/vb/project.csproj | 8 ++++++++ .../InvalidCastException/Overview/csharp/project.csproj | 8 ++++++++ .../InvalidCastException/Overview/vb/project.csproj | 8 ++++++++ .../Overview/csharp/project.csproj | 8 ++++++++ .../InvalidOperationException/Overview/vb/project.csproj | 8 ++++++++ .../NotSupportedException/Overview/csharp/project.csproj | 8 ++++++++ .../NotSupportedException/Overview/vb/project.csproj | 8 ++++++++ .../Overview/csharp/project.csproj | 8 ++++++++ .../Overview/vb/project.csproj | 8 ++++++++ 10 files changed, 80 insertions(+) create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/project.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/project.csproj diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/vb/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/csharp/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidCastException/Overview/vb/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/vb/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/csharp/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/NotSupportedException/Overview/vb/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/project.csproj new file mode 100644 index 0000000000000..5ec2e995f1200 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/vb/project.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + From 979f3da1df80549b2f263c0dd1d2edfdcdffc830 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Sun, 31 Dec 2023 20:49:18 -0800 Subject: [PATCH 04/10] fix warnings --- .../Exception/Overview/csharp/ToString2.cs | 15 ++ .../Overview/csharp/basetoderived1.cs | 66 ++++++++ .../Overview/csharp/catchexception.cs | 30 ++++ .../Overview/csharp/iconvertible1.cs | 30 ++++ .../Exception/Overview/csharp/usageerrors2.cs | 43 +++++ .../Overview/csharp/Enumerable2.cs | 22 +++ .../Overview/csharp/Enumerable4.cs | 22 +++ .../Overview/csharp/Iterating2.cs | 42 +++++ .../Overview/csharp/Iterating3.cs | 30 ++++ .../Overview/csharp/List_Sort2.cs | 39 +++++ .../Overview/csharp/List_Sort3.cs | 42 +++++ .../Overview/csharp/List_Sort4.cs | 39 +++++ .../Overview/csharp/Nullable2.cs | 27 +++ .../Overview/csharp/UWP/App.xaml | 8 + .../Overview/csharp/UWP/App.xaml.cs | 108 ++++++++++++ .../csharp/UWP/ApplicationInsights.config | 3 + .../Overview/csharp/UWP/MainPage.xaml | 15 ++ .../Overview/csharp/UWP/MainPage.xaml.cs | 62 +++++++ .../Overview/csharp/UWP/Package.appxmanifest | 49 ++++++ .../UWP/UWPCrossThreadSolutionCS.csproj | 157 ++++++++++++++++++ .../Overview/csharp/UWP/snippets.5000.json | 3 + .../Overview/csharp/WPF1/App1.xaml | 9 + .../Overview/csharp/WPF1/App1.xaml.cs | 17 ++ .../Overview/csharp/WPF1/MainWindow.xaml | 14 ++ .../Overview/csharp/WPF1/MainWindow.xaml.cs | 44 +++++ .../csharp/WPF1/WPFCrossThreadCS.csproj | 9 + .../Overview/csharp/WPF1/app.config | 3 + .../Overview/csharp/WPF2/App2.xaml | 9 + .../Overview/csharp/WPF2/App2.xaml.cs | 17 ++ .../Overview/csharp/WPF2/MainWindow1.xaml | 14 ++ .../csharp/WPF2/MainWindowDispatcher.xaml.cs | 49 ++++++ .../WPF2/WPFCrossThreadDispatcherCS.csproj | 9 + .../csharp/WinForms/Form1.Designer.cs | 73 ++++++++ .../Overview/csharp/WinForms/Form1.cs | 48 ++++++ .../Overview/csharp/WinForms/Form1.resx | 120 +++++++++++++ .../csharp/WinForms/Form11.Designer.cs | 73 ++++++++ .../Overview/csharp/WinForms/Form11.cs | 61 +++++++ .../Overview/csharp/WinForms/Form11.resx | 120 +++++++++++++ .../Overview/csharp/WinForms/Program.cs | 22 +++ .../Overview/csharp/WinForms/Program1.cs | 22 +++ .../csharp/WinForms/WFCrossThreadCS.csproj | 10 ++ .../system-notimplementedexception.md | 7 +- 42 files changed, 1601 insertions(+), 1 deletion(-) create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/ToString2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/basetoderived1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/catchexception.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/iconvertible1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable4.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating3.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort3.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort4.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable2.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/ApplicationInsights.config create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/Package.appxmanifest create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/UWPCrossThreadSolutionCS.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/snippets.5000.json create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/App1.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/App1.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/MainWindow.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/MainWindow.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/WPFCrossThreadCS.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF1/app.config create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF2/App2.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF2/App2.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF2/MainWindow1.xaml create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF2/MainWindowDispatcher.xaml.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WPF2/WPFCrossThreadDispatcherCS.csproj create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form1.Designer.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form1.resx create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form11.Designer.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form11.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form11.resx create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Program.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/Program1.cs create mode 100644 docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/WinForms/WFCrossThreadCS.csproj diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/ToString2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/ToString2.cs new file mode 100644 index 0000000000000..210a54af176f4 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/ToString2.cs @@ -0,0 +1,15 @@ +// +using System; + +public class Example +{ + public static void Main() + { + object value = 12; + string s = value.ToString(); + Console.WriteLine(s); + } +} +// The example displays the following output: +// 12 +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/basetoderived1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/basetoderived1.cs new file mode 100644 index 0000000000000..ff589249a2cb4 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/basetoderived1.cs @@ -0,0 +1,66 @@ +// +using System; + +public class Person +{ + String _name; + + public String Name + { + get { return _name; } + set { _name = value; } + } +} + +public class PersonWithId : Person +{ + String _id; + + public string Id + { + get { return _id; } + set { _id = value; } + } +} + +public class Example +{ + public static void Main() + { + Person p = new Person(); + p.Name = "John"; + try { + PersonWithId pid = (PersonWithId) p; + Console.WriteLine("Conversion succeeded."); + } + catch (InvalidCastException) { + Console.WriteLine("Conversion failed."); + } + + PersonWithId pid1 = new PersonWithId(); + pid1.Name = "John"; + pid1.Id = "246"; + Person p1 = pid1; + try { + PersonWithId pid1a = (PersonWithId) p1; + Console.WriteLine("Conversion succeeded."); + } + catch (InvalidCastException) { + Console.WriteLine("Conversion failed."); + } + + Person p2 = null; + try { + PersonWithId pid2 = (PersonWithId) p2; + Console.WriteLine("Conversion succeeded."); + } + catch (InvalidCastException) { + Console.WriteLine("Conversion failed."); + } + } +} +// The example displays the following output: +// Conversion failed. +// Conversion succeeded. +// Conversion succeeded. +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/catchexception.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/catchexception.cs new file mode 100644 index 0000000000000..cc7736bf616c3 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/catchexception.cs @@ -0,0 +1,30 @@ +// +using System; + +class ExceptionTestClass +{ + public static void Main() + { + int x = 0; + try + { + int y = 100 / x; + } + catch (ArithmeticException e) + { + Console.WriteLine($"ArithmeticException Handler: {e}"); + } + catch (Exception e) + { + Console.WriteLine($"Generic Exception Handler: {e}"); + } + } +} +/* +This code example produces the following results: + +ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. + at ExceptionTestClass.Main() + +*/ +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/iconvertible1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/iconvertible1.cs new file mode 100644 index 0000000000000..0ab111e2b83fc --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/iconvertible1.cs @@ -0,0 +1,30 @@ +// +using System; + +public class Example +{ + public static void Main() + { + bool flag = true; + try { + IConvertible conv = flag; + Char ch = conv.ToChar(null); + Console.WriteLine("Conversion succeeded."); + } + catch (InvalidCastException) { + Console.WriteLine("Cannot convert a Boolean to a Char."); + } + + try { + Char ch = Convert.ToChar(flag); + Console.WriteLine("Conversion succeeded."); + } + catch (InvalidCastException) { + Console.WriteLine("Cannot convert a Boolean to a Char."); + } + } +} +// The example displays the following output: +// Cannot convert a Boolean to a Char. +// Cannot convert a Boolean to a Char. +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs new file mode 100644 index 0000000000000..56b1801fc7070 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs @@ -0,0 +1,43 @@ +// +using System; + +public class Person +{ + private string _name; + + public string Name + { + get { return _name; } + set { _name = value; } + } + + public override int GetHashCode() + { + return this.Name.GetHashCode(); + } + + public override bool Equals(object obj) + { + // This implementation handles a null obj argument. + Person p = obj as Person; + if (p == null) + return false; + else + return this.Name.Equals(p.Name); + } +} + +public class Example +{ + public static void Main() + { + Person p1 = new Person(); + p1.Name = "John"; + Person p2 = null; + + Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); + } +} +// The example displays the following output: +// p1 = p2: False +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable2.cs new file mode 100644 index 0000000000000..b6a349a344d7c --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable2.cs @@ -0,0 +1,22 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] dbQueryResults = { 1, 2, 3, 4 }; + var moreThan4 = dbQueryResults.Where(num => num > 4); + + if(moreThan4.Any()) + Console.WriteLine("Average value of numbers greater than 4: {0}:", + moreThan4.Average()); + else + // handle empty collection + Console.WriteLine("The dataset has no values greater than 4."); + } +} +// The example displays the following output: +// The dataset has no values greater than 4. +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable4.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable4.cs new file mode 100644 index 0000000000000..961d3d9224b81 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Enumerable4.cs @@ -0,0 +1,22 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + int[] dbQueryResults = { 1, 2, 3, 4 }; + + var firstNum = dbQueryResults.FirstOrDefault(n => n > 4); + + if (firstNum == 0) + Console.WriteLine("No value is greater than 4."); + else + Console.WriteLine("The first value greater than 4 is {0}", + firstNum); + } +} +// The example displays the following output: +// No value is greater than 4. +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating2.cs new file mode 100644 index 0000000000000..965803fc71726 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating2.cs @@ -0,0 +1,42 @@ +// +using System; +using System.Collections.Generic; + +public class Example +{ + public static void Main() + { + var numbers = new List() { 1, 2, 3, 4, 5 }; + + int upperBound = numbers.Count - 1; + for (int ctr = 0; ctr <= upperBound; ctr++) { + int square = (int) Math.Pow(numbers[ctr], 2); + Console.WriteLine("{0}^{1}", numbers[ctr], square); + Console.WriteLine("Adding {0} to the collection...\n", square); + numbers.Add(square); + } + + Console.WriteLine("Elements now in the collection: "); + foreach (var number in numbers) + Console.Write("{0} ", number); + } +} +// The example displays the following output: +// 1^1 +// Adding 1 to the collection... +// +// 2^4 +// Adding 4 to the collection... +// +// 3^9 +// Adding 9 to the collection... +// +// 4^16 +// Adding 16 to the collection... +// +// 5^25 +// Adding 25 to the collection... +// +// Elements now in the collection: +// 1 2 3 4 5 1 4 9 16 25 +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating3.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating3.cs new file mode 100644 index 0000000000000..9283746cbf459 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Iterating3.cs @@ -0,0 +1,30 @@ +// +using System; +using System.Collections.Generic; + +public class Example +{ + public static void Main() + { + var numbers = new List() { 1, 2, 3, 4, 5 }; + var temp = new List(); + + // Square each number and store it in a temporary collection. + foreach (var number in numbers) { + int square = (int) Math.Pow(number, 2); + temp.Add(square); + } + + // Combine the numbers into a single array. + int[] combined = new int[numbers.Count + temp.Count]; + Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count); + Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count); + + // Iterate the array. + foreach (var value in combined) + Console.Write("{0} ", value); + } +} +// The example displays the following output: +// 1 2 3 4 5 1 4 9 16 25 +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort2.cs new file mode 100644 index 0000000000000..24f61b3d9df7b --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort2.cs @@ -0,0 +1,39 @@ +// +using System; +using System.Collections.Generic; + +public class Person : IComparable +{ + public Person(String fName, String lName) + { + FirstName = fName; + LastName = lName; + } + + public String FirstName { get; set; } + public String LastName { get; set; } + + public int CompareTo(Person other) + { + return String.Format("{0} {1}", LastName, FirstName). + CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName)); + } +} + +public class Example +{ + public static void Main() + { + var people = new List(); + + people.Add(new Person("John", "Doe")); + people.Add(new Person("Jane", "Doe")); + people.Sort(); + foreach (var person in people) + Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + } +} +// The example displays the following output: +// Jane Doe +// John Doe +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort3.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort3.cs new file mode 100644 index 0000000000000..453f5d5d4b2d2 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort3.cs @@ -0,0 +1,42 @@ +// +using System; +using System.Collections.Generic; + +public class Person +{ + public Person(String fName, String lName) + { + FirstName = fName; + LastName = lName; + } + + public String FirstName { get; set; } + public String LastName { get; set; } +} + +public class PersonComparer : IComparer +{ + public int Compare(Person x, Person y) + { + return String.Format("{0} {1}", x.LastName, x.FirstName). + CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); + } +} + +public class Example +{ + public static void Main() + { + var people = new List(); + + people.Add(new Person("John", "Doe")); + people.Add(new Person("Jane", "Doe")); + people.Sort(new PersonComparer()); + foreach (var person in people) + Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + } +} +// The example displays the following output: +// Jane Doe +// John Doe +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort4.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort4.cs new file mode 100644 index 0000000000000..220928e4a0bdf --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/List_Sort4.cs @@ -0,0 +1,39 @@ +// +using System; +using System.Collections.Generic; + +public class Person +{ + public Person(String fName, String lName) + { + FirstName = fName; + LastName = lName; + } + + public String FirstName { get; set; } + public String LastName { get; set; } +} + +public class Example +{ + public static void Main() + { + var people = new List(); + + people.Add(new Person("John", "Doe")); + people.Add(new Person("Jane", "Doe")); + people.Sort(PersonComparison); + foreach (var person in people) + Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + } + + public static int PersonComparison(Person x, Person y) + { + return String.Format("{0} {1}", x.LastName, x.FirstName). + CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); + } +} +// The example displays the following output: +// Jane Doe +// John Doe +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable2.cs new file mode 100644 index 0000000000000..56506c0979c76 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Nullable2.cs @@ -0,0 +1,27 @@ +// +using System; +using System.Linq; + +public class Example +{ + public static void Main() + { + var queryResult = new int?[] { 1, 2, null, 4 }; + var numbers = queryResult.Select(nullableInt => (int)nullableInt.GetValueOrDefault()); + + // Display list using Nullable.HasValue. + foreach (var number in numbers) + Console.Write("{0} ", number); + Console.WriteLine(); + + numbers = queryResult.Select(nullableInt => (int) (nullableInt.HasValue ? nullableInt : -1)); + // Display list using Nullable.GetValueOrDefault. + foreach (var number in numbers) + Console.Write("{0} ", number); + Console.WriteLine(); + } +} +// The example displays the following output: +// 1 2 0 4 +// 1 2 -1 4 +// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml new file mode 100644 index 0000000000000..d71ed553e18c2 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml @@ -0,0 +1,8 @@ + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml.cs new file mode 100644 index 0000000000000..80f7b509f22cc --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/App.xaml.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using Windows.ApplicationModel; +using Windows.ApplicationModel.Activation; +using Windows.Foundation; +using Windows.Foundation.Collections; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Controls.Primitives; +using Windows.UI.Xaml.Data; +using Windows.UI.Xaml.Input; +using Windows.UI.Xaml.Media; +using Windows.UI.Xaml.Navigation; + +namespace UWPCrossThreadSolutionCS +{ + /// + /// Provides application-specific behavior to supplement the default Application class. + /// + sealed partial class App : Application + { + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// + public App() + { + Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync( + Microsoft.ApplicationInsights.WindowsCollectors.Metadata | + Microsoft.ApplicationInsights.WindowsCollectors.Session); + this.InitializeComponent(); + this.Suspending += OnSuspending; + } + + /// + /// Invoked when the application is launched normally by the end user. Other entry points + /// will be used such as when the application is launched to open a specific file. + /// + /// Details about the launch request and process. + protected override void OnLaunched(LaunchActivatedEventArgs e) + { + +#if DEBUG + if (System.Diagnostics.Debugger.IsAttached) + { + this.DebugSettings.EnableFrameRateCounter = true; + } +#endif + + Frame rootFrame = Window.Current.Content as Frame; + + // Do not repeat app initialization when the Window already has content, + // just ensure that the window is active + if (rootFrame == null) + { + // Create a Frame to act as the navigation context and navigate to the first page + rootFrame = new Frame(); + + rootFrame.NavigationFailed += OnNavigationFailed; + + if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) + { + //TODO: Load state from previously suspended application + } + + // Place the frame in the current Window + Window.Current.Content = rootFrame; + } + + if (rootFrame.Content == null) + { + // When the navigation stack isn't restored navigate to the first page, + // configuring the new page by passing required information as a navigation + // parameter + rootFrame.Navigate(typeof(MainPage), e.Arguments); + } + // Ensure the current window is active + Window.Current.Activate(); + } + + /// + /// Invoked when Navigation to a certain page fails + /// + /// The Frame which failed navigation + /// Details about the navigation failure + void OnNavigationFailed(object sender, NavigationFailedEventArgs e) + { + throw new Exception("Failed to load Page " + e.SourcePageType.FullName); + } + + /// + /// Invoked when application execution is being suspended. Application state is saved + /// without knowing whether the application will be terminated or resumed with the contents + /// of memory still intact. + /// + /// The source of the suspend request. + /// Details about the suspend request. + private void OnSuspending(object sender, SuspendingEventArgs e) + { + var deferral = e.SuspendingOperation.GetDeferral(); + //TODO: Save application state and stop any background activity + deferral.Complete(); + } + } +} diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/ApplicationInsights.config b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/ApplicationInsights.config new file mode 100644 index 0000000000000..cb2a232da35d5 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/ApplicationInsights.config @@ -0,0 +1,3 @@ + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml new file mode 100644 index 0000000000000..f7cbdf976d66f --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/UWP/MainPage.xaml @@ -0,0 +1,15 @@ + + + + +