From 7d910447bf00e8ebaec6a28c33c82a2d241138f1 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Thu, 6 Aug 2026 16:59:58 -0700
Subject: [PATCH 1/5] Modernize C# code snippets
---
.../csharp/System/Char/CompareTo/compareto.cs | 18 +-
.../System/Char/ConvertFromUtf32/utf.cs | 114 ++++---
snippets/csharp/System/Char/Equals/equals.cs | 16 +-
.../Char/GetNumericValue/getnumericvalue.cs | 14 +-
.../Char/GetNumericValue/getnumericvalue1.cs | 158 +++++-----
.../GetUnicodeCategory/getunicodecategory.cs | 18 +-
.../System/Char/IsControl/IsControl1.cs | 30 +-
.../System/Char/IsControl/IsControl2.cs | 19 +-
.../csharp/System/Char/IsControl/iscontrol.cs | 14 +-
.../csharp/System/Char/IsDigit/isdigit.cs | 14 +-
.../csharp/System/Char/IsHighSurrogate/sur.cs | 66 ++--
.../csharp/System/Char/IsLetter/isletter.cs | 14 +-
.../Char/IsLetterOrDigit/isletterordigit.cs | 14 +-
.../csharp/System/Char/IsLower/islower.cs | 14 +-
.../csharp/System/Char/IsNumber/isnumber.cs | 14 +-
.../csharp/System/Char/IsNumber/isnumber1.cs | 63 ++--
.../Char/IsPunctuation/ispunctuation.cs | 14 +-
.../System/Char/IsSeparator/isseparator.cs | 14 +-
.../System/Char/IsSeparator/isseparator1.cs | 18 +-
.../System/Char/IsSurrogate/issurrogate.cs | 14 +-
.../csharp/System/Char/IsSymbol/issymbol.cs | 14 +-
.../System/Char/IsWhiteSpace/iswhitespace.cs | 14 +-
.../Char/Overview/GetUnicodeCategory3.cs | 20 +-
.../System/Char/Overview/charstructure.cs | 24 +-
.../csharp/System/Char/Overview/grapheme1.cs | 6 +-
.../csharp/System/Char/Overview/surrogate1.cs | 6 +-
.../System/Char/Overview/textelements2.cs | 6 +-
.../System/Char/Overview/textelements2a.cs | 8 +-
snippets/csharp/System/Char/Parse/parse.cs | 10 +-
.../csharp/System/Char/ToLower/tolower.cs | 12 +-
.../csharp/System/Char/ToString/tostring.cs | 14 +-
.../csharp/System/Char/ToUpper/toupper1.cs | 13 +-
.../csharp/System/Char/ToUpper/toupper5.cs | 27 +-
snippets/csharp/System/Char/TryParse/tp.cs | 242 +++++++--------
.../Overview/CharEnumerator1.cs | 120 ++++---
.../Console/BackgroundColor/Example2.cs | 19 +-
.../BackgroundColor/backgroundcolor1.cs | 41 +--
.../BackgroundColor/foregroundcolor3.cs | 60 ++--
snippets/csharp/System/Console/Beep/b2.cs | 90 +++---
snippets/csharp/System/Console/Beep/beep.cs | 22 +-
.../csharp/System/Console/BufferHeight/hw.cs | 8 +-
.../System/Console/CancelKeyPress/ckp.cs | 2 +-
.../csharp/System/Console/Clear/clear1.cs | 150 ++++-----
snippets/csharp/System/Console/Clear/lts.cs | 68 ++--
.../csharp/System/Console/CursorSize/csize.cs | 26 +-
.../System/Console/CursorVisible/vis.cs | 54 ++--
.../csharp/System/Console/Error/error1.cs | 53 ++--
.../System/Console/Error/expandtabsex.cs | 22 +-
.../System/Console/Error/viewtextfile.cs | 74 ++---
.../csharp/System/Console/In/consolein.cs | 12 +-
.../csharp/System/Console/KeyAvailable/ka.cs | 23 +-
.../Console/OpenStandardInput/decode.cs | 6 +-
.../Console/OpenStandardOutput/inserttabs.cs | 7 +-
snippets/csharp/System/Console/Out/out1.cs | 52 ++--
.../System/Console/Overview/example3.cs | 293 +++++++++---------
.../System/Console/Overview/fontlink1.cs | 126 ++++----
.../System/Console/Overview/normalize1.cs | 18 +-
.../System/Console/Overview/setfont1.cs | 129 ++++----
.../csharp/System/Console/Overview/source.cs | 5 +-
.../System/Console/Overview/unicode1.cs | 41 +--
snippets/csharp/System/Console/Read/read.cs | 48 +--
.../csharp/System/Console/ReadKey/ReadKey1.cs | 21 +-
.../csharp/System/Console/ReadKey/ReadKey2.cs | 21 +-
snippets/csharp/System/Console/ReadKey/rk.cs | 32 +-
.../csharp/System/Console/ReadKey/rkbool.cs | 33 +-
.../System/Console/ReadLine/ReadLine2.cs | 25 +-
.../System/Console/ReadLine/ReadLine3.cs | 38 +--
.../System/Console/ReadLine/ReadLineSimple.cs | 16 +-
.../System/Console/SetBufferSize/wlt.cs | 170 +++++-----
.../System/Console/SetError/SetError1.cs | 44 +--
.../csharp/System/Console/SetOut/source.cs | 21 +-
.../System/Console/SetWindowSize/sws.cs | 66 ++--
.../csharp/System/Console/Title/mytitle.cs | 17 +-
.../System/Console/WindowLeft/windowleft1.cs | 80 ++---
.../System/Console/Write/WriteParams1.cs | 52 ++--
.../System/Console/Write/WriteParams2.cs | 52 ++--
.../csharp/System/Console/Write/reformat.cs | 14 +-
snippets/csharp/System/Console/Write/wl.cs | 4 +-
.../System/Console/WriteLine/WriteLine6.cs | 35 ++-
.../System/Console/WriteLine/WriteLine7.cs | 7 +-
.../System/Console/WriteLine/newline1.cs | 64 ++--
.../System/Console/WriteLine/tipcalc.cs | 4 +-
.../Console/WriteLine/writeline_boolean1.cs | 35 ++-
.../Console/WriteLine/writeline_obj1.cs | 30 +-
.../System/ConsoleKey/Overview/ConsoleKey1.cs | 82 ++---
.../System/ConsoleKeyInfo/Equals/equals.cs | 110 +++----
.../System/ConsoleKeyInfo/GetHashCode/hash.cs | 92 +++---
.../System/ConsoleKeyInfo/KeyChar/keychar1.cs | 90 +++---
88 files changed, 1986 insertions(+), 1914 deletions(-)
diff --git a/snippets/csharp/System/Char/CompareTo/compareto.cs b/snippets/csharp/System/Char/CompareTo/compareto.cs
index cef09ab0111..a76567483ca 100644
--- a/snippets/csharp/System/Char/CompareTo/compareto.cs
+++ b/snippets/csharp/System/Char/CompareTo/compareto.cs
@@ -1,14 +1,16 @@
//
using System;
-public class CompareToSample {
- public static void Main() {
- char chA = 'A';
- char chB = 'B';
+public class CompareToSample
+{
+ public static void Main()
+ {
+ char chA = 'A';
+ char chB = 'B';
- Console.WriteLine(chA.CompareTo('A')); // Output: "0" (meaning they're equal)
- Console.WriteLine('b'.CompareTo(chB)); // Output: "32" (meaning 'b' is greater than 'B' by 32)
- Console.WriteLine(chA.CompareTo(chB)); // Output: "-1" (meaning 'A' is less than 'B' by 1)
- }
+ Console.WriteLine(chA.CompareTo('A')); // Output: "0" (meaning they're equal)
+ Console.WriteLine('b'.CompareTo(chB)); // Output: "32" (meaning 'b' is greater than 'B' by 32)
+ Console.WriteLine(chA.CompareTo(chB)); // Output: "-1" (meaning 'A' is less than 'B' by 1)
+ }
}
//
diff --git a/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs b/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
index 1006f5c344f..c853a5a51f7 100644
--- a/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
+++ b/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
@@ -7,68 +7,66 @@ class Sample
{
public static void Main()
{
- int letterA = 0x0041; //U+00041 = LATIN CAPITAL LETTER A
- int music = 0x1D161; //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
- string s1;
- string comment = "Create a UTF-16 encoded string from a code point.";
- string comment1b = "Create a code point from a UTF-16 encoded string.";
- string comment2b = "Create a code point from a surrogate pair at a certain position in a string.";
- string comment2c = "Create a code point from a high surrogate and a low surrogate code point.";
-
-// Convert code point U+0041 to UTF-16. The UTF-16 equivalent of
-// U+0041 is a Char with hexadecimal value 0041.
-
- Console.WriteLine(comment);
- s1 = Char.ConvertFromUtf32(letterA);
- Console.Write(" 1a) 0x{0:X} => ", letterA);
- Show(s1);
- Console.WriteLine();
-
-// Convert the lone UTF-16 character to a code point.
-
- Console.WriteLine(comment1b);
- letterA = Char.ConvertToUtf32(s1, 0);
- Console.Write(" 1b) ");
- Show(s1);
- Console.WriteLine(" => 0x{0:X}", letterA);
- Console.WriteLine();
-
-// -------------------------------------------------------------------
-
-// Convert the code point U+1D161 to UTF-16. The UTF-16 equivalent of
-// U+1D161 is a surrogate pair with hexadecimal values D834 and DD61.
-
- Console.WriteLine(comment);
- s1 = Char.ConvertFromUtf32(music);
- Console.Write(" 2a) 0x{0:X} => ", music);
- Show(s1);
- Console.WriteLine();
-
-// Convert the surrogate pair in the string at index position
-// zero to a code point.
-
- Console.WriteLine(comment2b);
- music = Char.ConvertToUtf32(s1, 0);
- Console.Write(" 2b) ");
- Show(s1);
- Console.WriteLine(" => 0x{0:X}", music);
-
-// Convert the high and low characters in the surrogate pair into a code point.
-
- Console.WriteLine(comment2c);
- music = Char.ConvertToUtf32(s1[0], s1[1]);
- Console.Write(" 2c) ");
- Show(s1);
- Console.WriteLine(" => 0x{0:X}", music);
+ int letterA = 0x0041; //U+00041 = LATIN CAPITAL LETTER A
+ int music = 0x1D161; //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
+ string s1;
+ string comment = "Create a UTF-16 encoded string from a code point.";
+ string comment1b = "Create a code point from a UTF-16 encoded string.";
+ string comment2b = "Create a code point from a surrogate pair at a certain position in a string.";
+ string comment2c = "Create a code point from a high surrogate and a low surrogate code point.";
+
+ // Convert code point U+0041 to UTF-16. The UTF-16 equivalent of
+ // U+0041 is a Char with hexadecimal value 0041.
+
+ Console.WriteLine(comment);
+ s1 = char.ConvertFromUtf32(letterA);
+ Console.Write($" 1a) 0x{letterA:X} => ");
+ Show(s1);
+ Console.WriteLine();
+
+ // Convert the lone UTF-16 character to a code point.
+
+ Console.WriteLine(comment1b);
+ letterA = char.ConvertToUtf32(s1, 0);
+ Console.Write(" 1b) ");
+ Show(s1);
+ Console.WriteLine($" => 0x{letterA:X}");
+ Console.WriteLine();
+
+ // -------------------------------------------------------------------
+
+ // Convert the code point U+1D161 to UTF-16. The UTF-16 equivalent of
+ // U+1D161 is a surrogate pair with hexadecimal values D834 and DD61.
+
+ Console.WriteLine(comment);
+ s1 = char.ConvertFromUtf32(music);
+ Console.Write($" 2a) 0x{music:X} => ");
+ Show(s1);
+ Console.WriteLine();
+
+ // Convert the surrogate pair in the string at index position
+ // zero to a code point.
+
+ Console.WriteLine(comment2b);
+ music = char.ConvertToUtf32(s1, 0);
+ Console.Write(" 2b) ");
+ Show(s1);
+ Console.WriteLine($" => 0x{music:X}");
+
+ // Convert the high and low characters in the surrogate pair into a code point.
+
+ Console.WriteLine(comment2c);
+ music = char.ConvertToUtf32(s1[0], s1[1]);
+ Console.Write(" 2c) ");
+ Show(s1);
+ Console.WriteLine($" => 0x{music:X}");
}
private static void Show(string s)
{
- for (int x = 0; x < s.Length; x++)
+ for (int x = 0; x < s.Length; x++)
{
- Console.Write("0x{0:X}{1}",
- (int)s[x],
- ((x == s.Length-1)? String.Empty : ", "));
+ Console.Write($"0x{(int)s[x]:X}{((x == s.Length - 1) ? string.Empty : ", ")}");
}
}
}
@@ -88,4 +86,4 @@ Create a code point from a high surrogate and a low surrogate code point.
2c) 0xD834, 0xDD61 => 0x1D161
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Char/Equals/equals.cs b/snippets/csharp/System/Char/Equals/equals.cs
index 0470e9a3774..d2c263528d6 100644
--- a/snippets/csharp/System/Char/Equals/equals.cs
+++ b/snippets/csharp/System/Char/Equals/equals.cs
@@ -1,13 +1,15 @@
//
using System;
-public class EqualsSample {
- public static void Main() {
- char chA = 'A';
- char chB = 'B';
+public class EqualsSample
+{
+ public static void Main()
+ {
+ char chA = 'A';
+ char chB = 'B';
- Console.WriteLine(chA.Equals('A')); // Output: "True"
- Console.WriteLine('b'.Equals(chB)); // Output: "False"
- }
+ Console.WriteLine(chA.Equals('A')); // Output: "True"
+ Console.WriteLine('b'.Equals(chB)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
index 8c8e10eb45b..d6f2c51339d 100644
--- a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
+++ b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
@@ -1,12 +1,14 @@
//
using System;
-public class GetNumericValueSample {
- public static void Main() {
- string str = "input: 1";
+public class GetNumericValueSample
+{
+ public static void Main()
+ {
+ string str = "input: 1";
- Console.WriteLine(Char.GetNumericValue('8')); // Output: "8"
- Console.WriteLine(Char.GetNumericValue(str, 7)); // Output: "1"
- }
+ Console.WriteLine(char.GetNumericValue('8')); // Output: "8"
+ Console.WriteLine(char.GetNumericValue(str, 7)); // Output: "1"
+ }
}
//
diff --git a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
index 7df01ad16c7..6066ef271ce 100644
--- a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
+++ b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
@@ -2,88 +2,86 @@
public class Example
{
- public static void Main()
- {
- Overload1();
- Console.WriteLine();
- Overload2();
- }
+ public static void Main()
+ {
+ Overload1();
+ Console.WriteLine();
+ Overload2();
+ }
- private static void Overload1()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = Char.ConvertFromUtf32(utf32);
- foreach (var ch in surrogate)
- Console.WriteLine("U+{0:X4}: {1} ", Convert.ToUInt16(ch),
- Char.GetNumericValue(ch));
+ private static void Overload1()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = char.ConvertFromUtf32(utf32);
+ foreach (char ch in surrogate)
+ Console.WriteLine($"U+{Convert.ToUInt16(ch):X4}: {char.GetNumericValue(ch)} ");
- // The example displays the following output:
- // U+D800: -1
- // U+DD07: -1
- //
- }
+ // The example displays the following output:
+ // U+D800: -1
+ // U+DD07: -1
+ //
+ }
- private static void Overload2()
- {
- //
- // Define a UTF32 value for each character in the
- // Aegean numbering system.
- for (int utf32 = 0x10107; utf32 <= 0x10133; utf32++) {
- string surrogate = Char.ConvertFromUtf32(utf32);
- for (int ctr = 0; ctr < surrogate.Length; ctr++)
- Console.Write("U+{0:X4} at position {1}: {2} ",
- Convert.ToUInt16(surrogate[ctr]), ctr,
- Char.GetNumericValue(surrogate, ctr));
+ private static void Overload2()
+ {
+ //
+ // Define a UTF32 value for each character in the
+ // Aegean numbering system.
+ for (int utf32 = 0x10107; utf32 <= 0x10133; utf32++)
+ {
+ string surrogate = char.ConvertFromUtf32(utf32);
+ for (int ctr = 0; ctr < surrogate.Length; ctr++)
+ Console.Write($"U+{Convert.ToUInt16(surrogate[ctr]):X4} at position {ctr}: {char.GetNumericValue(surrogate, ctr)} ");
- Console.WriteLine();
- }
- // The example displays the following output:
- // U+D800 at position 0: 1 U+DD07 at position 1: -1
- // U+D800 at position 0: 2 U+DD08 at position 1: -1
- // U+D800 at position 0: 3 U+DD09 at position 1: -1
- // U+D800 at position 0: 4 U+DD0A at position 1: -1
- // U+D800 at position 0: 5 U+DD0B at position 1: -1
- // U+D800 at position 0: 6 U+DD0C at position 1: -1
- // U+D800 at position 0: 7 U+DD0D at position 1: -1
- // U+D800 at position 0: 8 U+DD0E at position 1: -1
- // U+D800 at position 0: 9 U+DD0F at position 1: -1
- // U+D800 at position 0: 10 U+DD10 at position 1: -1
- // U+D800 at position 0: 20 U+DD11 at position 1: -1
- // U+D800 at position 0: 30 U+DD12 at position 1: -1
- // U+D800 at position 0: 40 U+DD13 at position 1: -1
- // U+D800 at position 0: 50 U+DD14 at position 1: -1
- // U+D800 at position 0: 60 U+DD15 at position 1: -1
- // U+D800 at position 0: 70 U+DD16 at position 1: -1
- // U+D800 at position 0: 80 U+DD17 at position 1: -1
- // U+D800 at position 0: 90 U+DD18 at position 1: -1
- // U+D800 at position 0: 100 U+DD19 at position 1: -1
- // U+D800 at position 0: 200 U+DD1A at position 1: -1
- // U+D800 at position 0: 300 U+DD1B at position 1: -1
- // U+D800 at position 0: 400 U+DD1C at position 1: -1
- // U+D800 at position 0: 500 U+DD1D at position 1: -1
- // U+D800 at position 0: 600 U+DD1E at position 1: -1
- // U+D800 at position 0: 700 U+DD1F at position 1: -1
- // U+D800 at position 0: 800 U+DD20 at position 1: -1
- // U+D800 at position 0: 900 U+DD21 at position 1: -1
- // U+D800 at position 0: 1000 U+DD22 at position 1: -1
- // U+D800 at position 0: 2000 U+DD23 at position 1: -1
- // U+D800 at position 0: 3000 U+DD24 at position 1: -1
- // U+D800 at position 0: 4000 U+DD25 at position 1: -1
- // U+D800 at position 0: 5000 U+DD26 at position 1: -1
- // U+D800 at position 0: 6000 U+DD27 at position 1: -1
- // U+D800 at position 0: 7000 U+DD28 at position 1: -1
- // U+D800 at position 0: 8000 U+DD29 at position 1: -1
- // U+D800 at position 0: 9000 U+DD2A at position 1: -1
- // U+D800 at position 0: 10000 U+DD2B at position 1: -1
- // U+D800 at position 0: 20000 U+DD2C at position 1: -1
- // U+D800 at position 0: 30000 U+DD2D at position 1: -1
- // U+D800 at position 0: 40000 U+DD2E at position 1: -1
- // U+D800 at position 0: 50000 U+DD2F at position 1: -1
- // U+D800 at position 0: 60000 U+DD30 at position 1: -1
- // U+D800 at position 0: 70000 U+DD31 at position 1: -1
- // U+D800 at position 0: 80000 U+DD32 at position 1: -1
- // U+D800 at position 0: 90000 U+DD33 at position 1: -1
- //
- }
+ Console.WriteLine();
+ }
+ // The example displays the following output:
+ // U+D800 at position 0: 1 U+DD07 at position 1: -1
+ // U+D800 at position 0: 2 U+DD08 at position 1: -1
+ // U+D800 at position 0: 3 U+DD09 at position 1: -1
+ // U+D800 at position 0: 4 U+DD0A at position 1: -1
+ // U+D800 at position 0: 5 U+DD0B at position 1: -1
+ // U+D800 at position 0: 6 U+DD0C at position 1: -1
+ // U+D800 at position 0: 7 U+DD0D at position 1: -1
+ // U+D800 at position 0: 8 U+DD0E at position 1: -1
+ // U+D800 at position 0: 9 U+DD0F at position 1: -1
+ // U+D800 at position 0: 10 U+DD10 at position 1: -1
+ // U+D800 at position 0: 20 U+DD11 at position 1: -1
+ // U+D800 at position 0: 30 U+DD12 at position 1: -1
+ // U+D800 at position 0: 40 U+DD13 at position 1: -1
+ // U+D800 at position 0: 50 U+DD14 at position 1: -1
+ // U+D800 at position 0: 60 U+DD15 at position 1: -1
+ // U+D800 at position 0: 70 U+DD16 at position 1: -1
+ // U+D800 at position 0: 80 U+DD17 at position 1: -1
+ // U+D800 at position 0: 90 U+DD18 at position 1: -1
+ // U+D800 at position 0: 100 U+DD19 at position 1: -1
+ // U+D800 at position 0: 200 U+DD1A at position 1: -1
+ // U+D800 at position 0: 300 U+DD1B at position 1: -1
+ // U+D800 at position 0: 400 U+DD1C at position 1: -1
+ // U+D800 at position 0: 500 U+DD1D at position 1: -1
+ // U+D800 at position 0: 600 U+DD1E at position 1: -1
+ // U+D800 at position 0: 700 U+DD1F at position 1: -1
+ // U+D800 at position 0: 800 U+DD20 at position 1: -1
+ // U+D800 at position 0: 900 U+DD21 at position 1: -1
+ // U+D800 at position 0: 1000 U+DD22 at position 1: -1
+ // U+D800 at position 0: 2000 U+DD23 at position 1: -1
+ // U+D800 at position 0: 3000 U+DD24 at position 1: -1
+ // U+D800 at position 0: 4000 U+DD25 at position 1: -1
+ // U+D800 at position 0: 5000 U+DD26 at position 1: -1
+ // U+D800 at position 0: 6000 U+DD27 at position 1: -1
+ // U+D800 at position 0: 7000 U+DD28 at position 1: -1
+ // U+D800 at position 0: 8000 U+DD29 at position 1: -1
+ // U+D800 at position 0: 9000 U+DD2A at position 1: -1
+ // U+D800 at position 0: 10000 U+DD2B at position 1: -1
+ // U+D800 at position 0: 20000 U+DD2C at position 1: -1
+ // U+D800 at position 0: 30000 U+DD2D at position 1: -1
+ // U+D800 at position 0: 40000 U+DD2E at position 1: -1
+ // U+D800 at position 0: 50000 U+DD2F at position 1: -1
+ // U+D800 at position 0: 60000 U+DD30 at position 1: -1
+ // U+D800 at position 0: 70000 U+DD31 at position 1: -1
+ // U+D800 at position 0: 80000 U+DD32 at position 1: -1
+ // U+D800 at position 0: 90000 U+DD33 at position 1: -1
+ //
+ }
}
diff --git a/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs b/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
index c3d97612139..7171ac77733 100644
--- a/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
+++ b/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
@@ -1,14 +1,16 @@
//
using System;
-public class GetUnicodeCategorySample {
- public static void Main() {
- char ch2 = '2';
- string str = "Upper Case";
+public class GetUnicodeCategorySample
+{
+ public static void Main()
+ {
+ char ch2 = '2';
+ string str = "Upper Case";
- Console.WriteLine(Char.GetUnicodeCategory('a')); // Output: "LowercaseLetter"
- Console.WriteLine(Char.GetUnicodeCategory(ch2)); // Output: "DecimalDigitNumber"
- Console.WriteLine(Char.GetUnicodeCategory(str, 6)); // Output: "UppercaseLetter"
- }
+ Console.WriteLine(char.GetUnicodeCategory('a')); // Output: "LowercaseLetter"
+ Console.WriteLine(char.GetUnicodeCategory(ch2)); // Output: "DecimalDigitNumber"
+ Console.WriteLine(char.GetUnicodeCategory(str, 6)); // Output: "UppercaseLetter"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsControl/IsControl1.cs b/snippets/csharp/System/Char/IsControl/IsControl1.cs
index a83b4ad7d49..4ecdedf6fee 100644
--- a/snippets/csharp/System/Char/IsControl/IsControl1.cs
+++ b/snippets/csharp/System/Char/IsControl/IsControl1.cs
@@ -3,22 +3,22 @@
public class ControlChars
{
- public static void Main()
- {
- int charsWritten = 0;
+ public static void Main()
+ {
+ int charsWritten = 0;
- for (int ctr = 0x00; ctr <= 0xFFFF; ctr++)
- {
- char ch = Convert.ToChar(ctr);
- if (char.IsControl(ch))
- {
- Console.Write(@"\U{0:X4} ", ctr);
- charsWritten++;
- if (charsWritten % 6 == 0)
- Console.WriteLine();
- }
- }
- }
+ for (int ctr = 0x00; ctr <= 0xFFFF; ctr++)
+ {
+ char ch = Convert.ToChar(ctr);
+ if (char.IsControl(ch))
+ {
+ Console.Write($"\\U{ctr:X4} ");
+ charsWritten++;
+ if (charsWritten % 6 == 0)
+ Console.WriteLine();
+ }
+ }
+ }
}
// The example displays the following output to the console:
// \U0000 \U0001 \U0002 \U0003 \U0004 \U0005
diff --git a/snippets/csharp/System/Char/IsControl/IsControl2.cs b/snippets/csharp/System/Char/IsControl/IsControl2.cs
index f3a353e9fb3..ba6b5efdde1 100644
--- a/snippets/csharp/System/Char/IsControl/IsControl2.cs
+++ b/snippets/csharp/System/Char/IsControl/IsControl2.cs
@@ -3,16 +3,15 @@
public class ControlChar
{
- public static void Main()
- {
- string sentence = "This is a " + Environment.NewLine + "two-line sentence.";
- for (int ctr = 0; ctr < sentence.Length; ctr++)
- {
- if (Char.IsControl(sentence, ctr))
- Console.WriteLine("Control character \\U{0} found in position {1}.",
- Convert.ToInt32(sentence[ctr]).ToString("X4"), ctr);
- }
- }
+ public static void Main()
+ {
+ string sentence = "This is a " + Environment.NewLine + "two-line sentence.";
+ for (int ctr = 0; ctr < sentence.Length; ctr++)
+ {
+ if (char.IsControl(sentence, ctr))
+ Console.WriteLine($"Control character \\U{Convert.ToInt32(sentence[ctr]).ToString("X4")} found in position {ctr}.");
+ }
+ }
}
// The example displays the following output to the console:
// Control character \U000D found in position 10.
diff --git a/snippets/csharp/System/Char/IsControl/iscontrol.cs b/snippets/csharp/System/Char/IsControl/iscontrol.cs
index f8519b6da5a..4d10789b134 100644
--- a/snippets/csharp/System/Char/IsControl/iscontrol.cs
+++ b/snippets/csharp/System/Char/IsControl/iscontrol.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsControlSample {
- public static void Main() {
- string str = "sample string";
+public class IsControlSample
+{
+ public static void Main()
+ {
+ string str = "sample string";
- Console.WriteLine(Char.IsControl('\t')); // Output: "True"
- Console.WriteLine(Char.IsControl(str, 7)); // Output: "False"
- }
+ Console.WriteLine(char.IsControl('\t')); // Output: "True"
+ Console.WriteLine(char.IsControl(str, 7)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsDigit/isdigit.cs b/snippets/csharp/System/Char/IsDigit/isdigit.cs
index 76a8ba660f9..5af135a1c9a 100644
--- a/snippets/csharp/System/Char/IsDigit/isdigit.cs
+++ b/snippets/csharp/System/Char/IsDigit/isdigit.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsDigitSample {
- public static void Main() {
- char ch = '8';
+public class IsDigitSample
+{
+ public static void Main()
+ {
+ char ch = '8';
- Console.WriteLine(Char.IsDigit(ch)); // Output: "True"
- Console.WriteLine(Char.IsDigit("sample string", 7)); // Output: "False"
- }
+ Console.WriteLine(char.IsDigit(ch)); // Output: "True"
+ Console.WriteLine(char.IsDigit("sample string", 7)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsHighSurrogate/sur.cs b/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
index a74645cc6e2..81899436c28 100644
--- a/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
+++ b/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
@@ -8,44 +8,44 @@ class Sample
{
public static void Main()
{
- char cHigh = '\uD800';
- char cLow = '\uDC00';
- string s1 = new String(new char[] {'a', '\uD800', '\uDC00', 'z'});
- string divider = String.Concat( Environment.NewLine, new String('-', 70),
- Environment.NewLine);
+ char cHigh = '\uD800';
+ char cLow = '\uDC00';
+ string s1 = new(new char[] { 'a', '\uD800', '\uDC00', 'z' });
+ string divider = string.Concat(Environment.NewLine, new string('-', 70),
+ Environment.NewLine);
- Console.WriteLine();
- Console.WriteLine("Hexadecimal code point of the character, cHigh: {0:X4}", (int)cHigh);
- Console.WriteLine("Hexadecimal code point of the character, cLow: {0:X4}", (int)cLow);
- Console.WriteLine();
- Console.WriteLine("Characters in string, s1: 'a', high surrogate, low surrogate, 'z'");
- Console.WriteLine("Hexadecimal code points of the characters in string, s1: ");
- for(int i = 0; i < s1.Length; i++)
+ Console.WriteLine();
+ Console.WriteLine($"Hexadecimal code point of the character, cHigh: {(int)cHigh:X4}");
+ Console.WriteLine($"Hexadecimal code point of the character, cLow: {(int)cLow:X4}");
+ Console.WriteLine();
+ Console.WriteLine("Characters in string, s1: 'a', high surrogate, low surrogate, 'z'");
+ Console.WriteLine("Hexadecimal code points of the characters in string, s1: ");
+ for (int i = 0; i < s1.Length; i++)
{
- Console.WriteLine("s1[{0}] = {1:X4} ", i, (int)s1[i]);
+ Console.WriteLine($"s1[{i}] = {(int)s1[i]:X4} ");
}
- Console.WriteLine(divider);
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following characters a high surrogate?");
- Console.WriteLine("A1) cLow? - {0}", Char.IsHighSurrogate(cLow));
- Console.WriteLine("A2) cHigh? - {0}", Char.IsHighSurrogate(cHigh));
- Console.WriteLine("A3) s1[0]? - {0}", Char.IsHighSurrogate(s1, 0));
- Console.WriteLine("A4) s1[1]? - {0}", Char.IsHighSurrogate(s1, 1));
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following characters a high surrogate?");
+ Console.WriteLine($"A1) cLow? - {char.IsHighSurrogate(cLow)}");
+ Console.WriteLine($"A2) cHigh? - {char.IsHighSurrogate(cHigh)}");
+ Console.WriteLine($"A3) s1[0]? - {char.IsHighSurrogate(s1, 0)}");
+ Console.WriteLine($"A4) s1[1]? - {char.IsHighSurrogate(s1, 1)}");
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following characters a low surrogate?");
- Console.WriteLine("B1) cLow? - {0}", Char.IsLowSurrogate(cLow));
- Console.WriteLine("B2) cHigh? - {0}", Char.IsLowSurrogate(cHigh));
- Console.WriteLine("B3) s1[0]? - {0}", Char.IsLowSurrogate(s1, 0));
- Console.WriteLine("B4) s1[2]? - {0}", Char.IsLowSurrogate(s1, 2));
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following characters a low surrogate?");
+ Console.WriteLine($"B1) cLow? - {char.IsLowSurrogate(cLow)}");
+ Console.WriteLine($"B2) cHigh? - {char.IsLowSurrogate(cHigh)}");
+ Console.WriteLine($"B3) s1[0]? - {char.IsLowSurrogate(s1, 0)}");
+ Console.WriteLine($"B4) s1[2]? - {char.IsLowSurrogate(s1, 2)}");
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following pairs of characters a surrogate pair?");
- Console.WriteLine("C1) cHigh and cLow? - {0}", Char.IsSurrogatePair(cHigh, cLow));
- Console.WriteLine("C2) s1[0] and s1[1]? - {0}", Char.IsSurrogatePair(s1, 0));
- Console.WriteLine("C3) s1[1] and s1[2]? - {0}", Char.IsSurrogatePair(s1, 1));
- Console.WriteLine("C4) s1[2] and s1[3]? - {0}", Char.IsSurrogatePair(s1, 2));
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following pairs of characters a surrogate pair?");
+ Console.WriteLine($"C1) cHigh and cLow? - {char.IsSurrogatePair(cHigh, cLow)}");
+ Console.WriteLine($"C2) s1[0] and s1[1]? - {char.IsSurrogatePair(s1, 0)}");
+ Console.WriteLine($"C3) s1[1] and s1[2]? - {char.IsSurrogatePair(s1, 1)}");
+ Console.WriteLine($"C4) s1[2] and s1[3]? - {char.IsSurrogatePair(s1, 2)}");
+ Console.WriteLine(divider);
}
}
/*
@@ -88,4 +88,4 @@ Is each of the following pairs of characters a surrogate pair?
----------------------------------------------------------------------
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Char/IsLetter/isletter.cs b/snippets/csharp/System/Char/IsLetter/isletter.cs
index a4ba24d96cf..3b22509d456 100644
--- a/snippets/csharp/System/Char/IsLetter/isletter.cs
+++ b/snippets/csharp/System/Char/IsLetter/isletter.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsLetterSample {
- public static void Main() {
- char ch = '8';
+public class IsLetterSample
+{
+ public static void Main()
+ {
+ char ch = '8';
- Console.WriteLine(Char.IsLetter(ch)); // False
- Console.WriteLine(Char.IsLetter("sample string", 7)); // True
- }
+ Console.WriteLine(char.IsLetter(ch)); // False
+ Console.WriteLine(char.IsLetter("sample string", 7)); // True
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs b/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
index 3a8fde0049b..253d41e3f6f 100644
--- a/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
+++ b/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsLetterOrDigitSample {
- public static void Main() {
- string str = "newline:\n";
+public class IsLetterOrDigitSample
+{
+ public static void Main()
+ {
+ string str = "newline:\n";
- Console.WriteLine(Char.IsLetterOrDigit('8')); // Output: "True"
- Console.WriteLine(Char.IsLetterOrDigit(str, 8)); // Output: "False", because it's a newline
- }
+ Console.WriteLine(char.IsLetterOrDigit('8')); // Output: "True"
+ Console.WriteLine(char.IsLetterOrDigit(str, 8)); // Output: "False", because it's a newline
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsLower/islower.cs b/snippets/csharp/System/Char/IsLower/islower.cs
index 67e7dbb06a6..b2a20399d04 100644
--- a/snippets/csharp/System/Char/IsLower/islower.cs
+++ b/snippets/csharp/System/Char/IsLower/islower.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsLowerSample {
- public static void Main() {
- char ch = 'a';
+public class IsLowerSample
+{
+ public static void Main()
+ {
+ char ch = 'a';
- Console.WriteLine(Char.IsLower(ch)); // Output: "True"
- Console.WriteLine(Char.IsLower("upperCase", 5)); // Output: "False"
- }
+ Console.WriteLine(char.IsLower(ch)); // Output: "True"
+ Console.WriteLine(char.IsLower("upperCase", 5)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsNumber/isnumber.cs b/snippets/csharp/System/Char/IsNumber/isnumber.cs
index b55268e15bc..2e0babb2655 100644
--- a/snippets/csharp/System/Char/IsNumber/isnumber.cs
+++ b/snippets/csharp/System/Char/IsNumber/isnumber.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsNumberSample {
- public static void Main() {
- string str = "non-numeric";
+public class IsNumberSample
+{
+ public static void Main()
+ {
+ string str = "non-numeric";
- Console.WriteLine(Char.IsNumber('8')); // Output: "True"
- Console.WriteLine(Char.IsNumber(str, 3)); // Output: "False"
- }
+ Console.WriteLine(char.IsNumber('8')); // Output: "True"
+ Console.WriteLine(char.IsNumber(str, 3)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsNumber/isnumber1.cs b/snippets/csharp/System/Char/IsNumber/isnumber1.cs
index cf24e3795b1..1d8bce01820 100644
--- a/snippets/csharp/System/Char/IsNumber/isnumber1.cs
+++ b/snippets/csharp/System/Char/IsNumber/isnumber1.cs
@@ -2,40 +2,37 @@
public class Example
{
- public static void Main()
- {
- Overload1();
- Console.WriteLine();
- Overload2();
- }
+ public static void Main()
+ {
+ Overload1();
+ Console.WriteLine();
+ Overload2();
+ }
- private static void Overload1()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = Char.ConvertFromUtf32(utf32);
- foreach (var ch in surrogate)
- Console.WriteLine("U+{0:X4}: {1}", Convert.ToUInt16(ch),
- Char.IsNumber(ch));
+ private static void Overload1()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = char.ConvertFromUtf32(utf32);
+ foreach (char ch in surrogate)
+ Console.WriteLine($"U+{Convert.ToUInt16(ch):X4}: {char.IsNumber(ch)}");
- // The example displays the following output:
- // U+D800: False
- // U+DD07: False
- //
- }
+ // The example displays the following output:
+ // U+D800: False
+ // U+DD07: False
+ //
+ }
- private static void Overload2()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = Char.ConvertFromUtf32(utf32);
- for (int ctr = 0; ctr < surrogate.Length; ctr++)
- Console.WriteLine("U+{0:X4} at position {1}: {2}",
- Convert.ToUInt16(surrogate[ctr]), ctr,
- Char.IsNumber(surrogate, ctr));
- // The example displays the following output:
- // U+D800 at position 0: True
- // U+DD07 at position 1: False
- //
- }
+ private static void Overload2()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = char.ConvertFromUtf32(utf32);
+ for (int ctr = 0; ctr < surrogate.Length; ctr++)
+ Console.WriteLine($"U+{Convert.ToUInt16(surrogate[ctr]):X4} at position {ctr}: {char.IsNumber(surrogate, ctr)}");
+ // The example displays the following output:
+ // U+D800 at position 0: True
+ // U+DD07 at position 1: False
+ //
+ }
}
diff --git a/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs b/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
index 4b4f667495c..79c08f161d3 100644
--- a/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
+++ b/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsPunctuationSample {
- public static void Main() {
- char ch = '.';
+public class IsPunctuationSample
+{
+ public static void Main()
+ {
+ char ch = '.';
- Console.WriteLine(Char.IsPunctuation(ch)); // Output: "True"
- Console.WriteLine(Char.IsPunctuation("no punctuation", 3)); // Output: "False"
- }
+ Console.WriteLine(char.IsPunctuation(ch)); // Output: "True"
+ Console.WriteLine(char.IsPunctuation("no punctuation", 3)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSeparator/isseparator.cs b/snippets/csharp/System/Char/IsSeparator/isseparator.cs
index ccac637ab6d..1186c007265 100644
--- a/snippets/csharp/System/Char/IsSeparator/isseparator.cs
+++ b/snippets/csharp/System/Char/IsSeparator/isseparator.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsSeparatorSample {
- public static void Main() {
- string str = "twain1 twain2";
+public class IsSeparatorSample
+{
+ public static void Main()
+ {
+ string str = "twain1 twain2";
- Console.WriteLine(Char.IsSeparator('a')); // Output: "False"
- Console.WriteLine(Char.IsSeparator(str, 6)); // Output: "True"
- }
+ Console.WriteLine(char.IsSeparator('a')); // Output: "False"
+ Console.WriteLine(char.IsSeparator(str, 6)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
index c33c9f9591a..353def1fcf6 100644
--- a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
+++ b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
@@ -3,15 +3,15 @@
public class Class1
{
- public static void Main()
- {
- for (int ctr = (int)(Char.MinValue); ctr <= (int)(Char.MaxValue); ctr++)
- {
- char ch = (Char)ctr;
- if (Char.IsSeparator(ch))
- Console.WriteLine(@"\u{(int)ch:X4} ({Char.GetUnicodeCategory(ch)})");
- }
- }
+ public static void Main()
+ {
+ for (int ctr = (int)(char.MinValue); ctr <= (int)(char.MaxValue); ctr++)
+ {
+ char ch = (char)ctr;
+ if (char.IsSeparator(ch))
+ Console.WriteLine(@"\u{(int)ch:X4} ({Char.GetUnicodeCategory(ch)})");
+ }
+ }
}
// The example displays the following output:
// \u0020 (SpaceSeparator)
diff --git a/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs b/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
index 362be515197..c9db1db5d34 100644
--- a/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
+++ b/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsSurrogateSample {
- public static void Main() {
- string str = "\U00010F00"; // Unicode values between 0x10000 and 0x10FFF are represented by two 16-bit "surrogate" characters
+public class IsSurrogateSample
+{
+ public static void Main()
+ {
+ string str = "\U00010F00"; // Unicode values between 0x10000 and 0x10FFF are represented by two 16-bit "surrogate" characters
- Console.WriteLine(Char.IsSurrogate('a')); // Output: "False"
- Console.WriteLine(Char.IsSurrogate(str, 0)); // Output: "True"
- }
+ Console.WriteLine(char.IsSurrogate('a')); // Output: "False"
+ Console.WriteLine(char.IsSurrogate(str, 0)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSymbol/issymbol.cs b/snippets/csharp/System/Char/IsSymbol/issymbol.cs
index 745c2f40be8..6bd6a86d3ab 100644
--- a/snippets/csharp/System/Char/IsSymbol/issymbol.cs
+++ b/snippets/csharp/System/Char/IsSymbol/issymbol.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsSymbolSample {
- public static void Main() {
- string str = "non-symbolic characters";
+public class IsSymbolSample
+{
+ public static void Main()
+ {
+ string str = "non-symbolic characters";
- Console.WriteLine(Char.IsSymbol('+')); // Output: "True"
- Console.WriteLine(Char.IsSymbol(str, 8)); // Output: "False"
- }
+ Console.WriteLine(char.IsSymbol('+')); // Output: "True"
+ Console.WriteLine(char.IsSymbol(str, 8)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs b/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
index 2ababcb4773..ed9b5f0672a 100644
--- a/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
+++ b/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
@@ -1,12 +1,14 @@
//
using System;
-public class IsWhiteSpaceSample {
- public static void Main() {
- string str = "black matter";
+public class IsWhiteSpaceSample
+{
+ public static void Main()
+ {
+ string str = "black matter";
- Console.WriteLine(Char.IsWhiteSpace('A')); // Output: "False"
- Console.WriteLine(Char.IsWhiteSpace(str, 5)); // Output: "True"
- }
+ Console.WriteLine(char.IsWhiteSpace('A')); // Output: "False"
+ Console.WriteLine(char.IsWhiteSpace(str, 5)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs b/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
index a41456fc514..ff560ccd03c 100644
--- a/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
+++ b/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
@@ -1,17 +1,17 @@
-//
+//
using System;
-using System.Globalization;
+
class Example
{
- public static void Main()
- {
- // Define a string with a variety of character categories.
- String s = "The red car drove down the long, narrow, secluded road.";
- // Determine the category of each character.
- foreach (var ch in s)
- Console.WriteLine($"'{ch}': {Char.GetUnicodeCategory(ch)}");
- }
+ public static void Main()
+ {
+ // Define a string with a variety of character categories.
+ string s = "The red car drove down the long, narrow, secluded road.";
+ // Determine the category of each character.
+ foreach (char ch in s)
+ Console.WriteLine($"'{ch}': {char.GetUnicodeCategory(ch)}");
+ }
}
// The example displays the following output:
// 'T': UppercaseLetter
diff --git a/snippets/csharp/System/Char/Overview/charstructure.cs b/snippets/csharp/System/Char/Overview/charstructure.cs
index 8b5600d535c..687a9e23d21 100644
--- a/snippets/csharp/System/Char/Overview/charstructure.cs
+++ b/snippets/csharp/System/Char/Overview/charstructure.cs
@@ -11,18 +11,18 @@ public static void Main()
Console.WriteLine(chA.CompareTo('B')); //----------- Output: "-1" (meaning 'A' is 1 less than 'B')
Console.WriteLine(chA.Equals('A')); //----------- Output: "True"
- Console.WriteLine(Char.GetNumericValue(ch1)); //----------- Output: "1"
- Console.WriteLine(Char.IsControl('\t')); //----------- Output: "True"
- Console.WriteLine(Char.IsDigit(ch1)); //----------- Output: "True"
- Console.WriteLine(Char.IsLetter(',')); //----------- Output: "False"
- Console.WriteLine(Char.IsLower('u')); //----------- Output: "True"
- Console.WriteLine(Char.IsNumber(ch1)); //----------- Output: "True"
- Console.WriteLine(Char.IsPunctuation('.')); //----------- Output: "True"
- Console.WriteLine(Char.IsSeparator(str, 4)); //----------- Output: "True"
- Console.WriteLine(Char.IsSymbol('+')); //----------- Output: "True"
- Console.WriteLine(Char.IsWhiteSpace(str, 4)); //----------- Output: "True"
- Console.WriteLine(Char.Parse("S")); //----------- Output: "S"
- Console.WriteLine(Char.ToLower('M')); //----------- Output: "m"
+ Console.WriteLine(char.GetNumericValue(ch1)); //----------- Output: "1"
+ Console.WriteLine(char.IsControl('\t')); //----------- Output: "True"
+ Console.WriteLine(char.IsDigit(ch1)); //----------- Output: "True"
+ Console.WriteLine(char.IsLetter(',')); //----------- Output: "False"
+ Console.WriteLine(char.IsLower('u')); //----------- Output: "True"
+ Console.WriteLine(char.IsNumber(ch1)); //----------- Output: "True"
+ Console.WriteLine(char.IsPunctuation('.')); //----------- Output: "True"
+ Console.WriteLine(char.IsSeparator(str, 4)); //----------- Output: "True"
+ Console.WriteLine(char.IsSymbol('+')); //----------- Output: "True"
+ Console.WriteLine(char.IsWhiteSpace(str, 4)); //----------- Output: "True"
+ Console.WriteLine(char.Parse("S")); //----------- Output: "S"
+ Console.WriteLine(char.ToLower('M')); //----------- Output: "m"
Console.WriteLine('x'.ToString()); //----------- Output: "x"
}
}
diff --git a/snippets/csharp/System/Char/Overview/grapheme1.cs b/snippets/csharp/System/Char/Overview/grapheme1.cs
index 3282858b551..c426d21bad8 100644
--- a/snippets/csharp/System/Char/Overview/grapheme1.cs
+++ b/snippets/csharp/System/Char/Overview/grapheme1.cs
@@ -6,9 +6,9 @@ public class Example1
{
public static void Main()
{
- StreamWriter sw = new StreamWriter("chars1.txt");
- char[] chars = [ '\u0061', '\u0308' ];
- string strng = new String(chars);
+ StreamWriter sw = new("chars1.txt");
+ char[] chars = ['\u0061', '\u0308'];
+ string strng = new(chars);
sw.WriteLine(strng);
sw.Close();
}
diff --git a/snippets/csharp/System/Char/Overview/surrogate1.cs b/snippets/csharp/System/Char/Overview/surrogate1.cs
index 767c0443120..71088e4bdf4 100644
--- a/snippets/csharp/System/Char/Overview/surrogate1.cs
+++ b/snippets/csharp/System/Char/Overview/surrogate1.cs
@@ -6,9 +6,9 @@ public class Example3
{
public static void Main()
{
- StreamWriter sw = new StreamWriter(@".\chars2.txt");
+ StreamWriter sw = new(@".\chars2.txt");
int utf32 = 0x1D160;
- string surrogate = Char.ConvertFromUtf32(utf32);
+ string surrogate = char.ConvertFromUtf32(utf32);
sw.WriteLine($"U+{utf32:X6} UTF-32 = {surrogate} ({ShowCodePoints(surrogate)}) UTF-16");
sw.Close();
}
@@ -16,7 +16,7 @@ public static void Main()
private static string ShowCodePoints(string value)
{
string retval = null;
- foreach (var ch in value)
+ foreach (char ch in value)
retval += $"U+{Convert.ToUInt16(ch):X4} ";
return retval.Trim();
diff --git a/snippets/csharp/System/Char/Overview/textelements2.cs b/snippets/csharp/System/Char/Overview/textelements2.cs
index c039c618373..bddc5de6457 100644
--- a/snippets/csharp/System/Char/Overview/textelements2.cs
+++ b/snippets/csharp/System/Char/Overview/textelements2.cs
@@ -1,13 +1,13 @@
-//
+//
using System;
public class Example5
{
public static void Main()
{
- string result = String.Empty;
+ string result = string.Empty;
for (int ctr = 0x10107; ctr <= 0x10110; ctr++) // Range of Aegean numbers.
- result += Char.ConvertFromUtf32(ctr);
+ result += char.ConvertFromUtf32(ctr);
Console.WriteLine($"The string contains {result.Length} characters.");
}
diff --git a/snippets/csharp/System/Char/Overview/textelements2a.cs b/snippets/csharp/System/Char/Overview/textelements2a.cs
index e6bcb56f7d7..467714bae69 100644
--- a/snippets/csharp/System/Char/Overview/textelements2a.cs
+++ b/snippets/csharp/System/Char/Overview/textelements2a.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using System.Globalization;
@@ -6,11 +6,11 @@ public class Example4
{
public static void Main()
{
- string result = String.Empty;
+ string result = string.Empty;
for (int ctr = 0x10107; ctr <= 0x10110; ctr++) // Range of Aegean numbers.
- result += Char.ConvertFromUtf32(ctr);
+ result += char.ConvertFromUtf32(ctr);
- StringInfo si = new StringInfo(result);
+ StringInfo si = new(result);
Console.WriteLine($"The string contains {si.LengthInTextElements} characters.");
}
}
diff --git a/snippets/csharp/System/Char/Parse/parse.cs b/snippets/csharp/System/Char/Parse/parse.cs
index f7d5733e55d..98a492d3653 100644
--- a/snippets/csharp/System/Char/Parse/parse.cs
+++ b/snippets/csharp/System/Char/Parse/parse.cs
@@ -1,9 +1,11 @@
//
using System;
-public class ParseSample {
- public static void Main() {
- Console.WriteLine(Char.Parse("A")); // Output: 'A'
- }
+public class ParseSample
+{
+ public static void Main()
+ {
+ Console.WriteLine(char.Parse("A")); // Output: 'A'
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToLower/tolower.cs b/snippets/csharp/System/Char/ToLower/tolower.cs
index 11cfa4604d9..3507a0514f9 100644
--- a/snippets/csharp/System/Char/ToLower/tolower.cs
+++ b/snippets/csharp/System/Char/ToLower/tolower.cs
@@ -1,10 +1,12 @@
//
using System;
-using System.Globalization;
-public class ToLowerSample {
- public static void Main() {
- Console.WriteLine(Char.ToLower('A')); // Output: "a"
- }
+
+public class ToLowerSample
+{
+ public static void Main()
+ {
+ Console.WriteLine(char.ToLower('A')); // Output: "a"
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToString/tostring.cs b/snippets/csharp/System/Char/ToString/tostring.cs
index 2f8456a8f81..1d1c0a6d7b5 100644
--- a/snippets/csharp/System/Char/ToString/tostring.cs
+++ b/snippets/csharp/System/Char/ToString/tostring.cs
@@ -1,12 +1,14 @@
//
using System;
-public class ToStringSample {
- public static void Main() {
- char ch = 'a';
- Console.WriteLine(ch.ToString()); // Output: "a"
+public class ToStringSample
+{
+ public static void Main()
+ {
+ char ch = 'a';
+ Console.WriteLine(ch.ToString()); // Output: "a"
- Console.WriteLine(Char.ToString('b')); // Output: "b"
- }
+ Console.WriteLine(char.ToString('b')); // Output: "b"
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToUpper/toupper1.cs b/snippets/csharp/System/Char/ToUpper/toupper1.cs
index e37a5aad0ba..abd6696dea2 100644
--- a/snippets/csharp/System/Char/ToUpper/toupper1.cs
+++ b/snippets/csharp/System/Char/ToUpper/toupper1.cs
@@ -3,13 +3,12 @@
public class Example
{
- public static void Main()
- {
- char[] chars = { 'e', 'E', '6', ',', 'ж', 'ä' };
- foreach (var ch in chars)
- Console.WriteLine("{0} --> {1} {2}", ch, Char.ToUpper(ch),
- ch == Char.ToUpper(ch) ? "(Same Character)" : "" );
- }
+ public static void Main()
+ {
+ char[] chars = { 'e', 'E', '6', ',', 'ж', 'ä' };
+ foreach (char ch in chars)
+ Console.WriteLine($"{ch} --> {char.ToUpper(ch)} {(ch == char.ToUpper(ch) ? "(Same Character)" : "")}");
+ }
}
// The example displays the following output:
// e --> E
diff --git a/snippets/csharp/System/Char/ToUpper/toupper5.cs b/snippets/csharp/System/Char/ToUpper/toupper5.cs
index f42420da25f..d2079357a6a 100644
--- a/snippets/csharp/System/Char/ToUpper/toupper5.cs
+++ b/snippets/csharp/System/Char/ToUpper/toupper5.cs
@@ -4,22 +4,23 @@
public class Example
{
- public static void Main()
- {
- CultureInfo[] cultures= { CultureInfo.CreateSpecificCulture("en-US"),
+ public static void Main()
+ {
+ CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.InvariantCulture,
CultureInfo.CreateSpecificCulture("tr-TR") };
- Char[] chars = {'ä', 'e', 'E', 'i', 'I' };
+ char[] chars = { 'ä', 'e', 'E', 'i', 'I' };
- Console.WriteLine("Character en-US Invariant tr-TR");
- foreach (var ch in chars) {
- Console.Write(" {0}", ch);
- foreach (var culture in cultures)
- Console.Write("{0,12}", Char.ToUpper(ch, culture));
+ Console.WriteLine("Character en-US Invariant tr-TR");
+ foreach (char ch in chars)
+ {
+ Console.Write($" {ch}");
+ foreach (var culture in cultures)
+ Console.Write($"{char.ToUpper(ch, culture),12}");
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Character en-US Invariant tr-TR
@@ -28,4 +29,4 @@ public static void Main()
// E E E E
// i I I İ
// I I I I
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Char/TryParse/tp.cs b/snippets/csharp/System/Char/TryParse/tp.cs
index 09410a90088..6c9a8695466 100644
--- a/snippets/csharp/System/Char/TryParse/tp.cs
+++ b/snippets/csharp/System/Char/TryParse/tp.cs
@@ -16,132 +16,132 @@ class Sample
{
public static void Main()
{
- bool success;
- CultureInfo ci;
- string nl = Environment.NewLine;
- string msg1 =
- "This example demonstrates overloads of the TryParse method for{0}" +
- "several base types, as well as the TryParseExact method for DateTime.{0}";
- string msg2 = "Non-numeric types:{0}";
- string msg3 = "{0}Numeric types:{0}";
- string msg4 = "{0}The following types are not CLS-compliant:{0}";
-
-// Non-numeric types.
- Boolean booleanVal;
- Char charVal;
- DateTime datetimeVal;
-
-// Numeric types.
- Byte byteVal;
- Int16 int16Val;
- Int32 int32Val;
- Int64 int64Val;
- Decimal decimalVal;
- Single singleVal;
- Double doubleVal;
-
-// The following types are not CLS-compliant.
- SByte sbyteVal;
- UInt16 uint16Val;
- UInt32 uint32Val;
- UInt64 uint64Val;
-//
- Console.WriteLine(msg1, nl);
-
-// Non-numeric types:
- Console.WriteLine(msg2, nl);
-// DateTime
- // TryParse:
- // Assume current culture is en-US, and dates of the form: MMDDYYYY.
- success = DateTime.TryParse("7/4/2004 12:34:56", out datetimeVal);
- Show(success, "DateTime #1", datetimeVal.ToString());
-
- // Use fr-FR culture, and dates of the form: DDMMYYYY.
- ci = new CultureInfo("fr-FR");
- success = DateTime.TryParse("4/7/2004 12:34:56",
- ci, DateTimeStyles.None, out datetimeVal);
- Show(success, "DateTime #2", datetimeVal.ToString());
-
- // TryParseExact:
- // Use fr-FR culture. The format, "G", is short date and long time.
- success = DateTime.TryParseExact("04/07/2004 12:34:56", "G",
- ci, DateTimeStyles.None, out datetimeVal);
- Show(success, "DateTime #3", datetimeVal.ToString());
-
- // Assume en-US culture.
- string[] dateFormats = {"f", "F", "g", "G"};
- success = DateTime.TryParseExact("7/4/2004 12:34:56 PM",
- dateFormats, null, DateTimeStyles.None,
- out datetimeVal);
- Show(success, "DateTime #4", datetimeVal.ToString());
-
- Console.WriteLine();
-// Boolean
- success = Boolean.TryParse("true", out booleanVal);
- Show(success, "Boolean", booleanVal.ToString());
-// Char
- success = Char.TryParse("A", out charVal);
- Show(success, "Char", charVal.ToString());
-
-// Numeric types:
- Console.WriteLine(msg3, nl);
-// Byte
- success = Byte.TryParse("1", NumberStyles.Integer, null, out byteVal);
- Show(success, "Byte", byteVal.ToString());
-// Int16
- success = Int16.TryParse("-2", NumberStyles.Integer, null, out int16Val);
- Show(success, "Int16", int16Val.ToString());
-// Int32
- success = Int32.TryParse("3", NumberStyles.Integer, null, out int32Val);
- Show(success, "Int32", int32Val.ToString());
-// Int64
- success = Int64.TryParse("4", NumberStyles.Integer, null, out int64Val);
- Show(success, "Int64", int64Val.ToString());
-// Decimal
- success = Decimal.TryParse("-5.5", NumberStyles.Number, null, out decimalVal);
- Show(success, "Decimal", decimalVal.ToString());
-// Single
- success = Single.TryParse("6.6",
- (NumberStyles.Float | NumberStyles.AllowThousands),
- null, out singleVal);
- Show(success, "Single", singleVal.ToString());
-// Double
- success = Double.TryParse("-7",
- (NumberStyles.Float | NumberStyles.AllowThousands),
- null, out doubleVal);
- Show(success, "Double", doubleVal.ToString());
-
-// Use the simple Double.TryParse overload, but specify an invalid value.
-
- success = Double.TryParse("abc", out doubleVal);
- Show(success, "Double #2", doubleVal.ToString());
-//
- Console.WriteLine(msg4, nl);
-// SByte
- success = SByte.TryParse("-8", NumberStyles.Integer, null, out sbyteVal);
- Show(success, "SByte", sbyteVal.ToString());
-// UInt16
- success = UInt16.TryParse("9", NumberStyles.Integer, null, out uint16Val);
- Show(success, "UInt16", uint16Val.ToString());
-// UInt32
- success = UInt32.TryParse("10", NumberStyles.Integer, null, out uint32Val);
- Show(success, "UInt32", uint32Val.ToString());
-// UInt64
- success = UInt64.TryParse("11", NumberStyles.Integer, null, out uint64Val);
- Show(success, "UInt64", uint64Val.ToString());
+ bool success;
+ CultureInfo ci;
+ string nl = Environment.NewLine;
+ string msg1 =
+ "This example demonstrates overloads of the TryParse method for{0}" +
+ "several base types, as well as the TryParseExact method for DateTime.{0}";
+ string msg2 = "Non-numeric types:{0}";
+ string msg3 = "{0}Numeric types:{0}";
+ string msg4 = "{0}The following types are not CLS-compliant:{0}";
+
+ // Non-numeric types.
+ bool booleanVal;
+ char charVal;
+ DateTime datetimeVal;
+
+ // Numeric types.
+ byte byteVal;
+ short int16Val;
+ int int32Val;
+ long int64Val;
+ decimal decimalVal;
+ float singleVal;
+ double doubleVal;
+
+ // The following types are not CLS-compliant.
+ sbyte sbyteVal;
+ ushort uint16Val;
+ uint uint32Val;
+ ulong uint64Val;
+ //
+ Console.WriteLine(msg1, nl);
+
+ // Non-numeric types:
+ Console.WriteLine(msg2, nl);
+ // DateTime
+ // TryParse:
+ // Assume current culture is en-US, and dates of the form: MMDDYYYY.
+ success = DateTime.TryParse("7/4/2004 12:34:56", out datetimeVal);
+ Show(success, "DateTime #1", datetimeVal.ToString());
+
+ // Use fr-FR culture, and dates of the form: DDMMYYYY.
+ ci = new("fr-FR");
+ success = DateTime.TryParse("4/7/2004 12:34:56",
+ ci, DateTimeStyles.None, out datetimeVal);
+ Show(success, "DateTime #2", datetimeVal.ToString());
+
+ // TryParseExact:
+ // Use fr-FR culture. The format, "G", is short date and long time.
+ success = DateTime.TryParseExact("04/07/2004 12:34:56", "G",
+ ci, DateTimeStyles.None, out datetimeVal);
+ Show(success, "DateTime #3", datetimeVal.ToString());
+
+ // Assume en-US culture.
+ string[] dateFormats = { "f", "F", "g", "G" };
+ success = DateTime.TryParseExact("7/4/2004 12:34:56 PM",
+ dateFormats, null, DateTimeStyles.None,
+ out datetimeVal);
+ Show(success, "DateTime #4", datetimeVal.ToString());
+
+ Console.WriteLine();
+ // Boolean
+ success = bool.TryParse("true", out booleanVal);
+ Show(success, "Boolean", booleanVal.ToString());
+ // Char
+ success = char.TryParse("A", out charVal);
+ Show(success, "Char", charVal.ToString());
+
+ // Numeric types:
+ Console.WriteLine(msg3, nl);
+ // Byte
+ success = byte.TryParse("1", NumberStyles.Integer, null, out byteVal);
+ Show(success, "Byte", byteVal.ToString());
+ // Int16
+ success = short.TryParse("-2", NumberStyles.Integer, null, out int16Val);
+ Show(success, "Int16", int16Val.ToString());
+ // Int32
+ success = int.TryParse("3", NumberStyles.Integer, null, out int32Val);
+ Show(success, "Int32", int32Val.ToString());
+ // Int64
+ success = long.TryParse("4", NumberStyles.Integer, null, out int64Val);
+ Show(success, "Int64", int64Val.ToString());
+ // Decimal
+ success = decimal.TryParse("-5.5", NumberStyles.Number, null, out decimalVal);
+ Show(success, "Decimal", decimalVal.ToString());
+ // Single
+ success = float.TryParse("6.6",
+ (NumberStyles.Float | NumberStyles.AllowThousands),
+ null, out singleVal);
+ Show(success, "Single", singleVal.ToString());
+ // Double
+ success = double.TryParse("-7",
+ (NumberStyles.Float | NumberStyles.AllowThousands),
+ null, out doubleVal);
+ Show(success, "Double", doubleVal.ToString());
+
+ // Use the simple Double.TryParse overload, but specify an invalid value.
+
+ success = double.TryParse("abc", out doubleVal);
+ Show(success, "Double #2", doubleVal.ToString());
+ //
+ Console.WriteLine(msg4, nl);
+ // SByte
+ success = sbyte.TryParse("-8", NumberStyles.Integer, null, out sbyteVal);
+ Show(success, "SByte", sbyteVal.ToString());
+ // UInt16
+ success = ushort.TryParse("9", NumberStyles.Integer, null, out uint16Val);
+ Show(success, "UInt16", uint16Val.ToString());
+ // UInt32
+ success = uint.TryParse("10", NumberStyles.Integer, null, out uint32Val);
+ Show(success, "UInt32", uint32Val.ToString());
+ // UInt64
+ success = ulong.TryParse("11", NumberStyles.Integer, null, out uint64Val);
+ Show(success, "UInt64", uint64Val.ToString());
}
protected static void Show(bool parseSuccess, string typeName,
string parseValue)
{
- string msgSuccess = "Parse for {0} = {1}";
- string msgFailure = "** Parse for {0} failed. Invalid input.";
-//
- if (parseSuccess )
- Console.WriteLine(msgSuccess, typeName, parseValue);
- else
- Console.WriteLine(msgFailure, typeName);
- }
+ string msgSuccess = "Parse for {0} = {1}";
+ string msgFailure = "** Parse for {0} failed. Invalid input.";
+ //
+ if (parseSuccess)
+ Console.WriteLine(msgSuccess, typeName, parseValue);
+ else
+ Console.WriteLine(msgFailure, typeName);
+ }
}
/*
This example produces the following results:
diff --git a/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs b/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
index f1cdd898f25..fc8b67530b4 100644
--- a/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
+++ b/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
@@ -2,71 +2,69 @@
public class Class1
{
- public static void Main()
- {
- UseCharEnumerator();
- Console.WriteLine("-----");
- UseForEach();
- }
+ public static void Main()
+ {
+ UseCharEnumerator();
+ Console.WriteLine("-----");
+ UseForEach();
+ }
- private static void UseCharEnumerator()
- {
- //
- string title = "A Tale of Two Cities";
- CharEnumerator chEnum = title.GetEnumerator();
- int ctr = 1;
- string outputLine1 = null;
- string outputLine2 = null;
- string outputLine3 = null;
+ private static void UseCharEnumerator()
+ {
+ //
+ string title = "A Tale of Two Cities";
+ CharEnumerator chEnum = title.GetEnumerator();
+ int ctr = 1;
+ string outputLine1 = null;
+ string outputLine2 = null;
+ string outputLine3 = null;
- while (chEnum.MoveNext())
- {
- outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
- outputLine2 += (ctr % 10) + " ";
- outputLine3 += chEnum.Current + " ";
- ctr++;
- }
+ while (chEnum.MoveNext())
+ {
+ outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
+ outputLine2 += (ctr % 10) + " ";
+ outputLine3 += chEnum.Current + " ";
+ ctr++;
+ }
- Console.WriteLine("The length of the string is {0} characters:",
- title.Length);
- Console.WriteLine(outputLine1);
- Console.WriteLine(outputLine2);
- Console.WriteLine(outputLine3);
- // The example displays the following output to the console:
- // The length of the string is 20 characters:
- // 1 2
- // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
- // A T a l e o f T w o C i t i e s
- //
- }
+ Console.WriteLine($"The length of the string is {title.Length} characters:");
+ Console.WriteLine(outputLine1);
+ Console.WriteLine(outputLine2);
+ Console.WriteLine(outputLine3);
+ // The example displays the following output to the console:
+ // The length of the string is 20 characters:
+ // 1 2
+ // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
+ // A T a l e o f T w o C i t i e s
+ //
+ }
- private static void UseForEach()
- {
- //
- string title = "A Tale of Two Cities";
- int ctr = 1;
- string outputLine1 = null;
- string outputLine2 = null;
- string outputLine3 = null;
+ private static void UseForEach()
+ {
+ //
+ string title = "A Tale of Two Cities";
+ int ctr = 1;
+ string outputLine1 = null;
+ string outputLine2 = null;
+ string outputLine3 = null;
- foreach (char ch in title)
- {
- outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
- outputLine2 += (ctr % 10) + " ";
- outputLine3 += ch + " ";
- ctr++;
- }
+ foreach (char ch in title)
+ {
+ outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
+ outputLine2 += (ctr % 10) + " ";
+ outputLine3 += ch + " ";
+ ctr++;
+ }
- Console.WriteLine("The length of the string is {0} characters:",
- title.Length);
- Console.WriteLine(outputLine1);
- Console.WriteLine(outputLine2);
- Console.WriteLine(outputLine3);
- // The example displays the following output to the console:
- // The length of the string is 20 characters:
- // 1 2
- // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
- // A T a l e o f T w o C i t i e s
- //
- }
+ Console.WriteLine($"The length of the string is {title.Length} characters:");
+ Console.WriteLine(outputLine1);
+ Console.WriteLine(outputLine2);
+ Console.WriteLine(outputLine3);
+ // The example displays the following output to the console:
+ // The length of the string is 20 characters:
+ // 1 2
+ // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
+ // A T a l e o f T w o C i t i e s
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/BackgroundColor/Example2.cs b/snippets/csharp/System/Console/BackgroundColor/Example2.cs
index 93af82b7407..4ed1d70b2e2 100644
--- a/snippets/csharp/System/Console/BackgroundColor/Example2.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/Example2.cs
@@ -3,13 +3,14 @@
public class Example
{
- public static void Main()
- {
- if (Console.BackgroundColor == ConsoleColor.Black) {
- Console.BackgroundColor = ConsoleColor.Red;
- Console.ForegroundColor = ConsoleColor.Black;
- Console.Clear();
- }
- }
+ public static void Main()
+ {
+ if (Console.BackgroundColor == ConsoleColor.Black)
+ {
+ Console.BackgroundColor = ConsoleColor.Red;
+ Console.ForegroundColor = ConsoleColor.Black;
+ Console.Clear();
+ }
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs b/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
index bd79ec6e0d4..4e3573448b3 100644
--- a/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
@@ -3,28 +3,29 @@
public class Example
{
- public static void Main()
- {
- WriteCharacterStrings(1, 26, true);
- Console.MoveBufferArea(0, Console.CursorTop - 10, 30, 1,
- Console.CursorLeft, Console.CursorTop + 1);
- Console.CursorTop = Console.CursorTop + 3;
- Console.WriteLine("Press any key...");
- Console.ReadKey();
+ public static void Main()
+ {
+ WriteCharacterStrings(1, 26, true);
+ Console.MoveBufferArea(0, Console.CursorTop - 10, 30, 1,
+ Console.CursorLeft, Console.CursorTop + 1);
+ Console.CursorTop = Console.CursorTop + 3;
+ Console.WriteLine("Press any key...");
+ Console.ReadKey();
- Console.Clear();
- WriteCharacterStrings(1, 26, false);
- }
+ Console.Clear();
+ WriteCharacterStrings(1, 26, false);
+ }
- private static void WriteCharacterStrings(int start, int end,
- bool changeColor)
- {
- for (int ctr = start; ctr <= end; ctr++) {
- if (changeColor)
- Console.BackgroundColor = (ConsoleColor) ((ctr - 1) % 16);
+ private static void WriteCharacterStrings(int start, int end,
+ bool changeColor)
+ {
+ for (int ctr = start; ctr <= end; ctr++)
+ {
+ if (changeColor)
+ Console.BackgroundColor = (ConsoleColor)((ctr - 1) % 16);
- Console.WriteLine(new String((char)(ctr + 64), 30));
- }
- }
+ Console.WriteLine(new string((char)(ctr + 64), 30));
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs b/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
index 107b7e78c64..f651b63ca00 100644
--- a/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
@@ -3,41 +3,41 @@
class Example
{
- public static void Main()
- {
- // Get an array with the values of ConsoleColor enumeration members.
- ConsoleColor[] colors = (ConsoleColor[]) ConsoleColor.GetValues(typeof(ConsoleColor));
- // Save the current background and foreground colors.
- ConsoleColor currentBackground = Console.BackgroundColor;
- ConsoleColor currentForeground = Console.ForegroundColor;
+ public static void Main()
+ {
+ // Get an array with the values of ConsoleColor enumeration members.
+ ConsoleColor[] colors = (ConsoleColor[])ConsoleColor.GetValues(typeof(ConsoleColor));
+ // Save the current background and foreground colors.
+ ConsoleColor currentBackground = Console.BackgroundColor;
+ ConsoleColor currentForeground = Console.ForegroundColor;
- // Display all foreground colors except the one that matches the background.
- Console.WriteLine("All the foreground colors except {0}, the background color:",
- currentBackground);
- foreach (var color in colors) {
- if (color == currentBackground) continue;
+ // Display all foreground colors except the one that matches the background.
+ Console.WriteLine($"All the foreground colors except {currentBackground}, the background color:");
+ foreach (var color in colors)
+ {
+ if (color == currentBackground) continue;
- Console.ForegroundColor = color;
- Console.WriteLine(" The foreground color is {0}.", color);
- }
- Console.WriteLine();
- // Restore the foreground color.
- Console.ForegroundColor = currentForeground;
+ Console.ForegroundColor = color;
+ Console.WriteLine($" The foreground color is {color}.");
+ }
+ Console.WriteLine();
+ // Restore the foreground color.
+ Console.ForegroundColor = currentForeground;
- // Display each background color except the one that matches the current foreground color.
- Console.WriteLine("All the background colors except {0}, the foreground color:",
- currentForeground);
- foreach (var color in colors) {
- if (color == currentForeground) continue;
+ // Display each background color except the one that matches the current foreground color.
+ Console.WriteLine($"All the background colors except {currentForeground}, the foreground color:");
+ foreach (var color in colors)
+ {
+ if (color == currentForeground) continue;
- Console.BackgroundColor = color;
- Console.WriteLine(" The background color is {0}.", color);
- }
+ Console.BackgroundColor = color;
+ Console.WriteLine($" The background color is {color}.");
+ }
- // Restore the original console colors.
- Console.ResetColor();
- Console.WriteLine("\nOriginal colors restored...");
- }
+ // Restore the original console colors.
+ Console.ResetColor();
+ Console.WriteLine("\nOriginal colors restored...");
+ }
}
//The example displays output like the following:
// All the foreground colors except DarkCyan, the background color:
diff --git a/snippets/csharp/System/Console/Beep/b2.cs b/snippets/csharp/System/Console/Beep/b2.cs
index c5ff8c085b4..a7971078dba 100644
--- a/snippets/csharp/System/Console/Beep/b2.cs
+++ b/snippets/csharp/System/Console/Beep/b2.cs
@@ -7,9 +7,9 @@ class Sample
{
public static void Main()
{
-// Declare the first few notes of the song, "Mary Had A Little Lamb".
- Note[] Mary =
- {
+ // Declare the first few notes of the song, "Mary Had A Little Lamb".
+ Note[] Mary =
+ {
new Note(Tone.B, Duration.QUARTER),
new Note(Tone.A, Duration.QUARTER),
new Note(Tone.GbelowC, Duration.QUARTER),
@@ -24,69 +24,69 @@ public static void Main()
new Note(Tone.D, Duration.QUARTER),
new Note(Tone.D, Duration.HALF)
};
-// Play the song
- Play(Mary);
+ // Play the song
+ Play(Mary);
}
-// Play the notes in a song.
+ // Play the notes in a song.
protected static void Play(Note[] tune)
{
- foreach (Note n in tune)
+ foreach (Note n in tune)
{
- if (n.NoteTone == Tone.REST)
- Thread.Sleep((int)n.NoteDuration);
- else
- Console.Beep((int)n.NoteTone, (int)n.NoteDuration);
+ if (n.NoteTone == Tone.REST)
+ Thread.Sleep((int)n.NoteDuration);
+ else
+ Console.Beep((int)n.NoteTone, (int)n.NoteDuration);
}
}
-// Define the frequencies of notes in an octave, as well as
-// silence (rest).
+ // Define the frequencies of notes in an octave, as well as
+ // silence (rest).
protected enum Tone
{
- REST = 0,
- GbelowC = 196,
- A = 220,
- Asharp = 233,
- B = 247,
- C = 262,
- Csharp = 277,
- D = 294,
- Dsharp = 311,
- E = 330,
- F = 349,
- Fsharp = 370,
- G = 392,
- Gsharp = 415,
+ REST = 0,
+ GbelowC = 196,
+ A = 220,
+ Asharp = 233,
+ B = 247,
+ C = 262,
+ Csharp = 277,
+ D = 294,
+ Dsharp = 311,
+ E = 330,
+ F = 349,
+ Fsharp = 370,
+ G = 392,
+ Gsharp = 415,
}
-// Define the duration of a note in units of milliseconds.
+ // Define the duration of a note in units of milliseconds.
protected enum Duration
{
- WHOLE = 1600,
- HALF = WHOLE/2,
- QUARTER = HALF/2,
- EIGHTH = QUARTER/2,
- SIXTEENTH = EIGHTH/2,
+ WHOLE = 1600,
+ HALF = WHOLE / 2,
+ QUARTER = HALF / 2,
+ EIGHTH = QUARTER / 2,
+ SIXTEENTH = EIGHTH / 2,
}
-// Define a note as a frequency (tone) and the amount of
-// time (duration) the note plays.
+ // Define a note as a frequency (tone) and the amount of
+ // time (duration) the note plays.
protected struct Note
{
- Tone toneVal;
- Duration durVal;
+ Tone toneVal;
+ Duration durVal;
-// Define a constructor to create a specific note.
- public Note(Tone frequency, Duration time)
+ // Define a constructor to create a specific note.
+ public Note(Tone frequency, Duration time)
{
- toneVal = frequency;
- durVal = time;
+ toneVal = frequency;
+ durVal = time;
}
-// Define properties to return the note's tone and duration.
- public Tone NoteTone { get{ return toneVal; } }
- public Duration NoteDuration { get{ return durVal; } }
+ // Define properties to return the note's tone and duration.
+ public Tone NoteTone => toneVal;
+ public Duration NoteDuration => durVal;
}
}
/*
@@ -95,4 +95,4 @@ public Note(Tone frequency, Duration time)
This example plays the first few notes of "Mary Had A Little Lamb"
through the console speaker.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/Beep/beep.cs b/snippets/csharp/System/Console/Beep/beep.cs
index 7dbfc5fbc16..cd7260caaf7 100644
--- a/snippets/csharp/System/Console/Beep/beep.cs
+++ b/snippets/csharp/System/Console/Beep/beep.cs
@@ -4,21 +4,21 @@
class Sample
{
- public static void Main(String[] args)
+ public static void Main(string[] args)
{
- int x = 0;
-//
- if ((args.Length == 1) &&
- (Int32.TryParse(args[0], out x)) &&
- ((x >= 1) && (x <= 9)))
+ int x = 0;
+ //
+ if ((args.Length == 1) &&
+ (int.TryParse(args[0], out x)) &&
+ ((x >= 1) && (x <= 9)))
{
- for (int i = 1; i <= x; i++)
+ for (int i = 1; i <= x; i++)
{
- Console.WriteLine("Beep number {0}.", i);
- Console.Beep();
+ Console.WriteLine($"Beep number {i}.");
+ Console.Beep();
}
}
- else
+ else
{
Console.WriteLine("Usage: Enter the number of times (between 1 and 9) to beep.");
}
@@ -42,4 +42,4 @@ Beep number 8.
Beep number 9.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/BufferHeight/hw.cs b/snippets/csharp/System/Console/BufferHeight/hw.cs
index a7494f02e0f..8eb4f0ed291 100644
--- a/snippets/csharp/System/Console/BufferHeight/hw.cs
+++ b/snippets/csharp/System/Console/BufferHeight/hw.cs
@@ -7,10 +7,8 @@ class Sample
{
public static void Main()
{
- Console.WriteLine("The current buffer height is {0} rows.",
- Console.BufferHeight);
- Console.WriteLine("The current buffer width is {0} columns.",
- Console.BufferWidth);
+ Console.WriteLine($"The current buffer height is {Console.BufferHeight} rows.");
+ Console.WriteLine($"The current buffer width is {Console.BufferWidth} columns.");
}
}
/*
@@ -19,4 +17,4 @@ public static void Main()
The current buffer height is 300 rows.
The current buffer width is 85 columns.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/CancelKeyPress/ckp.cs b/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
index dfe22b6d9f3..85990e0ffae 100644
--- a/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
+++ b/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
@@ -10,7 +10,7 @@ public static void Main()
Console.Clear();
// Establish an event handler to process key press events.
- Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
+ Console.CancelKeyPress += new(myHandler);
while (true)
{
Console.Write("Press any key, or 'X' to quit, or ");
diff --git a/snippets/csharp/System/Console/Clear/clear1.cs b/snippets/csharp/System/Console/Clear/clear1.cs
index ee3a91ec720..d1572e44d0d 100644
--- a/snippets/csharp/System/Console/Clear/clear1.cs
+++ b/snippets/csharp/System/Console/Clear/clear1.cs
@@ -3,83 +3,87 @@
public class Example
{
- public static void Main()
- {
- // Save colors so they can be restored when use finishes input.
- ConsoleColor dftForeColor = Console.ForegroundColor;
- ConsoleColor dftBackColor = Console.BackgroundColor;
- bool continueFlag = true;
- Console.Clear();
+ public static void Main()
+ {
+ // Save colors so they can be restored when use finishes input.
+ ConsoleColor dftForeColor = Console.ForegroundColor;
+ ConsoleColor dftBackColor = Console.BackgroundColor;
+ bool continueFlag = true;
+ Console.Clear();
- do {
- ConsoleColor newForeColor = ConsoleColor.White;
- ConsoleColor newBackColor = ConsoleColor.Black;
+ do
+ {
+ ConsoleColor newForeColor = ConsoleColor.White;
+ ConsoleColor newBackColor = ConsoleColor.Black;
- Char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ",
- new Char[] { 'B', 'R', 'Y' } );
- switch (foreColorSelection) {
- case 'B':
- case 'b':
- newForeColor = ConsoleColor.DarkBlue;
- break;
- case 'R':
- case 'r':
- newForeColor = ConsoleColor.DarkRed;
- break;
- case 'Y':
- case 'y':
- newForeColor = ConsoleColor.DarkYellow;
- break;
- }
- Char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
- new Char[] { 'W', 'G', 'M' });
- switch (backColorSelection) {
- case 'W':
- case 'w':
- newBackColor = ConsoleColor.White;
- break;
- case 'G':
- case 'g':
- newBackColor = ConsoleColor.Green;
- break;
- case 'M':
- case 'm':
- newBackColor = ConsoleColor.Magenta;
- break;
- }
+ char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ",
+ new char[] { 'B', 'R', 'Y' });
+ switch (foreColorSelection)
+ {
+ case 'B':
+ case 'b':
+ newForeColor = ConsoleColor.DarkBlue;
+ break;
+ case 'R':
+ case 'r':
+ newForeColor = ConsoleColor.DarkRed;
+ break;
+ case 'Y':
+ case 'y':
+ newForeColor = ConsoleColor.DarkYellow;
+ break;
+ }
+ char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
+ new char[] { 'W', 'G', 'M' });
+ switch (backColorSelection)
+ {
+ case 'W':
+ case 'w':
+ newBackColor = ConsoleColor.White;
+ break;
+ case 'G':
+ case 'g':
+ newBackColor = ConsoleColor.Green;
+ break;
+ case 'M':
+ case 'm':
+ newBackColor = ConsoleColor.Magenta;
+ break;
+ }
- Console.WriteLine();
- Console.Write("Enter a message to display: ");
- String textToDisplay = Console.ReadLine();
- Console.WriteLine();
- Console.ForegroundColor = newForeColor;
- Console.BackgroundColor = newBackColor;
- Console.WriteLine(textToDisplay);
- Console.WriteLine();
- if (Char.ToUpper(GetKeyPress("Display another message (Y/N): ", new Char[] { 'Y', 'N' } )) == 'N')
- continueFlag = false;
+ Console.WriteLine();
+ Console.Write("Enter a message to display: ");
+ string textToDisplay = Console.ReadLine();
+ Console.WriteLine();
+ Console.ForegroundColor = newForeColor;
+ Console.BackgroundColor = newBackColor;
+ Console.WriteLine(textToDisplay);
+ Console.WriteLine();
+ if (char.ToUpper(GetKeyPress("Display another message (Y/N): ", new char[] { 'Y', 'N' })) == 'N')
+ continueFlag = false;
- // Restore the default settings and clear the screen.
- Console.ForegroundColor = dftForeColor;
- Console.BackgroundColor = dftBackColor;
- Console.Clear();
- } while (continueFlag);
- }
+ // Restore the default settings and clear the screen.
+ Console.ForegroundColor = dftForeColor;
+ Console.BackgroundColor = dftBackColor;
+ Console.Clear();
+ } while (continueFlag);
+ }
- private static Char GetKeyPress(String msg, Char[] validChars)
- {
- ConsoleKeyInfo keyPressed;
- bool valid = false;
+ private static char GetKeyPress(string msg, char[] validChars)
+ {
+ ConsoleKeyInfo keyPressed;
+ bool valid = false;
- Console.WriteLine();
- do {
- Console.Write(msg);
- keyPressed = Console.ReadKey();
- Console.WriteLine();
- if (Array.Exists(validChars, ch => ch.Equals(Char.ToUpper(keyPressed.KeyChar))))
- valid = true;
- } while (!valid);
- return keyPressed.KeyChar;
- }
+ Console.WriteLine();
+ do
+ {
+ Console.Write(msg);
+ keyPressed = Console.ReadKey();
+ Console.WriteLine();
+ if (Array.Exists(validChars, ch => ch.Equals(char.ToUpper(keyPressed.KeyChar))))
+ valid = true;
+ } while (!valid);
+ return keyPressed.KeyChar;
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/Clear/lts.cs b/snippets/csharp/System/Console/Clear/lts.cs
index a9d328bf97c..3904927aa78 100644
--- a/snippets/csharp/System/Console/Clear/lts.cs
+++ b/snippets/csharp/System/Console/Clear/lts.cs
@@ -13,51 +13,51 @@ class Sample
protected static void WriteAt(string s, int x, int y)
{
- try
+ try
{
- Console.SetCursorPosition(origCol+x, origRow+y);
- Console.Write(s);
+ Console.SetCursorPosition(origCol + x, origRow + y);
+ Console.Write(s);
}
- catch (ArgumentOutOfRangeException e)
+ catch (ArgumentOutOfRangeException e)
{
- Console.Clear();
- Console.WriteLine(e.Message);
+ Console.Clear();
+ Console.WriteLine(e.Message);
}
}
public static void Main()
{
-// Clear the screen, then save the top and left coordinates.
- Console.Clear();
- origRow = Console.CursorTop;
- origCol = Console.CursorLeft;
+ // Clear the screen, then save the top and left coordinates.
+ Console.Clear();
+ origRow = Console.CursorTop;
+ origCol = Console.CursorLeft;
-// Draw the left side of a 5x5 rectangle, from top to bottom.
- WriteAt("+", 0, 0);
- WriteAt("|", 0, 1);
- WriteAt("|", 0, 2);
- WriteAt("|", 0, 3);
- WriteAt("+", 0, 4);
+ // Draw the left side of a 5x5 rectangle, from top to bottom.
+ WriteAt("+", 0, 0);
+ WriteAt("|", 0, 1);
+ WriteAt("|", 0, 2);
+ WriteAt("|", 0, 3);
+ WriteAt("+", 0, 4);
-// Draw the bottom side, from left to right.
- WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4)
- WriteAt("-", 2, 4); // ...
- WriteAt("-", 3, 4); // ...
- WriteAt("+", 4, 4);
+ // Draw the bottom side, from left to right.
+ WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4)
+ WriteAt("-", 2, 4); // ...
+ WriteAt("-", 3, 4); // ...
+ WriteAt("+", 4, 4);
-// Draw the right side, from bottom to top.
- WriteAt("|", 4, 3);
- WriteAt("|", 4, 2);
- WriteAt("|", 4, 1);
- WriteAt("+", 4, 0);
+ // Draw the right side, from bottom to top.
+ WriteAt("|", 4, 3);
+ WriteAt("|", 4, 2);
+ WriteAt("|", 4, 1);
+ WriteAt("+", 4, 0);
-// Draw the top side, from right to left.
- WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0)
- WriteAt("-", 2, 0); // ...
- WriteAt("-", 1, 0); // ...
-//
- WriteAt("All done!", 0, 6);
- Console.WriteLine();
+ // Draw the top side, from right to left.
+ WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0)
+ WriteAt("-", 2, 0); // ...
+ WriteAt("-", 1, 0); // ...
+ //
+ WriteAt("All done!", 0, 6);
+ Console.WriteLine();
}
}
/*
@@ -72,4 +72,4 @@ public static void Main()
All done!
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/CursorSize/csize.cs b/snippets/csharp/System/Console/CursorSize/csize.cs
index e50801352ea..174e821eb48 100644
--- a/snippets/csharp/System/Console/CursorSize/csize.cs
+++ b/snippets/csharp/System/Console/CursorSize/csize.cs
@@ -6,20 +6,20 @@ class Sample
{
public static void Main()
{
- string m0 = "This example increments the cursor size from 1% to 100%:\n";
- string m1 = "Cursor size = {0}%. (Press any key to continue...)";
- int[] sizes = {1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
- int saveCursorSize;
-//
- saveCursorSize = Console.CursorSize;
- Console.WriteLine(m0);
- foreach (int size in sizes)
+ string m0 = "This example increments the cursor size from 1% to 100%:\n";
+ string m1 = "Cursor size = {0}%. (Press any key to continue...)";
+ int[] sizes = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
+ int saveCursorSize;
+ //
+ saveCursorSize = Console.CursorSize;
+ Console.WriteLine(m0);
+ foreach (int size in sizes)
{
- Console.CursorSize = size;
- Console.WriteLine(m1, size);
- Console.ReadKey();
+ Console.CursorSize = size;
+ Console.WriteLine(m1, size);
+ Console.ReadKey();
}
- Console.CursorSize = saveCursorSize;
+ Console.CursorSize = saveCursorSize;
}
}
/*
@@ -40,4 +40,4 @@ public static void Main()
Cursor size = 100%. (Press any key to continue...)
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/CursorVisible/vis.cs b/snippets/csharp/System/Console/CursorVisible/vis.cs
index a03617a4af4..8544ba7ab39 100644
--- a/snippets/csharp/System/Console/CursorVisible/vis.cs
+++ b/snippets/csharp/System/Console/CursorVisible/vis.cs
@@ -7,35 +7,35 @@ class Sample
{
public static void Main()
{
- string m1 = "\nThe cursor is {0}.\nType any text then press Enter. " +
- "Type '+' in the first column to show \n" +
- "the cursor, '-' to hide the cursor, " +
- "or lowercase 'x' to quit:";
- string s;
- bool saveCursorVisibile;
- int saveCursorSize;
-//
- Console.CursorVisible = true; // Initialize the cursor to visible.
- saveCursorVisibile = Console.CursorVisible;
- saveCursorSize = Console.CursorSize;
- Console.CursorSize = 100; // Emphasize the cursor.
+ string m1 = "\nThe cursor is {0}.\nType any text then press Enter. " +
+ "Type '+' in the first column to show \n" +
+ "the cursor, '-' to hide the cursor, " +
+ "or lowercase 'x' to quit:";
+ string s;
+ bool saveCursorVisibile;
+ int saveCursorSize;
+ //
+ Console.CursorVisible = true; // Initialize the cursor to visible.
+ saveCursorVisibile = Console.CursorVisible;
+ saveCursorSize = Console.CursorSize;
+ Console.CursorSize = 100; // Emphasize the cursor.
- while(true)
+ while (true)
{
- Console.WriteLine(m1,
- ((Console.CursorVisible == true) ?
- "VISIBLE" : "HIDDEN"));
- s = Console.ReadLine();
- if (!String.IsNullOrEmpty(s))
- if (s[0] == '+')
- Console.CursorVisible = true;
- else if (s[0] == '-')
- Console.CursorVisible = false;
- else if (s[0] == 'x')
- break;
+ Console.WriteLine(m1,
+ ((Console.CursorVisible == true) ?
+ "VISIBLE" : "HIDDEN"));
+ s = Console.ReadLine();
+ if (!string.IsNullOrEmpty(s))
+ if (s[0] == '+')
+ Console.CursorVisible = true;
+ else if (s[0] == '-')
+ Console.CursorVisible = false;
+ else if (s[0] == 'x')
+ break;
}
- Console.CursorVisible = saveCursorVisibile;
- Console.CursorSize = saveCursorSize;
+ Console.CursorVisible = saveCursorVisibile;
+ Console.CursorSize = saveCursorSize;
}
}
/*
@@ -74,4 +74,4 @@ Type any text then press Enter. Type '+' in the first column to show
x
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/Error/error1.cs b/snippets/csharp/System/Console/Error/error1.cs
index 3af1a8fb07c..22658588652 100644
--- a/snippets/csharp/System/Console/Error/error1.cs
+++ b/snippets/csharp/System/Console/Error/error1.cs
@@ -3,38 +3,37 @@
public class Example
{
- public static void Main()
- {
- int increment = 0;
- bool exitFlag = false;
+ public static void Main()
+ {
+ int increment = 0;
+ bool exitFlag = false;
- while (!exitFlag) {
- if (Console.IsOutputRedirected)
- Console.Error.WriteLine("Generating multiples of numbers from {0} to {1}",
- increment + 1, increment + 10);
+ while (!exitFlag)
+ {
+ if (Console.IsOutputRedirected)
+ Console.Error.WriteLine($"Generating multiples of numbers from {increment + 1} to {increment + 10}");
- Console.WriteLine("Generating multiples of numbers from {0} to {1}",
- increment + 1, increment + 10);
- for (int ctr = increment + 1; ctr <= increment + 10; ctr++) {
- Console.Write("Multiples of {0}: ", ctr);
- for (int ctr2 = 1; ctr2 <= 10; ctr2++)
- Console.Write("{0}{1}", ctr * ctr2, ctr2 == 10 ? "" : ", ");
+ Console.WriteLine($"Generating multiples of numbers from {increment + 1} to {increment + 10}");
+ for (int ctr = increment + 1; ctr <= increment + 10; ctr++)
+ {
+ Console.Write($"Multiples of {ctr}: ");
+ for (int ctr2 = 1; ctr2 <= 10; ctr2++)
+ Console.Write($"{ctr * ctr2}{(ctr2 == 10 ? "" : ", ")}");
+ Console.WriteLine();
+ }
Console.WriteLine();
- }
- Console.WriteLine();
- increment += 10;
- Console.Error.Write("Display multiples of {0} through {1} (y/n)? ",
- increment + 1, increment + 10);
- Char response = Console.ReadKey(true).KeyChar;
- Console.Error.WriteLine(response);
- if (!Console.IsOutputRedirected)
- Console.CursorTop--;
+ increment += 10;
+ Console.Error.Write($"Display multiples of {increment + 1} through {increment + 10} (y/n)? ");
+ char response = Console.ReadKey(true).KeyChar;
+ Console.Error.WriteLine(response);
+ if (!Console.IsOutputRedirected)
+ Console.CursorTop--;
- if (Char.ToUpperInvariant(response) == 'N')
- exitFlag = true;
- }
- }
+ if (char.ToUpperInvariant(response) == 'N')
+ exitFlag = true;
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Console/Error/expandtabsex.cs b/snippets/csharp/System/Console/Error/expandtabsex.cs
index 2240a3abe6c..e9814f8750b 100644
--- a/snippets/csharp/System/Console/Error/expandtabsex.cs
+++ b/snippets/csharp/System/Console/Error/expandtabsex.cs
@@ -23,24 +23,28 @@ public static void Main(string[] args)
{
StreamWriter writer = null;
- if (args.Length < 2) {
+ if (args.Length < 2)
+ {
Console.WriteLine(usageText);
return;
}
- try {
- writer = new StreamWriter(args[1]);
+ try
+ {
+ writer = new(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
- catch(IOException e) {
+ catch (IOException e)
+ {
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return;
}
int i;
- while ((i = Console.Read()) != -1) {
+ while ((i = Console.Read()) != -1)
+ {
char c = (char)i;
if (c == '\t')
Console.Write(("").PadRight(tabSize, ' '));
@@ -50,10 +54,12 @@ public static void Main(string[] args)
writer.Close();
// Recover the standard output stream so that a
// completion message can be displayed.
- StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
- standardOutput.AutoFlush = true;
+ StreamWriter standardOutput = new(Console.OpenStandardOutput())
+ {
+ AutoFlush = true
+ };
Console.SetOut(standardOutput);
- Console.WriteLine("EXPANDTABSEX has completed the processing of {0}.", args[0]);
+ Console.WriteLine($"EXPANDTABSEX has completed the processing of {args[0]}.");
return;
}
}
diff --git a/snippets/csharp/System/Console/Error/viewtextfile.cs b/snippets/csharp/System/Console/Error/viewtextfile.cs
index 93190fc9bb6..58a4b563bf0 100644
--- a/snippets/csharp/System/Console/Error/viewtextfile.cs
+++ b/snippets/csharp/System/Console/Error/viewtextfile.cs
@@ -4,44 +4,46 @@
public class ViewTextFile
{
- public static void Main()
- {
- String[] args = Environment.GetCommandLineArgs();
- String errorOutput = "";
- // Make sure that there is at least one command line argument.
- if (args.Length <= 1)
- errorOutput += "You must include a filename on the command line.\n";
+ public static void Main()
+ {
+ string[] args = Environment.GetCommandLineArgs();
+ string errorOutput = "";
+ // Make sure that there is at least one command line argument.
+ if (args.Length <= 1)
+ errorOutput += "You must include a filename on the command line.\n";
- for (int ctr = 1; ctr <= args.GetUpperBound(0); ctr++) {
- // Check whether the file exists.
- if (!File.Exists(args[ctr])) {
- errorOutput += String.Format("'{0}' does not exist.\n", args[ctr]);
- }
- else {
- // Display the contents of the file.
- StreamReader sr = new StreamReader(args[ctr]);
- String contents = sr.ReadToEnd();
- sr.Close();
- Console.WriteLine("*****Contents of file '{0}':\n\n",
- args[ctr]);
- Console.WriteLine(contents);
- Console.WriteLine("*****\n");
- }
- }
+ for (int ctr = 1; ctr <= args.GetUpperBound(0); ctr++)
+ {
+ // Check whether the file exists.
+ if (!File.Exists(args[ctr]))
+ {
+ errorOutput += $"'{args[ctr]}' does not exist.\n";
+ }
+ else
+ {
+ // Display the contents of the file.
+ StreamReader sr = new(args[ctr]);
+ string contents = sr.ReadToEnd();
+ sr.Close();
+ Console.WriteLine($"*****Contents of file '{args[ctr]}':\n\n");
+ Console.WriteLine(contents);
+ Console.WriteLine("*****\n");
+ }
+ }
- // Check for error conditions.
- if (!String.IsNullOrEmpty(errorOutput)) {
- // Write error information to a file.
- Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"));
- Console.Error.WriteLine(errorOutput);
- Console.Error.Close();
- // Reacquire the standard error stream.
- var standardError = new StreamWriter(Console.OpenStandardError());
- standardError.AutoFlush = true;
- Console.SetError(standardError);
- Console.Error.WriteLine("\nError information written to ViewTextFile.Err.txt");
- }
- }
+ // Check for error conditions.
+ if (!string.IsNullOrEmpty(errorOutput))
+ {
+ // Write error information to a file.
+ Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"));
+ Console.Error.WriteLine(errorOutput);
+ Console.Error.Close();
+ // Reacquire the standard error stream.
+ var standardError = new StreamWriter(Console.OpenStandardError()) { AutoFlush = true };
+ Console.SetError(standardError);
+ Console.Error.WriteLine("\nError information written to ViewTextFile.Err.txt");
+ }
+ }
}
// If the example is compiled and run with the following command line:
// ViewTextFile file1.txt file2.txt
diff --git a/snippets/csharp/System/Console/In/consolein.cs b/snippets/csharp/System/Console/In/consolein.cs
index 7306524513b..4bc9809bf19 100644
--- a/snippets/csharp/System/Console/In/consolein.cs
+++ b/snippets/csharp/System/Console/In/consolein.cs
@@ -2,17 +2,19 @@
using System;
using System.IO;
-class InTest {
- public static void Main() {
+class InTest
+{
+ public static void Main()
+ {
TextReader tIn = Console.In;
TextWriter tOut = Console.Out;
tOut.WriteLine("Hola Mundo!");
tOut.Write("What is your name: ");
- String name = tIn.ReadLine();
+ string name = tIn.ReadLine();
- tOut.WriteLine("Buenos Dias, {0}!", name);
+ tOut.WriteLine($"Buenos Dias, {name}!");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/KeyAvailable/ka.cs b/snippets/csharp/System/Console/KeyAvailable/ka.cs
index 141d556c5fa..a5414177168 100644
--- a/snippets/csharp/System/Console/KeyAvailable/ka.cs
+++ b/snippets/csharp/System/Console/KeyAvailable/ka.cs
@@ -6,20 +6,21 @@ class Sample
{
public static void Main()
{
- ConsoleKeyInfo cki;
+ ConsoleKeyInfo cki;
- do {
- Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
+ do
+ {
+ Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
- // Your code could perform some useful task in the following loop. However,
- // for the sake of this example we'll merely pause for a quarter second.
+ // Your code could perform some useful task in the following loop. However,
+ // for the sake of this example we'll merely pause for a quarter second.
- while (!Console.KeyAvailable)
- Thread.Sleep(250); // Loop until input is entered.
+ while (!Console.KeyAvailable)
+ Thread.Sleep(250); // Loop until input is entered.
- cki = Console.ReadKey(true);
- Console.WriteLine("You pressed the '{0}' key.", cki.Key);
- } while(cki.Key != ConsoleKey.X);
+ cki = Console.ReadKey(true);
+ Console.WriteLine($"You pressed the '{cki.Key}' key.");
+ } while (cki.Key != ConsoleKey.X);
}
}
/*
@@ -40,4 +41,4 @@ You pressed the 'DownArrow' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'X' key.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/OpenStandardInput/decode.cs b/snippets/csharp/System/Console/OpenStandardInput/decode.cs
index 16ea92ccf82..9c7bbe996d2 100644
--- a/snippets/csharp/System/Console/OpenStandardInput/decode.cs
+++ b/snippets/csharp/System/Console/OpenStandardInput/decode.cs
@@ -4,8 +4,10 @@
using System.Text;
using System.IO;
-public class Decoder {
- public static void Main() {
+public class Decoder
+{
+ public static void Main()
+ {
Stream inputStream = Console.OpenStandardInput();
byte[] bytes = new byte[100];
Console.WriteLine("To decode, type or paste the UTF7 encoded string and press enter:");
diff --git a/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs b/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
index 8f1bbf07e64..9709d09b277 100644
--- a/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
+++ b/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
@@ -1,4 +1,4 @@
-// This sample opens a file whose name is passed to it as a parameter.
+// This sample opens a file whose name is passed to it as a parameter.
// It reads each line in the file and replaces every occurrence of 4
// space characters with a tab character.
//
@@ -45,7 +45,7 @@ public static int Main(string[] args)
}
}
}
- catch(IOException e)
+ catch (IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
@@ -55,8 +55,7 @@ public static int Main(string[] args)
// Recover the standard output stream so that a
// completion message can be displayed.
- var standardOutput = new StreamWriter(Console.OpenStandardOutput());
- standardOutput.AutoFlush = true;
+ var standardOutput = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
Console.SetOut(standardOutput);
Console.WriteLine($"INSERTTABS has completed the processing of {args[0]}.");
return 0;
diff --git a/snippets/csharp/System/Console/Out/out1.cs b/snippets/csharp/System/Console/Out/out1.cs
index aba012bc641..7a5669224e8 100644
--- a/snippets/csharp/System/Console/Out/out1.cs
+++ b/snippets/csharp/System/Console/Out/out1.cs
@@ -4,34 +4,36 @@
public class Example
{
- public static void Main()
- {
- // Get all files in the current directory.
- string[] files = Directory.GetFiles(".");
- Array.Sort(files);
+ public static void Main()
+ {
+ // Get all files in the current directory.
+ string[] files = Directory.GetFiles(".");
+ Array.Sort(files);
- // Display the files to the current output source to the console.
- Console.Out.WriteLine("First display of filenames to the console:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- Console.Out.WriteLine();
+ // Display the files to the current output source to the console.
+ Console.Out.WriteLine("First display of filenames to the console:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ Console.Out.WriteLine();
- // Redirect output to a file named Files.txt and write file list.
- StreamWriter sw = new StreamWriter(@".\Files.txt");
- sw.AutoFlush = true;
- Console.SetOut(sw);
- Console.Out.WriteLine("Display filenames to a file:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- Console.Out.WriteLine();
+ // Redirect output to a file named Files.txt and write file list.
+ StreamWriter sw = new(@".\Files.txt")
+ {
+ AutoFlush = true
+ };
+ Console.SetOut(sw);
+ Console.Out.WriteLine("Display filenames to a file:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ Console.Out.WriteLine();
- // Close previous output stream and redirect output to standard output.
- Console.Out.Close();
- sw = new StreamWriter(Console.OpenStandardOutput());
- sw.AutoFlush = true;
- Console.SetOut(sw);
+ // Close previous output stream and redirect output to standard output.
+ Console.Out.Close();
+ sw = new(Console.OpenStandardOutput());
+ sw.AutoFlush = true;
+ Console.SetOut(sw);
- // Display the files to the current output source to the console.
- Console.Out.WriteLine("Second display of filenames to the console:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- }
+ // Display the files to the current output source to the console.
+ Console.Out.WriteLine("Second display of filenames to the console:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/example3.cs b/snippets/csharp/System/Console/Overview/example3.cs
index 05e7487ae35..970e6164f79 100644
--- a/snippets/csharp/System/Console/Overview/example3.cs
+++ b/snippets/csharp/System/Console/Overview/example3.cs
@@ -7,159 +7,158 @@
public static class DisplayChars
{
- private static void Main(string[] args)
- {
- uint rangeStart = 0;
- uint rangeEnd = 0;
- bool setOutputEncodingToUnicode = true;
- // Get the current encoding so we can restore it.
- Encoding originalOutputEncoding = Console.OutputEncoding;
-
- try
- {
- switch(args.Length)
- {
- case 2:
- rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
- rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
- setOutputEncodingToUnicode = true;
- break;
- case 3:
- if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
- throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0]));
-
- if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
- throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1]));
-
- bool.TryParse(args[2], out setOutputEncodingToUnicode);
- break;
- default:
- Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]",
- Environment.GetCommandLineArgs()[0],
- "startingCodePointInHex",
- "endingCodePointInHex",
- "");
- return;
- }
-
- if (setOutputEncodingToUnicode)
- {
- try {
- // Set encoding using endianness of this system.
- // We're interested in displaying individual Char objects, so
- // we don't want a Unicode BOM or exceptions to be thrown on
- // invalid Char values.
- Console.OutputEncoding = new UnicodeEncoding(! BitConverter.IsLittleEndian, false);
- Console.WriteLine("\nOutput encoding set to UTF-16");
+ private static void Main(string[] args)
+ {
+ uint rangeStart = 0;
+ uint rangeEnd = 0;
+ bool setOutputEncodingToUnicode = true;
+ // Get the current encoding so we can restore it.
+ Encoding originalOutputEncoding = Console.OutputEncoding;
+
+ try
+ {
+ switch (args.Length)
+ {
+ case 2:
+ rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
+ rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
+ setOutputEncodingToUnicode = true;
+ break;
+ case 3:
+ if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
+ throw new ArgumentException($"{args[0]} is not a valid hexadecimal number.");
+
+ if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
+ throw new ArgumentException($"{args[1]} is not a valid hexadecimal number.");
+
+ bool.TryParse(args[2], out setOutputEncodingToUnicode);
+ break;
+ default:
+ Console.WriteLine($"Usage: {Environment.GetCommandLineArgs()[0]} <{"startingCodePointInHex"}> <{"endingCodePointInHex"}> [{""}]");
+ return;
}
- catch (IOException) {
- Console.OutputEncoding = new UTF8Encoding();
- Console.WriteLine("Output encoding set to UTF-8");
- }
- }
- else {
- Console.WriteLine("The console encoding is {0} (code page {1})",
- Console.OutputEncoding.EncodingName,
- Console.OutputEncoding.CodePage);
- }
- DisplayRange(rangeStart, rangeEnd);
- }
- catch (ArgumentException ex) {
- Console.WriteLine(ex.Message);
- }
- finally {
- // Restore console environment.
- Console.OutputEncoding = originalOutputEncoding;
- }
- }
-
- public static void DisplayRange(uint start, uint end)
- {
- const uint upperRange = 0x10FFFF;
- const uint surrogateStart = 0xD800;
- const uint surrogateEnd = 0xDFFF;
-
- if (end <= start) {
- uint t = start;
- start = end;
- end = t;
- }
-
- // Check whether the start or end range is outside of last plane.
- if (start > upperRange)
- throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
- start, upperRange));
- if (end > upperRange)
- throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
- end, upperRange));
-
- // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
- if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd ))
- throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}",
- start, end, surrogateStart, surrogateEnd));
- uint last = RoundUpToMultipleOf(0x10, end);
- uint first = RoundDownToMultipleOf(0x10, start);
-
- uint rows = (last - first) / 0x10;
-
- for (uint r = 0; r < rows; ++r) {
- // Display the row header.
- Console.Write("{0:x5} ", first + 0x10 * r);
-
- for (uint c = 0; c < 0x10; ++c) {
- uint cur = (first + 0x10 * r + c);
- if (cur < start) {
- Console.Write($" {(char)(0x20)} ");
- }
- else if (end < cur) {
- Console.Write($" {(char)(0x20)} ");
+
+ if (setOutputEncodingToUnicode)
+ {
+ try
+ {
+ // Set encoding using endianness of this system.
+ // We're interested in displaying individual Char objects, so
+ // we don't want a Unicode BOM or exceptions to be thrown on
+ // invalid Char values.
+ Console.OutputEncoding = new UnicodeEncoding(!BitConverter.IsLittleEndian, false);
+ Console.WriteLine("\nOutput encoding set to UTF-16");
+ }
+ catch (IOException)
+ {
+ Console.OutputEncoding = new UTF8Encoding();
+ Console.WriteLine("Output encoding set to UTF-8");
+ }
}
- else {
- // the cast to int is safe, since we know that val <= upperRange.
- String chars = Char.ConvertFromUtf32( (int) cur);
- // Display a space for code points that are not valid characters.
- if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
- UnicodeCategory.OtherNotAssigned)
- Console.Write($" {(char)(0x20)} ");
- // Display a space for code points in the private use area.
- else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
- UnicodeCategory.PrivateUse)
- Console.Write($" {(char)(0x20)} ");
- // Is surrogate pair a valid character?
- // Note that the console will interpret the high and low surrogate
- // as separate (and unrecognizable) characters.
- else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
- UnicodeCategory.OtherNotAssigned)
- Console.Write($" {(char)(0x20)} ");
- else
- Console.Write($" {chars} ");
+ else
+ {
+ Console.WriteLine($"The console encoding is {Console.OutputEncoding.EncodingName} (code page {Console.OutputEncoding.CodePage})");
}
-
- switch (c) {
- case 3: case 11:
- Console.Write("-");
- break;
- case 7:
- Console.Write("--");
- break;
+ DisplayRange(rangeStart, rangeEnd);
+ }
+ catch (ArgumentException ex)
+ {
+ Console.WriteLine(ex.Message);
+ }
+ finally
+ {
+ // Restore console environment.
+ Console.OutputEncoding = originalOutputEncoding;
+ }
+ }
+
+ public static void DisplayRange(uint start, uint end)
+ {
+ const uint upperRange = 0x10FFFF;
+ const uint surrogateStart = 0xD800;
+ const uint surrogateEnd = 0xDFFF;
+
+ if (end <= start)
+ {
+ uint t = start;
+ start = end;
+ end = t;
+ }
+
+ // Check whether the start or end range is outside of last plane.
+ if (start > upperRange)
+ throw new ArgumentException($"0x{start:X5} is outside the upper range of Unicode code points (0x{upperRange:X5})");
+ if (end > upperRange)
+ throw new ArgumentException(string.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
+ end, upperRange));
+
+ // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
+ if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd))
+ throw new ArgumentException($"0x{start:X5}-0x{end:X5} includes the surrogate pair range 0x{surrogateStart:X5}-0x{surrogateEnd:X5}");
+ uint last = RoundUpToMultipleOf(0x10, end);
+ uint first = RoundDownToMultipleOf(0x10, start);
+
+ uint rows = (last - first) / 0x10;
+
+ for (uint r = 0; r < rows; ++r)
+ {
+ // Display the row header.
+ Console.Write($"{first + 0x10 * r:x5} ");
+
+ for (uint c = 0; c < 0x10; ++c)
+ {
+ uint cur = (first + 0x10 * r + c);
+ if (cur < start)
+ {
+ Console.Write($" {(char)(0x20)} ");
+ }
+ else if (end < cur)
+ {
+ Console.Write($" {(char)(0x20)} ");
+ }
+ else
+ {
+ // the cast to int is safe, since we know that val <= upperRange.
+ string chars = char.ConvertFromUtf32((int)cur);
+ // Display a space for code points that are not valid characters.
+ if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
+ UnicodeCategory.OtherNotAssigned)
+ Console.Write($" {(char)(0x20)} ");
+ // Display a space for code points in the private use area.
+ else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
+ UnicodeCategory.PrivateUse)
+ Console.Write($" {(char)(0x20)} ");
+ // Is surrogate pair a valid character?
+ // Note that the console will interpret the high and low surrogate
+ // as separate (and unrecognizable) characters.
+ else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
+ UnicodeCategory.OtherNotAssigned)
+ Console.Write($" {(char)(0x20)} ");
+ else
+ Console.Write($" {chars} ");
+ }
+
+ switch (c)
+ {
+ case 3:
+ case 11:
+ Console.Write("-");
+ break;
+ case 7:
+ Console.Write("--");
+ break;
+ }
}
- }
- Console.WriteLine();
- if (0 < r && r % 0x10 == 0)
Console.WriteLine();
- }
- }
-
- private static uint RoundUpToMultipleOf(uint b, uint u)
- {
- return RoundDownToMultipleOf(b, u) + b;
- }
-
- private static uint RoundDownToMultipleOf(uint b, uint u)
- {
- return u - (u % b);
- }
+ if (0 < r && r % 0x10 == 0)
+ Console.WriteLine();
+ }
+ }
+
+ private static uint RoundUpToMultipleOf(uint b, uint u) => RoundDownToMultipleOf(b, u) + b;
+
+ private static uint RoundDownToMultipleOf(uint b, uint u) => u - (u % b);
}
// If the example is run with the command line
// DisplayChars 0400 04FF true
diff --git a/snippets/csharp/System/Console/Overview/fontlink1.cs b/snippets/csharp/System/Console/Overview/fontlink1.cs
index 46a9fb5d6e3..105a481cb5b 100644
--- a/snippets/csharp/System/Console/Overview/fontlink1.cs
+++ b/snippets/csharp/System/Console/Overview/fontlink1.cs
@@ -4,71 +4,79 @@
public class Example
{
- public static void Main()
- {
- string valueName = "Lucida Console";
- string newFont = "simsun.ttc,SimSun";
- string[] fonts = null;
- RegistryValueKind kind = 0;
- bool toAdd;
+ public static void Main()
+ {
+ string valueName = "Lucida Console";
+ string newFont = "simsun.ttc,SimSun";
+ string[] fonts = null;
+ RegistryValueKind kind = 0;
+ bool toAdd;
- RegistryKey key = Registry.LocalMachine.OpenSubKey(
- @"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink",
- true);
- if (key == null) {
- Console.WriteLine("Font linking is not enabled.");
- }
- else {
- // Determine if the font is a base font.
- string[] names = key.GetValueNames();
- if (Array.Exists(names, s => s.Equals(valueName,
- StringComparison.OrdinalIgnoreCase))) {
- // Get the value's type.
- kind = key.GetValueKind(valueName);
+ RegistryKey key = Registry.LocalMachine.OpenSubKey(
+ @"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink",
+ true);
+ if (key == null)
+ {
+ Console.WriteLine("Font linking is not enabled.");
+ }
+ else
+ {
+ // Determine if the font is a base font.
+ string[] names = key.GetValueNames();
+ if (Array.Exists(names, s => s.Equals(valueName,
+ StringComparison.OrdinalIgnoreCase)))
+ {
+ // Get the value's type.
+ kind = key.GetValueKind(valueName);
- // Type should be RegistryValueKind.MultiString, but we can't be sure.
- switch (kind) {
- case RegistryValueKind.String:
- fonts = new string[] { (string) key.GetValue(valueName) };
- break;
- case RegistryValueKind.MultiString:
- fonts = (string[]) key.GetValue(valueName);
- break;
- case RegistryValueKind.None:
- // Do nothing.
- fonts = new string[] { };
- break;
+ // Type should be RegistryValueKind.MultiString, but we can't be sure.
+ switch (kind)
+ {
+ case RegistryValueKind.String:
+ fonts = new string[] { (string)key.GetValue(valueName) };
+ break;
+ case RegistryValueKind.MultiString:
+ fonts = (string[])key.GetValue(valueName);
+ break;
+ case RegistryValueKind.None:
+ // Do nothing.
+ fonts = new string[] { };
+ break;
+ }
+ // Determine whether SimSun is a linked font.
+ if (Array.FindIndex(fonts, s => s.IndexOf("SimSun",
+ StringComparison.OrdinalIgnoreCase) >= 0) >= 0)
+ {
+ Console.WriteLine("Font is already linked.");
+ toAdd = false;
+ }
+ else
+ {
+ // Font is not a linked font.
+ toAdd = true;
+ }
}
- // Determine whether SimSun is a linked font.
- if (Array.FindIndex(fonts, s =>s.IndexOf("SimSun",
- StringComparison.OrdinalIgnoreCase) >=0) >= 0) {
- Console.WriteLine("Font is already linked.");
- toAdd = false;
+ else
+ {
+ // Font is not a base font.
+ toAdd = true;
+ fonts = new string[] { };
}
- else {
- // Font is not a linked font.
- toAdd = true;
- }
- }
- else {
- // Font is not a base font.
- toAdd = true;
- fonts = new string[] { };
- }
- if (toAdd) {
- Array.Resize(ref fonts, fonts.Length + 1);
- fonts[fonts.GetUpperBound(0)] = newFont;
- // Change REG_SZ to REG_MULTI_SZ.
- if (kind == RegistryValueKind.String)
- key.DeleteValue(valueName, false);
+ if (toAdd)
+ {
+ Array.Resize(ref fonts, fonts.Length + 1);
+ fonts[fonts.GetUpperBound(0)] = newFont;
+ // Change REG_SZ to REG_MULTI_SZ.
+ if (kind == RegistryValueKind.String)
+ key.DeleteValue(valueName, false);
- key.SetValue(valueName, fonts, RegistryValueKind.MultiString);
- Console.WriteLine("SimSun added to the list of linked fonts.");
- }
- }
+ key.SetValue(valueName, fonts, RegistryValueKind.MultiString);
+ Console.WriteLine("SimSun added to the list of linked fonts.");
+ }
+ }
- if (key != null) key.Close();
- }
+ if (key != null) key.Close();
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/normalize1.cs b/snippets/csharp/System/Console/Overview/normalize1.cs
index 3babe347a87..afa95e9f15c 100644
--- a/snippets/csharp/System/Console/Overview/normalize1.cs
+++ b/snippets/csharp/System/Console/Overview/normalize1.cs
@@ -1,19 +1,19 @@
//
using System;
-using System.IO;
+
public class Example
{
- public static void Main()
- {
- char[] chars = { '\u0061', '\u0308' };
+ public static void Main()
+ {
+ char[] chars = { '\u0061', '\u0308' };
- string combining = new String(chars);
- Console.WriteLine(combining);
+ string combining = new(chars);
+ Console.WriteLine(combining);
- combining = combining.Normalize();
- Console.WriteLine(combining);
- }
+ combining = combining.Normalize();
+ Console.WriteLine(combining);
+ }
}
// The example displays the following output:
// a"
diff --git a/snippets/csharp/System/Console/Overview/setfont1.cs b/snippets/csharp/System/Console/Overview/setfont1.cs
index c237d2aa5cf..8a51d11b9b3 100644
--- a/snippets/csharp/System/Console/Overview/setfont1.cs
+++ b/snippets/csharp/System/Console/Overview/setfont1.cs
@@ -4,77 +4,80 @@
public class Example
{
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern IntPtr GetStdHandle(int nStdHandle);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern IntPtr GetStdHandle(int nStdHandle);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- static extern bool GetCurrentConsoleFontEx(
- IntPtr consoleOutput,
- bool maximumWindow,
- ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ static extern bool GetCurrentConsoleFontEx(
+ IntPtr consoleOutput,
+ bool maximumWindow,
+ ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern bool SetCurrentConsoleFontEx(
- IntPtr consoleOutput,
- bool maximumWindow,
- CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern bool SetCurrentConsoleFontEx(
+ IntPtr consoleOutput,
+ bool maximumWindow,
+ CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
- private const int STD_OUTPUT_HANDLE = -11;
- private const int TMPF_TRUETYPE = 4;
- private const int LF_FACESIZE = 32;
- private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
+ private const int STD_OUTPUT_HANDLE = -11;
+ private const int TMPF_TRUETYPE = 4;
+ private const int LF_FACESIZE = 32;
+ private static IntPtr INVALID_HANDLE_VALUE = new(-1);
- public static unsafe void Main()
- {
- string fontName = "Lucida Console";
- IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
- if (hnd != INVALID_HANDLE_VALUE) {
- CONSOLE_FONT_INFO_EX info = new CONSOLE_FONT_INFO_EX();
- info.cbSize = (uint) Marshal.SizeOf(info);
- bool tt = false;
- // First determine whether there's already a TrueType font.
- if (GetCurrentConsoleFontEx(hnd, false, ref info)) {
- tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
- if (tt) {
- Console.WriteLine("The console already is using a TrueType font.");
- return;
+ public static unsafe void Main()
+ {
+ string fontName = "Lucida Console";
+ IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (hnd != INVALID_HANDLE_VALUE)
+ {
+ CONSOLE_FONT_INFO_EX info = new();
+ info.cbSize = (uint)Marshal.SizeOf(info);
+ bool tt = false;
+ // First determine whether there's already a TrueType font.
+ if (GetCurrentConsoleFontEx(hnd, false, ref info))
+ {
+ tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
+ if (tt)
+ {
+ Console.WriteLine("The console already is using a TrueType font.");
+ return;
+ }
+ // Set console font to Lucida Console.
+ CONSOLE_FONT_INFO_EX newInfo = new();
+ newInfo.cbSize = (uint)Marshal.SizeOf(newInfo);
+ newInfo.FontFamily = TMPF_TRUETYPE;
+ IntPtr ptr = new(newInfo.FaceName);
+ Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
+ // Get some settings from current font.
+ newInfo.dwFontSize = new(info.dwFontSize.X, info.dwFontSize.Y);
+ newInfo.FontWeight = info.FontWeight;
+ SetCurrentConsoleFontEx(hnd, false, newInfo);
}
- // Set console font to Lucida Console.
- CONSOLE_FONT_INFO_EX newInfo = new CONSOLE_FONT_INFO_EX();
- newInfo.cbSize = (uint) Marshal.SizeOf(newInfo);
- newInfo.FontFamily = TMPF_TRUETYPE;
- IntPtr ptr = new IntPtr(newInfo.FaceName);
- Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
- // Get some settings from current font.
- newInfo.dwFontSize = new COORD(info.dwFontSize.X, info.dwFontSize.Y);
- newInfo.FontWeight = info.FontWeight;
- SetCurrentConsoleFontEx(hnd, false, newInfo);
- }
- }
+ }
}
- [StructLayout(LayoutKind.Sequential)]
- internal struct COORD
- {
- internal short X;
- internal short Y;
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct COORD
+ {
+ internal short X;
+ internal short Y;
- internal COORD(short x, short y)
- {
- X = x;
- Y = y;
- }
- }
+ internal COORD(short x, short y)
+ {
+ X = x;
+ Y = y;
+ }
+ }
- [StructLayout(LayoutKind.Sequential)]
- internal unsafe struct CONSOLE_FONT_INFO_EX
- {
- internal uint cbSize;
- internal uint nFont;
- internal COORD dwFontSize;
- internal int FontFamily;
- internal int FontWeight;
- internal fixed char FaceName[LF_FACESIZE];
- }
+ [StructLayout(LayoutKind.Sequential)]
+ internal unsafe struct CONSOLE_FONT_INFO_EX
+ {
+ internal uint cbSize;
+ internal uint nFont;
+ internal COORD dwFontSize;
+ internal int FontFamily;
+ internal int FontWeight;
+ internal fixed char FaceName[LF_FACESIZE];
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/source.cs b/snippets/csharp/System/Console/Overview/source.cs
index b25867ef0df..0451dc4b837 100644
--- a/snippets/csharp/System/Console/Overview/source.cs
+++ b/snippets/csharp/System/Console/Overview/source.cs
@@ -1,7 +1,8 @@
-//
+//
using System;
-public class Example {
+public class Example
+{
public static void Main()
{
Console.Write("Hello ");
diff --git a/snippets/csharp/System/Console/Overview/unicode1.cs b/snippets/csharp/System/Console/Overview/unicode1.cs
index e36e9a1837e..8350ab587d2 100644
--- a/snippets/csharp/System/Console/Overview/unicode1.cs
+++ b/snippets/csharp/System/Console/Overview/unicode1.cs
@@ -3,27 +3,28 @@
public class Example
{
- public static void Main()
- {
- // Create a Char array for the modern Cyrillic alphabet,
- // from U+0410 to U+044F.
- int nChars = 0x044F - 0x0410 + 1;
- char[] chars = new char[nChars];
- ushort codePoint = 0x0410;
- for (int ctr = 0; ctr < chars.Length; ctr++) {
- chars[ctr] = (char)codePoint;
- codePoint++;
- }
+ public static void Main()
+ {
+ // Create a Char array for the modern Cyrillic alphabet,
+ // from U+0410 to U+044F.
+ int nChars = 0x044F - 0x0410 + 1;
+ char[] chars = new char[nChars];
+ ushort codePoint = 0x0410;
+ for (int ctr = 0; ctr < chars.Length; ctr++)
+ {
+ chars[ctr] = (char)codePoint;
+ codePoint++;
+ }
- Console.WriteLine("Current code page: {0}\n",
- Console.OutputEncoding.CodePage);
- // Display the characters.
- foreach (var ch in chars) {
- Console.Write("{0} ", ch);
- if (Console.CursorLeft >= 70)
- Console.WriteLine();
- }
- }
+ Console.WriteLine($"Current code page: {Console.OutputEncoding.CodePage}\n");
+ // Display the characters.
+ foreach (char ch in chars)
+ {
+ Console.Write($"{ch} ");
+ if (Console.CursorLeft >= 70)
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Current code page: 437
diff --git a/snippets/csharp/System/Console/Read/read.cs b/snippets/csharp/System/Console/Read/read.cs
index 5fdc7751b1c..9178e3ded6e 100644
--- a/snippets/csharp/System/Console/Read/read.cs
+++ b/snippets/csharp/System/Console/Read/read.cs
@@ -6,36 +6,36 @@ class Sample
{
public static void Main()
{
- string m1 = "\nType a string of text then press Enter. " +
- "Type '+' anywhere in the text to quit:\n";
- string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
- string m3 = "Character is hexadecimal 0x{0:x4}.";
- char ch;
- int x;
-//
- Console.WriteLine(m1);
- do
+ string m1 = "\nType a string of text then press Enter. " +
+ "Type '+' anywhere in the text to quit:\n";
+ string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
+ string m3 = "Character is hexadecimal 0x{0:x4}.";
+ char ch;
+ int x;
+ //
+ Console.WriteLine(m1);
+ do
{
- x = Console.Read();
- try
+ x = Console.Read();
+ try
{
- ch = Convert.ToChar(x);
- if (Char.IsWhiteSpace(ch))
- {
- Console.WriteLine(m3, x);
- if (ch == 0x0a)
- Console.WriteLine(m1);
- }
- else
+ ch = Convert.ToChar(x);
+ if (char.IsWhiteSpace(ch))
+ {
+ Console.WriteLine(m3, x);
+ if (ch == 0x0a)
+ Console.WriteLine(m1);
+ }
+ else
{
Console.WriteLine(m2, ch, x);
}
}
- catch (OverflowException e)
+ catch (OverflowException e)
{
- Console.WriteLine("{0} Value read = {1}.", e.Message, x);
- ch = Char.MinValue;
- Console.WriteLine(m1);
+ Console.WriteLine($"{e.Message} Value read = {x}.");
+ ch = char.MinValue;
+ Console.WriteLine(m1);
}
} while (ch != '+');
}
@@ -80,4 +80,4 @@ Character is hexadecimal 0x000a.
Character '+' is hexadecimal 0x002b.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/ReadKey/ReadKey1.cs b/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
index 263f3da42bd..09165916326 100644
--- a/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
+++ b/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
@@ -3,17 +3,16 @@
public class Example
{
- public static void Main()
- {
- DateTime dat = DateTime.Now;
- Console.WriteLine("The time: {0:d} at {0:t}", dat);
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Console.WriteLine("The time zone: {0}\n",
- tz.IsDaylightSavingTime(dat) ?
- tz.DaylightName : tz.StandardName);
- Console.Write("Press to exit... ");
- while (Console.ReadKey().Key != ConsoleKey.Enter) {}
- }
+ public static void Main()
+ {
+ DateTime dat = DateTime.Now;
+ Console.WriteLine("The time: {0:d} at {0:t}", dat);
+ TimeZoneInfo tz = TimeZoneInfo.Local;
+ Console.WriteLine($"The time zone: {(tz.IsDaylightSavingTime(dat) ?
+ tz.DaylightName : tz.StandardName)}\n");
+ Console.Write("Press to exit... ");
+ while (Console.ReadKey().Key != ConsoleKey.Enter) { }
+ }
}
// The example displays output like the following:
// The time: 11/11/2015 at 4:02 PM:
diff --git a/snippets/csharp/System/Console/ReadKey/ReadKey2.cs b/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
index 9f8d14b4337..509d4247b8f 100644
--- a/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
+++ b/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
@@ -3,17 +3,16 @@
public class Example
{
- public static void Main()
- {
- DateTime dat = DateTime.Now;
- Console.WriteLine("The time: {0:d} at {0:t}", dat);
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Console.WriteLine("The time zone: {0}\n",
- tz.IsDaylightSavingTime(dat) ?
- tz.DaylightName : tz.StandardName);
- Console.Write("Press to exit... ");
- while (Console.ReadKey(true).Key != ConsoleKey.Enter) {}
- }
+ public static void Main()
+ {
+ DateTime dat = DateTime.Now;
+ Console.WriteLine("The time: {0:d} at {0:t}", dat);
+ TimeZoneInfo tz = TimeZoneInfo.Local;
+ Console.WriteLine($"The time zone: {(tz.IsDaylightSavingTime(dat) ?
+ tz.DaylightName : tz.StandardName)}\n");
+ Console.Write("Press to exit... ");
+ while (Console.ReadKey(true).Key != ConsoleKey.Enter) { }
+ }
}
// The example displays output like the following:
// The time: 11/11/2015 at 4:02 PM:
diff --git a/snippets/csharp/System/Console/ReadKey/rk.cs b/snippets/csharp/System/Console/ReadKey/rk.cs
index 85578c6099a..66d8e08ceac 100644
--- a/snippets/csharp/System/Console/ReadKey/rk.cs
+++ b/snippets/csharp/System/Console/ReadKey/rk.cs
@@ -3,23 +3,23 @@
class Example
{
- public static void Main()
- {
- ConsoleKeyInfo cki;
- // Prevent example from ending if CTL+C is pressed.
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ ConsoleKeyInfo cki;
+ // Prevent example from ending if CTL+C is pressed.
+ Console.TreatControlCAsInput = true;
- Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
- Console.WriteLine("Press the Escape (Esc) key to quit: \n");
- do
- {
- cki = Console.ReadKey();
- Console.Write(" --- You pressed ");
- if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
- if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
- if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
- Console.WriteLine(cki.Key.ToString());
- } while (cki.Key != ConsoleKey.Escape);
+ Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
+ Console.WriteLine("Press the Escape (Esc) key to quit: \n");
+ do
+ {
+ cki = Console.ReadKey();
+ Console.Write(" --- You pressed ");
+ if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
+ if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
+ if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
+ Console.WriteLine(cki.Key.ToString());
+ } while (cki.Key != ConsoleKey.Escape);
}
}
// This example displays output similar to the following:
diff --git a/snippets/csharp/System/Console/ReadKey/rkbool.cs b/snippets/csharp/System/Console/ReadKey/rkbool.cs
index 8dee6cbb5c8..b6f655a7d43 100644
--- a/snippets/csharp/System/Console/ReadKey/rkbool.cs
+++ b/snippets/csharp/System/Console/ReadKey/rkbool.cs
@@ -3,23 +3,24 @@
class Example
{
- public static void Main()
- {
- ConsoleKeyInfo cki;
- // Prevent example from ending if CTL+C is pressed.
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ ConsoleKeyInfo cki;
+ // Prevent example from ending if CTL+C is pressed.
+ Console.TreatControlCAsInput = true;
- Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
- Console.WriteLine("Press the Escape (Esc) key to quit: \n");
- do {
- cki = Console.ReadKey(true);
- Console.Write("You pressed ");
- if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
- if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
- if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
- Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
- } while (cki.Key != ConsoleKey.Escape);
- }
+ Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
+ Console.WriteLine("Press the Escape (Esc) key to quit: \n");
+ do
+ {
+ cki = Console.ReadKey(true);
+ Console.Write("You pressed ");
+ if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
+ if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
+ if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
+ Console.WriteLine($"{cki.Key} (character '{cki.KeyChar}')");
+ } while (cki.Key != ConsoleKey.Escape);
+ }
}
// This example displays output similar to the following:
// Press any combination of CTL, ALT, and SHIFT, and a console key.
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLine2.cs b/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
index 95b0bc58501..7c1f5b60edb 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
@@ -3,18 +3,19 @@
public class Example
{
- public static void Main()
- {
- string line;
- Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
- Console.WriteLine();
- do {
- Console.Write(" ");
- line = Console.ReadLine();
- if (line != null)
- Console.WriteLine(" " + line);
- } while (line != null);
- }
+ public static void Main()
+ {
+ string line;
+ Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
+ Console.WriteLine();
+ do
+ {
+ Console.Write(" ");
+ line = Console.ReadLine();
+ if (line != null)
+ Console.WriteLine(" " + line);
+ } while (line != null);
+ }
}
// The following displays possible output from this example:
// Enter one or more lines of text (press CTRL+Z to exit):
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLine3.cs b/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
index 531421d7f5f..f3d0aea181a 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
@@ -3,24 +3,26 @@
public class Example
{
- public static void Main()
- {
- if (!Console.IsInputRedirected) {
- Console.WriteLine("This example requires that input be redirected from a file.");
- return;
- }
+ public static void Main()
+ {
+ if (!Console.IsInputRedirected)
+ {
+ Console.WriteLine("This example requires that input be redirected from a file.");
+ return;
+ }
- Console.WriteLine("About to call Console.ReadLine in a loop.");
- Console.WriteLine("----");
- String s;
- int ctr = 0;
- do {
- ctr++;
- s = Console.ReadLine();
- Console.WriteLine("Line {0}: {1}", ctr, s);
- } while (s != null);
- Console.WriteLine("---");
- }
+ Console.WriteLine("About to call Console.ReadLine in a loop.");
+ Console.WriteLine("----");
+ string s;
+ int ctr = 0;
+ do
+ {
+ ctr++;
+ s = Console.ReadLine();
+ Console.WriteLine($"Line {ctr}: {s}");
+ } while (s != null);
+ Console.WriteLine("---");
+ }
}
// The example displays the following output:
// About to call Console.ReadLine in a loop.
@@ -31,4 +33,4 @@ public static void Main()
// Line 4: This is the fourth line.
// Line 5:
// ---
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs b/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
index 3adb24727de..49e07aac22a 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
@@ -3,16 +3,16 @@
public class Example
{
- public static void Main()
- {
- Console.Clear();
+ public static void Main()
+ {
+ Console.Clear();
- DateTime dat = DateTime.Now;
+ DateTime dat = DateTime.Now;
- Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
- Console.Write("\nPress any key to continue... ");
- Console.ReadLine();
- }
+ Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
+ Console.Write("\nPress any key to continue... ");
+ Console.ReadLine();
+ }
}
// The example displays output like the following:
// Today is 10/26/2015 at 12:22:22 PM.
diff --git a/snippets/csharp/System/Console/SetBufferSize/wlt.cs b/snippets/csharp/System/Console/SetBufferSize/wlt.cs
index 406d5c83a57..fdde5bdd3aa 100644
--- a/snippets/csharp/System/Console/SetBufferSize/wlt.cs
+++ b/snippets/csharp/System/Console/SetBufferSize/wlt.cs
@@ -12,101 +12,101 @@ class Sample
public static int saveWindowHeight;
public static int saveWindowWidth;
public static bool saveCursorVisible;
-//
+ //
public static void Main()
{
- string m1 = "1) Press the cursor keys to move the console window.\n" +
- "2) Press any key to begin. When you're finished...\n" +
- "3) Press the Escape key to quit.";
- string g1 = "+----";
- string g2 = "| ";
- string grid1;
- string grid2;
- StringBuilder sbG1 = new StringBuilder();
- StringBuilder sbG2 = new StringBuilder();
- ConsoleKeyInfo cki;
- int y;
-//
- try
- {
- saveBufferWidth = Console.BufferWidth;
- saveBufferHeight = Console.BufferHeight;
- saveWindowHeight = Console.WindowHeight;
- saveWindowWidth = Console.WindowWidth;
- saveCursorVisible = Console.CursorVisible;
-//
- Console.Clear();
- Console.WriteLine(m1);
- Console.ReadKey(true);
+ string m1 = "1) Press the cursor keys to move the console window.\n" +
+ "2) Press any key to begin. When you're finished...\n" +
+ "3) Press the Escape key to quit.";
+ string g1 = "+----";
+ string g2 = "| ";
+ string grid1;
+ string grid2;
+ StringBuilder sbG1 = new();
+ StringBuilder sbG2 = new();
+ ConsoleKeyInfo cki;
+ int y;
+ //
+ try
+ {
+ saveBufferWidth = Console.BufferWidth;
+ saveBufferHeight = Console.BufferHeight;
+ saveWindowHeight = Console.WindowHeight;
+ saveWindowWidth = Console.WindowWidth;
+ saveCursorVisible = Console.CursorVisible;
+ //
+ Console.Clear();
+ Console.WriteLine(m1);
+ Console.ReadKey(true);
-// Set the smallest possible window size before setting the buffer size.
- Console.SetWindowSize(1, 1);
- Console.SetBufferSize(80, 80);
- Console.SetWindowSize(40, 20);
+ // Set the smallest possible window size before setting the buffer size.
+ Console.SetWindowSize(1, 1);
+ Console.SetBufferSize(80, 80);
+ Console.SetWindowSize(40, 20);
-// Create grid lines to fit the buffer. (The buffer width is 80, but
-// this same technique could be used with an arbitrary buffer width.)
- for (y = 0; y < Console.BufferWidth/g1.Length; y++)
- {
- sbG1.Append(g1);
- sbG2.Append(g2);
- }
- sbG1.Append(g1, 0, Console.BufferWidth%g1.Length);
- sbG2.Append(g2, 0, Console.BufferWidth%g2.Length);
- grid1 = sbG1.ToString();
- grid2 = sbG2.ToString();
+ // Create grid lines to fit the buffer. (The buffer width is 80, but
+ // this same technique could be used with an arbitrary buffer width.)
+ for (y = 0; y < Console.BufferWidth / g1.Length; y++)
+ {
+ sbG1.Append(g1);
+ sbG2.Append(g2);
+ }
+ sbG1.Append(g1, 0, Console.BufferWidth % g1.Length);
+ sbG2.Append(g2, 0, Console.BufferWidth % g2.Length);
+ grid1 = sbG1.ToString();
+ grid2 = sbG2.ToString();
- Console.CursorVisible = false;
- Console.Clear();
- for (y = 0; y < Console.BufferHeight-1; y++)
- {
- if (y%3 == 0)
- Console.Write(grid1);
- else
- Console.Write(grid2);
- }
+ Console.CursorVisible = false;
+ Console.Clear();
+ for (y = 0; y < Console.BufferHeight - 1; y++)
+ {
+ if (y % 3 == 0)
+ Console.Write(grid1);
+ else
+ Console.Write(grid2);
+ }
- Console.SetWindowPosition(0, 0);
- do
- {
- cki = Console.ReadKey(true);
- switch (cki.Key)
+ Console.SetWindowPosition(0, 0);
+ do
{
- case ConsoleKey.LeftArrow:
- if (Console.WindowLeft > 0)
- Console.SetWindowPosition(
- Console.WindowLeft-1, Console.WindowTop);
- break;
- case ConsoleKey.UpArrow:
- if (Console.WindowTop > 0)
- Console.SetWindowPosition(
- Console.WindowLeft, Console.WindowTop-1);
- break;
- case ConsoleKey.RightArrow:
- if (Console.WindowLeft < (Console.BufferWidth-Console.WindowWidth))
- Console.SetWindowPosition(
- Console.WindowLeft+1, Console.WindowTop);
- break;
- case ConsoleKey.DownArrow:
- if (Console.WindowTop < (Console.BufferHeight-Console.WindowHeight))
- Console.SetWindowPosition(
- Console.WindowLeft, Console.WindowTop+1);
- break;
+ cki = Console.ReadKey(true);
+ switch (cki.Key)
+ {
+ case ConsoleKey.LeftArrow:
+ if (Console.WindowLeft > 0)
+ Console.SetWindowPosition(
+ Console.WindowLeft - 1, Console.WindowTop);
+ break;
+ case ConsoleKey.UpArrow:
+ if (Console.WindowTop > 0)
+ Console.SetWindowPosition(
+ Console.WindowLeft, Console.WindowTop - 1);
+ break;
+ case ConsoleKey.RightArrow:
+ if (Console.WindowLeft < (Console.BufferWidth - Console.WindowWidth))
+ Console.SetWindowPosition(
+ Console.WindowLeft + 1, Console.WindowTop);
+ break;
+ case ConsoleKey.DownArrow:
+ if (Console.WindowTop < (Console.BufferHeight - Console.WindowHeight))
+ Console.SetWindowPosition(
+ Console.WindowLeft, Console.WindowTop + 1);
+ break;
+ }
}
- }
- while (cki.Key != ConsoleKey.Escape); // end do-while
- } // end try
- catch (IOException e)
+ while (cki.Key != ConsoleKey.Escape); // end do-while
+ } // end try
+ catch (IOException e)
{
- Console.WriteLine(e.Message);
+ Console.WriteLine(e.Message);
}
- finally
+ finally
{
- Console.Clear();
- Console.SetWindowSize(1, 1);
- Console.SetBufferSize(saveBufferWidth, saveBufferHeight);
- Console.SetWindowSize(saveWindowWidth, saveWindowHeight);
- Console.CursorVisible = saveCursorVisible;
+ Console.Clear();
+ Console.SetWindowSize(1, 1);
+ Console.SetBufferSize(saveBufferWidth, saveBufferHeight);
+ Console.SetWindowSize(saveWindowWidth, saveWindowHeight);
+ Console.CursorVisible = saveCursorVisible;
}
} // end Main
} // end Sample
@@ -128,4 +128,4 @@ public static void Main()
+----+----+----+-
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/SetError/SetError1.cs b/snippets/csharp/System/Console/SetError/SetError1.cs
index c4eaff4b0e5..5025a062a80 100644
--- a/snippets/csharp/System/Console/SetError/SetError1.cs
+++ b/snippets/csharp/System/Console/SetError/SetError1.cs
@@ -1,30 +1,30 @@
//
using System;
using System.IO;
-using System.Reflection;
+
public class RedirectStdErr
{
- public static void Main()
- {
- // Define file to receive error stream.
- DateTime appStart = DateTime.Now;
- string fn = @"c:\temp\errlog" + appStart.ToString("yyyyMMddHHmm") + ".log";
- TextWriter errStream = new StreamWriter(fn);
- string appName = typeof(RedirectStdErr).Assembly.Location;
- appName = appName.Substring(appName.LastIndexOf('\\') + 1);
- // Redirect standard error stream to file.
- Console.SetError(errStream);
- // Write file header.
- Console.Error.WriteLine("Error Log for Application {0}", appName);
- Console.Error.WriteLine();
- Console.Error.WriteLine("Application started at {0}.", appStart);
- Console.Error.WriteLine();
- //
- // Application code along with error output
- //
- // Close redirected error stream.
- Console.Error.Close();
- }
+ public static void Main()
+ {
+ // Define file to receive error stream.
+ DateTime appStart = DateTime.Now;
+ string fn = @"c:\temp\errlog" + appStart.ToString("yyyyMMddHHmm") + ".log";
+ TextWriter errStream = new StreamWriter(fn);
+ string appName = typeof(RedirectStdErr).Assembly.Location;
+ appName = appName.Substring(appName.LastIndexOf('\\') + 1);
+ // Redirect standard error stream to file.
+ Console.SetError(errStream);
+ // Write file header.
+ Console.Error.WriteLine($"Error Log for Application {appName}");
+ Console.Error.WriteLine();
+ Console.Error.WriteLine($"Application started at {appStart}.");
+ Console.Error.WriteLine();
+ //
+ // Application code along with error output
+ //
+ // Close redirected error stream.
+ Console.Error.Close();
+ }
}
//
diff --git a/snippets/csharp/System/Console/SetOut/source.cs b/snippets/csharp/System/Console/SetOut/source.cs
index c5fbd1f19b1..6368bc63c2f 100644
--- a/snippets/csharp/System/Console/SetOut/source.cs
+++ b/snippets/csharp/System/Console/SetOut/source.cs
@@ -5,24 +5,25 @@ class SetOutSample
{
public static void Main()
{
- try {
-//
+ try
+ {
+ //
Console.WriteLine("Hello World");
- FileStream fs = new FileStream("Test.txt", FileMode.Create);
+ FileStream fs = new("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
- StreamWriter sw = new StreamWriter(fs);
+ StreamWriter sw = new(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();
-//
+ //
}
catch (Exception ex)
{
- Console.WriteLine(ex.Message);
- Console.WriteLine(ex.StackTrace);
- }
- }
-}
\ No newline at end of file
+ Console.WriteLine(ex.Message);
+ Console.WriteLine(ex.StackTrace);
+ }
+ }
+}
diff --git a/snippets/csharp/System/Console/SetWindowSize/sws.cs b/snippets/csharp/System/Console/SetWindowSize/sws.cs
index 8b4f1413538..2c30e51e186 100644
--- a/snippets/csharp/System/Console/SetWindowSize/sws.cs
+++ b/snippets/csharp/System/Console/SetWindowSize/sws.cs
@@ -8,38 +8,38 @@ class Sample
{
public static void Main()
{
- int origWidth, width;
- int origHeight, height;
- string m1 = "The current window width is {0}, and the " +
- "current window height is {1}.";
- string m2 = "The new window width is {0}, and the new " +
- "window height is {1}.";
- string m4 = " (Press any key to continue...)";
-//
-// Step 1: Get the current window dimensions.
-//
- origWidth = Console.WindowWidth;
- origHeight = Console.WindowHeight;
- Console.WriteLine(m1, Console.WindowWidth,
- Console.WindowHeight);
- Console.WriteLine(m4);
- Console.ReadKey(true);
-//
-// Step 2: Cut the window to 1/4 its original size.
-//
- width = origWidth/2;
- height = origHeight/2;
- Console.SetWindowSize(width, height);
- Console.WriteLine(m2, Console.WindowWidth,
- Console.WindowHeight);
- Console.WriteLine(m4);
- Console.ReadKey(true);
-//
-// Step 3: Restore the window to its original size.
-//
- Console.SetWindowSize(origWidth, origHeight);
- Console.WriteLine(m1, Console.WindowWidth,
- Console.WindowHeight);
+ int origWidth, width;
+ int origHeight, height;
+ string m1 = "The current window width is {0}, and the " +
+ "current window height is {1}.";
+ string m2 = "The new window width is {0}, and the new " +
+ "window height is {1}.";
+ string m4 = " (Press any key to continue...)";
+ //
+ // Step 1: Get the current window dimensions.
+ //
+ origWidth = Console.WindowWidth;
+ origHeight = Console.WindowHeight;
+ Console.WriteLine(m1, Console.WindowWidth,
+ Console.WindowHeight);
+ Console.WriteLine(m4);
+ Console.ReadKey(true);
+ //
+ // Step 2: Cut the window to 1/4 its original size.
+ //
+ width = origWidth / 2;
+ height = origHeight / 2;
+ Console.SetWindowSize(width, height);
+ Console.WriteLine(m2, Console.WindowWidth,
+ Console.WindowHeight);
+ Console.WriteLine(m4);
+ Console.ReadKey(true);
+ //
+ // Step 3: Restore the window to its original size.
+ //
+ Console.SetWindowSize(origWidth, origHeight);
+ Console.WriteLine(m1, Console.WindowWidth,
+ Console.WindowHeight);
}
}
/*
@@ -52,4 +52,4 @@ public static void Main()
The current window width is 85, and the current window height is 43.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/Title/mytitle.cs b/snippets/csharp/System/Console/Title/mytitle.cs
index 2718a9095d7..68ec4e50937 100644
--- a/snippets/csharp/System/Console/Title/mytitle.cs
+++ b/snippets/csharp/System/Console/Title/mytitle.cs
@@ -6,14 +6,13 @@ class Sample
{
public static void Main()
{
- Console.WriteLine("The current console title is: \"{0}\"",
- Console.Title);
- Console.WriteLine(" (Press any key to change the console title.)");
- Console.ReadKey(true);
- Console.Title = "The title has changed!";
- Console.WriteLine("Note that the new console title is \"{0}\"\n" +
- " (Press any key to quit.)", Console.Title);
- Console.ReadKey(true);
+ Console.WriteLine($"The current console title is: \"{Console.Title}\"");
+ Console.WriteLine(" (Press any key to change the console title.)");
+ Console.ReadKey(true);
+ Console.Title = "The title has changed!";
+ Console.WriteLine("Note that the new console title is \"{0}\"\n" +
+ " (Press any key to quit.)", Console.Title);
+ Console.ReadKey(true);
}
}
/*
@@ -26,4 +25,4 @@ public static void Main()
(Press any key to quit.)
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Console/WindowLeft/windowleft1.cs b/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
index b25d1af0b13..d7a0af10c3c 100644
--- a/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
+++ b/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
@@ -3,52 +3,52 @@
public class Example
{
- public static void Main()
- {
- ConsoleKeyInfo key;
- bool moved = false;
+ public static void Main()
+ {
+ ConsoleKeyInfo key;
+ bool moved = false;
- Console.BufferWidth += 4;
- Console.Clear();
+ Console.BufferWidth += 4;
+ Console.Clear();
- ShowConsoleStatistics();
- do
- {
- key = Console.ReadKey(true);
- if (key.Key == ConsoleKey.LeftArrow)
- {
- int pos = Console.WindowLeft - 1;
- if (pos >= 0 && pos + Console.WindowWidth <= Console.BufferWidth)
+ ShowConsoleStatistics();
+ do
+ {
+ key = Console.ReadKey(true);
+ if (key.Key == ConsoleKey.LeftArrow)
{
- Console.WindowLeft = pos;
- moved = true;
+ int pos = Console.WindowLeft - 1;
+ if (pos >= 0 && pos + Console.WindowWidth <= Console.BufferWidth)
+ {
+ Console.WindowLeft = pos;
+ moved = true;
+ }
}
- }
- else if (key.Key == ConsoleKey.RightArrow)
- {
- int pos = Console.WindowLeft + 1;
- if (pos + Console.WindowWidth <= Console.BufferWidth)
+ else if (key.Key == ConsoleKey.RightArrow)
{
- Console.WindowLeft = pos;
- moved = true;
+ int pos = Console.WindowLeft + 1;
+ if (pos + Console.WindowWidth <= Console.BufferWidth)
+ {
+ Console.WindowLeft = pos;
+ moved = true;
+ }
}
- }
- if (moved)
- {
- ShowConsoleStatistics();
- moved = false;
- }
- Console.WriteLine();
- } while (true);
- }
+ if (moved)
+ {
+ ShowConsoleStatistics();
+ moved = false;
+ }
+ Console.WriteLine();
+ } while (true);
+ }
- private static void ShowConsoleStatistics()
- {
- Console.WriteLine("Console statistics:");
- Console.WriteLine(" Buffer: {0} x {1}", Console.BufferHeight, Console.BufferWidth);
- Console.WriteLine(" Window: {0} x {1}", Console.WindowHeight, Console.WindowWidth);
- Console.WriteLine(" Window starts at {0}.", Console.WindowLeft);
- Console.WriteLine("Press <- or -> to move window, Ctrl+C to exit.");
- }
+ private static void ShowConsoleStatistics()
+ {
+ Console.WriteLine("Console statistics:");
+ Console.WriteLine($" Buffer: {Console.BufferHeight} x {Console.BufferWidth}");
+ Console.WriteLine($" Window: {Console.WindowHeight} x {Console.WindowWidth}");
+ Console.WriteLine($" Window starts at {Console.WindowLeft}.");
+ Console.WriteLine("Press <- or -> to move window, Ctrl+C to exit.");
+ }
}
//
diff --git a/snippets/csharp/System/Console/Write/WriteParams1.cs b/snippets/csharp/System/Console/Write/WriteParams1.cs
index e55a9737241..dcf92542cc0 100644
--- a/snippets/csharp/System/Console/Write/WriteParams1.cs
+++ b/snippets/csharp/System/Console/Write/WriteParams1.cs
@@ -3,36 +3,38 @@
public class Person
{
- public String Name { get; set; }
- public DateTime BirthDate { get; set; }
- public Double Height { get; set; }
- public Double Weight { get; set; }
- public Char Gender { get; set; }
- public String Remarks { get; set; }
+ public string Name { get; set; }
+ public DateTime BirthDate { get; set; }
+ public double Height { get; set; }
+ public double Weight { get; set; }
+ public char Gender { get; set; }
+ public string Remarks { get; set; }
- public object[] GetDescription()
- {
- return new object[] { Name, Gender, Height, Weight, BirthDate};
- }
+ public object[] GetDescription() => new object[] { Name, Gender, Height, Weight, BirthDate };
}
public class Example
{
- public static void Main()
- {
- var p1 = new Person() { Name = "John", Gender = 'M',
- BirthDate = new DateTime(1992, 5, 10),
- Height = 73.5, Weight = 207 };
- p1.Remarks = "Client since 1/3/2012";
- Console.Write("{0}: {1}, born {4:d} Height {2} inches, Weight {3} lbs ",
- p1.GetDescription());
- if (String.IsNullOrEmpty(p1.Remarks))
- Console.WriteLine();
- else
- Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
- Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
- "\n " : "");
- }
+ public static void Main()
+ {
+ var p1 = new Person()
+ {
+ Name = "John",
+ Gender = 'M',
+ BirthDate = new DateTime(1992, 5, 10),
+ Height = 73.5,
+ Weight = 207,
+ Remarks = "Client since 1/3/2012"
+ };
+ Console.Write("{0}: {1}, born {4:d} Height {2} inches, Weight {3} lbs ",
+ p1.GetDescription());
+ if (string.IsNullOrEmpty(p1.Remarks))
+ Console.WriteLine();
+ else
+ Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
+ Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
+ "\n " : "");
+ }
}
// The example displays the following output:
// John: M, born 5/10/1992 Height 73.5 inches, Weight 207 lbs Remarks: Client since 1/3/2012
diff --git a/snippets/csharp/System/Console/Write/WriteParams2.cs b/snippets/csharp/System/Console/Write/WriteParams2.cs
index 9aaf17c3103..b9cd2cd4c9a 100644
--- a/snippets/csharp/System/Console/Write/WriteParams2.cs
+++ b/snippets/csharp/System/Console/Write/WriteParams2.cs
@@ -3,36 +3,38 @@
public class Person
{
- public String Name { get; set; }
- public DateTime BirthDate { get; set; }
- public Double Height { get; set; }
- public Double Weight { get; set; }
- public Char Gender { get; set; }
- public String Remarks { get; set; }
+ public string Name { get; set; }
+ public DateTime BirthDate { get; set; }
+ public double Height { get; set; }
+ public double Weight { get; set; }
+ public char Gender { get; set; }
+ public string Remarks { get; set; }
- public object[] GetDescription()
- {
- return new object[] { Name, Gender, Height, Weight, BirthDate};
- }
+ public object[] GetDescription() => new object[] { Name, Gender, Height, Weight, BirthDate };
}
public class Example
{
- public static void Main()
- {
- var p1 = new Person() { Name = "John", Gender = 'M',
- BirthDate = new DateTime(1992, 5, 10),
- Height = 73.5, Weight = 207 };
- p1.Remarks = "Client since 1/3/2012";
- Console.Write("{0}: {1}, born {2:d} Height {3} inches, Weight {4} lbs ",
- p1.Name, p1.Gender, p1.BirthDate, p1.Height, p1.Weight);
- if (String.IsNullOrEmpty(p1.Remarks))
- Console.WriteLine();
- else
- Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
- Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
- "\n " : "");
- }
+ public static void Main()
+ {
+ var p1 = new Person()
+ {
+ Name = "John",
+ Gender = 'M',
+ BirthDate = new DateTime(1992, 5, 10),
+ Height = 73.5,
+ Weight = 207,
+ Remarks = "Client since 1/3/2012"
+ };
+ Console.Write("{0}: {1}, born {2:d} Height {3} inches, Weight {4} lbs ",
+ p1.Name, p1.Gender, p1.BirthDate, p1.Height, p1.Weight);
+ if (string.IsNullOrEmpty(p1.Remarks))
+ Console.WriteLine();
+ else
+ Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
+ Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
+ "\n " : "");
+ }
}
// The example displays the following output:
// John: M, born 5/10/1992 Height 73.5 inches, Weight 207 lbs Remarks: Client since 1/3/2012
diff --git a/snippets/csharp/System/Console/Write/reformat.cs b/snippets/csharp/System/Console/Write/reformat.cs
index 38dd8a95995..e169951b7c5 100644
--- a/snippets/csharp/System/Console/Write/reformat.cs
+++ b/snippets/csharp/System/Console/Write/reformat.cs
@@ -13,9 +13,9 @@ public static void Main(string[] args)
string lineInput;
while ((lineInput = Console.ReadLine()) != null)
{
- string[] fields = lineInput.Split(new char[] {'\t'});
+ string[] fields = lineInput.Split(new char[] { '\t' });
bool isFirstField = true;
- foreach (var item in fields)
+ foreach (string item in fields)
{
if (isFirstField)
isFirstField = false;
@@ -23,11 +23,11 @@ public static void Main(string[] args)
Console.Write(',');
// If the field represents a boolean, replace with a numeric representation.
- bool itemBool;
- if (Boolean.TryParse(item, out itemBool))
- Console.Write(Convert.ToByte(itemBool));
- else
- Console.Write(item);
+ bool itemBool;
+ if (bool.TryParse(item, out itemBool))
+ Console.Write(Convert.ToByte(itemBool));
+ else
+ Console.Write(item);
}
Console.WriteLine();
}
diff --git a/snippets/csharp/System/Console/Write/wl.cs b/snippets/csharp/System/Console/Write/wl.cs
index 3aafac9d489..2ebd52baa74 100644
--- a/snippets/csharp/System/Console/Write/wl.cs
+++ b/snippets/csharp/System/Console/Write/wl.cs
@@ -1,11 +1,11 @@
-//
+//
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
- enum Color {Yellow = 1, Blue, Green};
+ enum Color { Yellow = 1, Blue, Green };
static DateTime thisDate = DateTime.Now;
public static void Main()
diff --git a/snippets/csharp/System/Console/WriteLine/WriteLine6.cs b/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
index ce3afce161b..1fc696ec4ff 100644
--- a/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
+++ b/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
@@ -2,22 +2,23 @@
public class Example
{
- public static void Main()
- {
- //
- Random rnd = new Random();
- // Generate five random Boolean values.
- for (int ctr = 1; ctr <= 5; ctr++) {
- bool bln = rnd.Next(0, 2) == 1;
- Console.WriteLine($"True or False: {bln}");
- }
+ public static void Main()
+ {
+ //
+ Random rnd = new();
+ // Generate five random Boolean values.
+ for (int ctr = 1; ctr <= 5; ctr++)
+ {
+ bool bln = rnd.Next(0, 2) == 1;
+ Console.WriteLine($"True or False: {bln}");
+ }
- // The example displays an output similar to the following:
- // True or False: False
- // True or False: True
- // True or False: False
- // True or False: False
- // True or False: True
- //
- }
+ // The example displays an output similar to the following:
+ // True or False: False
+ // True or False: True
+ // True or False: False
+ // True or False: False
+ // True or False: True
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/WriteLine7.cs b/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
index e48fe44472f..40347ff1ad5 100644
--- a/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
+++ b/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
@@ -1,12 +1,9 @@
-//
+//
using System;
public class Example
{
- public static void Main()
- {
- Console.WriteLine("Today's date: {0:D}", DateTime.Now);
- }
+ public static void Main() => Console.WriteLine("Today's date: {0:D}", DateTime.Now);
}
// The example displays output like the following:
// Today's date: Monday, April 1, 2019
diff --git a/snippets/csharp/System/Console/WriteLine/newline1.cs b/snippets/csharp/System/Console/WriteLine/newline1.cs
index 5b6f51fed3c..14e95f1f860 100644
--- a/snippets/csharp/System/Console/WriteLine/newline1.cs
+++ b/snippets/csharp/System/Console/WriteLine/newline1.cs
@@ -2,40 +2,40 @@
public class Example
{
- public static void Main()
- {
- //
- string[] lines = { "This is the first line.",
+ public static void Main()
+ {
+ //
+ string[] lines = { "This is the first line.",
"This is the second line." };
- // Output the lines using the default newline sequence.
- Console.WriteLine("With the default new line characters:");
- Console.WriteLine();
- foreach (string line in lines)
- Console.WriteLine(line);
+ // Output the lines using the default newline sequence.
+ Console.WriteLine("With the default new line characters:");
+ Console.WriteLine();
+ foreach (string line in lines)
+ Console.WriteLine(line);
- Console.WriteLine();
+ Console.WriteLine();
- // Redefine the newline characters to double space.
- Console.Out.NewLine = "\r\n\r\n";
- // Output the lines using the new newline sequence.
- Console.WriteLine("With redefined new line characters:");
- Console.WriteLine();
- foreach (string line in lines)
- Console.WriteLine(line);
+ // Redefine the newline characters to double space.
+ Console.Out.NewLine = "\r\n\r\n";
+ // Output the lines using the new newline sequence.
+ Console.WriteLine("With redefined new line characters:");
+ Console.WriteLine();
+ foreach (string line in lines)
+ Console.WriteLine(line);
- // The example displays the following output:
- // With the default new line characters:
- //
- // This is the first line.
- // This is the second line.
- //
- // With redefined new line characters:
- //
- //
- //
- // This is the first line.
- //
- // This is the second line.
- //
- }
+ // The example displays the following output:
+ // With the default new line characters:
+ //
+ // This is the first line.
+ // This is the second line.
+ //
+ // With redefined new line characters:
+ //
+ //
+ //
+ // This is the first line.
+ //
+ // This is the second line.
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/tipcalc.cs b/snippets/csharp/System/Console/WriteLine/tipcalc.cs
index 82719638d30..882529a1b43 100644
--- a/snippets/csharp/System/Console/WriteLine/tipcalc.cs
+++ b/snippets/csharp/System/Console/WriteLine/tipcalc.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
public class TipCalculator
@@ -7,7 +7,7 @@ public class TipCalculator
public static void Main(string[] args)
{
double billTotal;
- if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
+ if (args.Length == 0 || !double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
diff --git a/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs b/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
index b84e282754f..207acb5e018 100644
--- a/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
+++ b/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
@@ -2,22 +2,23 @@
public class Example
{
- public static void Main()
- {
- //
- // Assign 10 random integers to an array.
- Random rnd = new Random();
- int[] numbers = new int[10];
- for (int ctr = 0; ctr <= numbers.GetUpperBound(0); ctr++)
- numbers[ctr] = rnd.Next();
+ public static void Main()
+ {
+ //
+ // Assign 10 random integers to an array.
+ Random rnd = new();
+ int[] numbers = new int[10];
+ for (int ctr = 0; ctr <= numbers.GetUpperBound(0); ctr++)
+ numbers[ctr] = rnd.Next();
- // Determine whether the numbers are even or odd.
- foreach (var number in numbers) {
- bool even = (number % 2 == 0);
- Console.WriteLine("Is {0} even:", number);
- Console.WriteLine(even);
- Console.WriteLine();
- }
- //
- }
+ // Determine whether the numbers are even or odd.
+ foreach (int number in numbers)
+ {
+ bool even = (number % 2 == 0);
+ Console.WriteLine("Is {0} even:", number);
+ Console.WriteLine(even);
+ Console.WriteLine();
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs b/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
index d9e5c533435..765fc9623d5 100644
--- a/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
+++ b/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
@@ -2,21 +2,21 @@
public class Example
{
- public static void Main()
- {
- //
- Object[] values = { true, 12.632, 17908, "stringValue",
+ public static void Main()
+ {
+ //
+ object[] values = { true, 12.632, 17908, "stringValue",
'a', 16907.32m };
- foreach (var value in values)
- Console.WriteLine(value);
+ foreach (object value in values)
+ Console.WriteLine(value);
- // The example displays the following output:
- // True
- // 12.632
- // 17908
- // stringValue
- // a
- // 16907.32
- //
- }
+ // The example displays the following output:
+ // True
+ // 12.632
+ // 17908
+ // stringValue
+ // a
+ // 16907.32
+ //
+ }
}
diff --git a/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs b/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
index f57fb36b858..eba1ea1a6d8 100644
--- a/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
+++ b/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
@@ -4,49 +4,55 @@
public class ConsoleKeyExample
{
- public static void Main()
- {
- ConsoleKeyInfo input;
- do {
- Console.WriteLine("Press a key, together with Alt, Ctrl, or Shift.");
- Console.WriteLine("Press Esc to exit.");
- input = Console.ReadKey(true);
+ public static void Main()
+ {
+ ConsoleKeyInfo input;
+ do
+ {
+ Console.WriteLine("Press a key, together with Alt, Ctrl, or Shift.");
+ Console.WriteLine("Press Esc to exit.");
+ input = Console.ReadKey(true);
- StringBuilder output = new StringBuilder(
- String.Format("You pressed {0}", input.Key.ToString()));
- bool modifiers = false;
+ StringBuilder output = new(
+ $"You pressed {input.Key.ToString()}");
+ bool modifiers = false;
- if (input.Modifiers.HasFlag(ConsoleModifiers.Alt)) {
- output.Append(", together with " + ConsoleModifiers.Alt.ToString());
- modifiers = true;
- }
- if (input.Modifiers.HasFlag(ConsoleModifiers.Control))
- {
- if (modifiers) {
- output.Append(" and ");
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Alt))
+ {
+ output.Append(", together with " + ConsoleModifiers.Alt.ToString());
+ modifiers = true;
}
- else {
- output.Append(", together with ");
- modifiers = true;
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Control))
+ {
+ if (modifiers)
+ {
+ output.Append(" and ");
+ }
+ else
+ {
+ output.Append(", together with ");
+ modifiers = true;
+ }
+ output.Append(ConsoleModifiers.Control.ToString());
}
- output.Append(ConsoleModifiers.Control.ToString());
- }
- if (input.Modifiers.HasFlag(ConsoleModifiers.Shift))
- {
- if (modifiers) {
- output.Append(" and ");
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Shift))
+ {
+ if (modifiers)
+ {
+ output.Append(" and ");
+ }
+ else
+ {
+ output.Append(", together with ");
+ modifiers = true;
+ }
+ output.Append(ConsoleModifiers.Shift.ToString());
}
- else {
- output.Append(", together with ");
- modifiers = true;
- }
- output.Append(ConsoleModifiers.Shift.ToString());
- }
- output.Append(".");
- Console.WriteLine(output.ToString());
- Console.WriteLine();
- } while (input.Key != ConsoleKey.Escape);
- }
+ output.Append(".");
+ Console.WriteLine(output.ToString());
+ Console.WriteLine();
+ } while (input.Key != ConsoleKey.Escape);
+ }
}
// The output from a sample console session might appear as follows:
// Press a key, together with Alt, Ctrl, or Shift.
diff --git a/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs b/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
index aed90927338..7065e1f3ec8 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
@@ -8,69 +8,71 @@ class Sample
{
public static void Main()
{
- string k1 = "\nEnter a key ......... ";
- string k2 = "\nEnter another key ... ";
- string key1 = "";
- string key2 = "";
- string areKeysEqual = "The {0} and {1} keys are {2}equal.";
- string equalValue = "";
- string prompt = "Press the escape key (ESC) to quit, " +
- "or any other key to continue.";
- ConsoleKeyInfo cki1;
- ConsoleKeyInfo cki2;
+ string k1 = "\nEnter a key ......... ";
+ string k2 = "\nEnter another key ... ";
+ string key1 = "";
+ string key2 = "";
+ string areKeysEqual = "The {0} and {1} keys are {2}equal.";
+ string equalValue = "";
+ string prompt = "Press the escape key (ESC) to quit, " +
+ "or any other key to continue.";
+ ConsoleKeyInfo cki1;
+ ConsoleKeyInfo cki2;
-//
-// The Console.TreatControlCAsInput property prevents this example from
-// ending if you press CTL+C, however all other operating system keys and
-// shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
-//
- Console.TreatControlCAsInput = true;
+ //
+ // The Console.TreatControlCAsInput property prevents this example from
+ // ending if you press CTL+C, however all other operating system keys and
+ // shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
+ //
+ Console.TreatControlCAsInput = true;
-// Request that the user enter two key presses. A key press and any
-// combination shift, CTRL, and ALT modifier keys is permitted.
- do
- {
- Console.Write(k1);
- cki1 = Console.ReadKey(false);
- Console.Write(k2);
- cki2 = Console.ReadKey(false);
- Console.WriteLine();
-//
- key1 = KeyCombination(cki1);
- key2 = KeyCombination(cki2);
- if (cki1.Equals(cki2))
- equalValue = "";
- else
- equalValue = "not ";
- Console.WriteLine(areKeysEqual, key1, key2, equalValue);
-//
- Console.WriteLine(prompt);
- cki1 = Console.ReadKey(true);
- } while (cki1.Key != ConsoleKey.Escape);
-// Note: This example requires the Escape (Esc) key.
+ // Request that the user enter two key presses. A key press and any
+ // combination shift, CTRL, and ALT modifier keys is permitted.
+ do
+ {
+ Console.Write(k1);
+ cki1 = Console.ReadKey(false);
+ Console.Write(k2);
+ cki2 = Console.ReadKey(false);
+ Console.WriteLine();
+ //
+ key1 = KeyCombination(cki1);
+ key2 = KeyCombination(cki2);
+ if (cki1.Equals(cki2))
+ equalValue = "";
+ else
+ equalValue = "not ";
+ Console.WriteLine(areKeysEqual, key1, key2, equalValue);
+ //
+ Console.WriteLine(prompt);
+ cki1 = Console.ReadKey(true);
+ } while (cki1.Key != ConsoleKey.Escape);
+ // Note: This example requires the Escape (Esc) key.
}
-// The KeyCombination() method creates a string that specifies what
-// key and what combination of shift, CTRL, and ALT modifier keys
-// were pressed simultaneously.
+ // The KeyCombination() method creates a string that specifies what
+ // key and what combination of shift, CTRL, and ALT modifier keys
+ // were pressed simultaneously.
protected static string KeyCombination(ConsoleKeyInfo sourceCki)
{
- StringBuilder sb = new StringBuilder();
- sb.Length = 0;
- string keyCombo;
- if (sourceCki.Modifiers != 0)
+ StringBuilder sb = new()
+ {
+ Length = 0
+ };
+ string keyCombo;
+ if (sourceCki.Modifiers != 0)
{
- if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
- sb.Append("ALT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
- sb.Append("SHIFT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
- sb.Append("CTL+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
+ sb.Append("ALT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
+ sb.Append("SHIFT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
+ sb.Append("CTL+");
}
- sb.Append(sourceCki.Key.ToString());
- keyCombo = sb.ToString();
- return keyCombo;
+ sb.Append(sourceCki.Key.ToString());
+ keyCombo = sb.ToString();
+ return keyCombo;
}
}
diff --git a/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs b/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
index 42107343468..53668489262 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
@@ -8,60 +8,62 @@ class Sample
{
public static void Main()
{
- string k1 = "\nEnter a key ......... ";
- string key1 = "";
- string hashCodeFmt = "The hash code for the {0} key is {1}.";
- string prompt = "Press the escape key (ESC) to quit, " +
- "or any other key to continue.";
- ConsoleKeyInfo cki1;
- int hashCode = 0;
+ string k1 = "\nEnter a key ......... ";
+ string key1 = "";
+ string hashCodeFmt = "The hash code for the {0} key is {1}.";
+ string prompt = "Press the escape key (ESC) to quit, " +
+ "or any other key to continue.";
+ ConsoleKeyInfo cki1;
+ int hashCode = 0;
-//
-// The Console.TreatControlCAsInput property prevents this example from
-// ending if you press CTL+C, however all other operating system keys and
-// shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
-//
- Console.TreatControlCAsInput = true;
+ //
+ // The Console.TreatControlCAsInput property prevents this example from
+ // ending if you press CTL+C, however all other operating system keys and
+ // shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
+ //
+ Console.TreatControlCAsInput = true;
-// Request that the user enter two key presses. A key press and any
-// combination shift, CTRL, and ALT modifier keys is permitted.
- do
- {
- Console.Write(k1);
- cki1 = Console.ReadKey(false);
- Console.WriteLine();
-//
- key1 = KeyCombination(cki1);
- hashCode = cki1.GetHashCode();
- Console.WriteLine(hashCodeFmt, key1, hashCode);
-//
- Console.WriteLine(prompt);
- cki1 = Console.ReadKey(true);
- } while (cki1.Key != ConsoleKey.Escape);
-// Note: This example requires the Escape (Esc) key.
+ // Request that the user enter two key presses. A key press and any
+ // combination shift, CTRL, and ALT modifier keys is permitted.
+ do
+ {
+ Console.Write(k1);
+ cki1 = Console.ReadKey(false);
+ Console.WriteLine();
+ //
+ key1 = KeyCombination(cki1);
+ hashCode = cki1.GetHashCode();
+ Console.WriteLine(hashCodeFmt, key1, hashCode);
+ //
+ Console.WriteLine(prompt);
+ cki1 = Console.ReadKey(true);
+ } while (cki1.Key != ConsoleKey.Escape);
+ // Note: This example requires the Escape (Esc) key.
}
-// The KeyCombination() method creates a string that specifies what
-// key and what combination of shift, CTRL, and ALT modifier keys
-// were pressed simultaneously.
+ // The KeyCombination() method creates a string that specifies what
+ // key and what combination of shift, CTRL, and ALT modifier keys
+ // were pressed simultaneously.
protected static string KeyCombination(ConsoleKeyInfo sourceCki)
{
- StringBuilder sb = new StringBuilder();
- sb.Length = 0;
- string keyCombo;
- if (sourceCki.Modifiers != 0)
+ StringBuilder sb = new()
+ {
+ Length = 0
+ };
+ string keyCombo;
+ if (sourceCki.Modifiers != 0)
{
- if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
- sb.Append("ALT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
- sb.Append("SHIFT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
- sb.Append("CTL+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
+ sb.Append("ALT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
+ sb.Append("SHIFT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
+ sb.Append("CTL+");
}
- sb.Append(sourceCki.Key.ToString());
- keyCombo = sb.ToString();
- return keyCombo;
+ sb.Append(sourceCki.Key.ToString());
+ keyCombo = sb.ToString();
+ return keyCombo;
}
}
diff --git a/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs b/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
index 9426ae7aec5..57adc40a6e2 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
@@ -3,53 +3,55 @@
public class Example
{
- public static void Main()
- {
- // Configure console.
- Console.BufferWidth = 80;
- Console.WindowWidth = Console.BufferWidth;
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ // Configure console.
+ Console.BufferWidth = 80;
+ Console.WindowWidth = Console.BufferWidth;
+ Console.TreatControlCAsInput = true;
- string inputString = String.Empty;
- ConsoleKeyInfo keyInfo;
+ string inputString = string.Empty;
+ ConsoleKeyInfo keyInfo;
- Console.WriteLine("Enter a string. Press or Esc to exit.");
- do {
- keyInfo = Console.ReadKey(true);
- // Ignore if Alt or Ctrl is pressed.
- if ((keyInfo.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt)
- continue;
- if ((keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
- continue;
- // Ignore if KeyChar value is \u0000.
- if (keyInfo.KeyChar == '\u0000') continue;
- // Ignore tab key.
- if (keyInfo.Key == ConsoleKey.Tab) continue;
- // Handle backspace.
- if (keyInfo.Key == ConsoleKey.Backspace) {
- // Are there any characters to erase?
- if (inputString.Length >= 1) {
- // Determine where we are in the console buffer.
- int cursorCol = Console.CursorLeft - 1;
- int oldLength = inputString.Length;
- int extraRows = oldLength / 80;
+ Console.WriteLine("Enter a string. Press or Esc to exit.");
+ do
+ {
+ keyInfo = Console.ReadKey(true);
+ // Ignore if Alt or Ctrl is pressed.
+ if ((keyInfo.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt)
+ continue;
+ if ((keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
+ continue;
+ // Ignore if KeyChar value is \u0000.
+ if (keyInfo.KeyChar == '\u0000') continue;
+ // Ignore tab key.
+ if (keyInfo.Key == ConsoleKey.Tab) continue;
+ // Handle backspace.
+ if (keyInfo.Key == ConsoleKey.Backspace)
+ {
+ // Are there any characters to erase?
+ if (inputString.Length >= 1)
+ {
+ // Determine where we are in the console buffer.
+ int cursorCol = Console.CursorLeft - 1;
+ int oldLength = inputString.Length;
+ int extraRows = oldLength / 80;
- inputString = inputString.Substring(0, oldLength - 1);
- Console.CursorLeft = 0;
- Console.CursorTop = Console.CursorTop - extraRows;
- Console.Write(inputString + new String(' ', oldLength - inputString.Length));
- Console.CursorLeft = cursorCol;
+ inputString = inputString.Substring(0, oldLength - 1);
+ Console.CursorLeft = 0;
+ Console.CursorTop = Console.CursorTop - extraRows;
+ Console.Write(inputString + new string(' ', oldLength - inputString.Length));
+ Console.CursorLeft = cursorCol;
+ }
+ continue;
}
- continue;
- }
- // Handle Escape key.
- if (keyInfo.Key == ConsoleKey.Escape) break;
- // Handle key by adding it to input string.
- Console.Write(keyInfo.KeyChar);
- inputString += keyInfo.KeyChar;
- } while (keyInfo.Key != ConsoleKey.Enter);
- Console.WriteLine("\n\nYou entered:\n {0}",
- String.IsNullOrEmpty(inputString) ? "" : inputString);
- }
+ // Handle Escape key.
+ if (keyInfo.Key == ConsoleKey.Escape) break;
+ // Handle key by adding it to input string.
+ Console.Write(keyInfo.KeyChar);
+ inputString += keyInfo.KeyChar;
+ } while (keyInfo.Key != ConsoleKey.Enter);
+ Console.WriteLine($"\n\nYou entered:\n {(string.IsNullOrEmpty(inputString) ? "" : inputString)}");
+ }
}
//
From 6b0937bd0f7c6175e8a03034cf8290c778ade8fa Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Fri, 7 Aug 2026 14:40:10 -0700
Subject: [PATCH 2/5] Modernize C# code snippets
---
.../Overview/badcall1.cs | 44 ++---
.../Overview/fiximportassembly1.cs | 5 +-
.../Overview/importassembly1.cs | 9 +-
.../Overview/mangle1.cs | 9 +-
.../Overview/mangle2.cs | 9 +-
.../Overview/nofunction1.cs | 25 +--
.../Overview/stringutilities.cs | 7 +-
.../System/Enum/CompareTo/EnumCompareTo.cs | 16 +-
.../csharp/System/Enum/Equals/EnumEquals.cs | 27 +--
.../csharp/System/Enum/Equals/enumequals1.cs | 31 ++--
.../csharp/System/Enum/Format/EnumFormat.cs | 12 +-
.../csharp/System/Enum/GetName/EnumGetName.cs | 10 +-
.../System/Enum/GetNames/EnumGetNames.cs | 12 +-
.../csharp/System/Enum/GetNames/getnames1.cs | 16 +-
.../GetUnderlyingType/getunderlyingtype1.cs | 30 ++--
.../System/Enum/GetValues/EnumGetValues.cs | 10 +-
.../System/Enum/GetValues/getvalues1.cs | 14 +-
.../GetValues/getvalues_reflectiononly.cs | 30 ++--
.../csharp/System/Enum/HasFlag/hasflag0.cs | 52 +++---
.../csharp/System/Enum/HasFlag/hasflag1.cs | 35 ++--
.../System/Enum/IsDefined/isdefined1.cs | 61 +++----
.../System/Enum/IsDefined/isdefined2.cs | 25 +--
.../csharp/System/Enum/Overview/EnumMain.cs | 16 +-
.../csharp/System/Enum/Overview/Extensions.cs | 5 +-
.../csharp/System/Enum/Overview/class1.cs | 14 +-
.../csharp/System/Enum/Overview/class2.cs | 4 +-
.../System/Enum/Overview/classconversion1.cs | 6 +-
.../System/Enum/Overview/classconversion2.cs | 4 +-
.../System/Enum/Overview/classformat1.cs | 2 +-
.../System/Enum/Overview/classiterate.cs | 4 +-
.../csharp/System/Enum/Parse/EnumParse.cs | 5 +-
.../csharp/System/Enum/Parse/ParseExample1.cs | 38 +++--
.../csharp/System/Enum/Parse/ParseExample2.cs | 38 +++--
.../csharp/System/Enum/ToString/source.cs | 11 +-
snippets/csharp/System/Enum/ToString/tostr.cs | 32 ++--
.../System/Enum/ToString/tostringbyvalue1.cs | 38 ++---
.../System/Enum/TryParseTEnum/tryparse1.cs | 30 ++--
.../System/Enum/TryParseTEnum/tryparse2.cs | 30 ++--
.../Overview/getfolderpath.cs | 7 +-
.../Environment/CommandLine/commandline.cs | 8 +-
.../Environment/CurrentDirectory/Vars1.cs | 28 ++--
.../CurrentDirectory/environmentsample.cs | 68 ++++----
.../System/Environment/ExitCode/double.cs | 42 ++---
.../System/Environment/ExitCode/double1.cs | 46 +++---
.../csharp/System/Environment/FailFast/ff.cs | 28 ++--
.../GetCommandLineArgs/getcommandlineargs.cs | 2 +-
.../getenvironmentvariableex1.cs | 74 +++++----
.../GetEnvironmentVariable/gsev.cs | 32 ++--
.../getenvironmentvariables.cs | 10 +-
.../GetLogicalDrives/getlogicaldrives.cs | 8 +-
.../Environment/MachineName/machinename.cs | 8 +-
.../System/Environment/Overview/env0.cs | 44 +++--
.../System/Environment/ProcessorCount/pc.cs | 7 +-
.../Environment/StackTrace/stacktrace.cs | 6 +-
.../SystemDirectory/systemdirectory.cs | 8 +-
.../UserInteractive/userinteractive.cs | 6 +-
.../System/Environment/UserName/username.cs | 8 +-
.../System/Environment/Version/version.cs | 6 +-
.../Environment/WorkingSet/workingset.cs | 7 +-
.../EventArgs/Overview/programnodata.cs | 10 +-
.../EventArgs/Overview/programtruncated.cs | 5 +-
.../EventArgs/Overview/programwithdata.cs | 12 +-
.../EventArgs/Overview/programwithdelegate.cs | 12 +-
snippets/csharp/System/Exception/.ctor/new.cs | 56 +++----
.../csharp/System/Exception/.ctor/news.cs | 61 ++++---
.../csharp/System/Exception/.ctor/newsi.cs | 46 +++---
snippets/csharp/System/Exception/Data/data.cs | 99 +++++------
.../Exception/GetBaseException/getbaseexc.cs | 44 ++---
.../System/Exception/HResult/hresult.cs | 23 ++-
.../System/Exception/HelpLink/properties.cs | 46 +++---
.../Exception/InnerException/innerex.cs | 59 +++----
.../Exception/Overview/catchexception.cs | 32 ++--
.../System/Exception/Overview/example.cs | 70 ++++----
.../Exception/Overview/notprimeexception.cs | 40 ++---
.../Overview/primenumbergenerator.cs | 97 ++++++-----
.../System/Exception/Overview/rethrow1.cs | 93 ++++++-----
.../System/Exception/Overview/rethrow3.cs | 156 +++++++++---------
.../System/Exception/Overview/usageerrors1.cs | 45 +++--
.../System/Exception/Overview/usageerrors2.cs | 47 +++---
.../System/Exception/ToString/ToStringEx1.cs | 44 ++---
80 files changed, 1140 insertions(+), 1176 deletions(-)
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
index 32c43c4db91..ffa218fa50c 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
@@ -4,29 +4,31 @@
public class Example
{
- [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )]
- public static extern int MessageBox(IntPtr hwnd, String text, String caption, uint type);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
+ public static extern int MessageBox(IntPtr hwnd, string text, string caption, uint type);
- [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )]
- public static extern int MessageBoxW(IntPtr hwnd, String text, String caption, uint type);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
+ public static extern int MessageBoxW(IntPtr hwnd, string text, string caption, uint type);
- public static void Main()
- {
- try {
- MessageBox(new IntPtr(0), "Calling the MessageBox Function", "Example", 0);
- }
- catch (EntryPointNotFoundException e) {
- Console.WriteLine("{0}:\n {1}", e.GetType().Name,
- e.Message);
- }
+ public static void Main()
+ {
+ try
+ {
+ MessageBox(new IntPtr(0), "Calling the MessageBox Function", "Example", 0);
+ }
+ catch (EntryPointNotFoundException e)
+ {
+ Console.WriteLine($"{e.GetType().Name}:\n {e.Message}");
+ }
- try {
- MessageBoxW(new IntPtr(0), "Calling the MessageBox Function", "Example", 0);
- }
- catch (EntryPointNotFoundException e) {
- Console.WriteLine("{0}:\n {1}", e.GetType().Name,
- e.Message);
- }
- }
+ try
+ {
+ MessageBoxW(new IntPtr(0), "Calling the MessageBox Function", "Example", 0);
+ }
+ catch (EntryPointNotFoundException e)
+ {
+ Console.WriteLine($"{e.GetType().Name}:\n {e.Message}");
+ }
+ }
}
//
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
index bb3ec821556..3def163c260 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
@@ -3,10 +3,7 @@
public class Example
{
- public static void Main()
- {
- Console.WriteLine(StringUtilities.SayGoodMorning("Dakota"));
- }
+ public static void Main() => Console.WriteLine(StringUtilities.SayGoodMorning("Dakota"));
}
// The example displays the following output:
// A top of the morning to you, Dakota!
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
index f9a8be42553..65adebedfd0 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
@@ -4,13 +4,10 @@
public class Example
{
- [DllImport("StringUtilities.dll", CharSet = CharSet.Unicode )]
- public static extern String SayGoodMorning(String name);
+ [DllImport("StringUtilities.dll", CharSet = CharSet.Unicode)]
+ public static extern string SayGoodMorning(string name);
- public static void Main()
- {
- Console.WriteLine(SayGoodMorning("Dakota"));
- }
+ public static void Main() => Console.WriteLine(SayGoodMorning("Dakota"));
}
// The example displays the following output:
// Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
index e9a9d7bb994..a54acbd5ff6 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
@@ -4,13 +4,10 @@
public class Example
{
- [DllImport("TestDll.dll")]
- public static extern int Double(int number);
+ [DllImport("TestDll.dll")]
+ public static extern int Double(int number);
- public static void Main()
- {
- Console.WriteLine(Double(10));
- }
+ public static void Main() => Console.WriteLine(Double(10));
}
// The example displays the following output:
// Unhandled Exception: System.EntryPointNotFoundException: Unable to find
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
index 9e3f91d8097..19fc3684403 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
@@ -4,13 +4,10 @@
public class Example
{
- [DllImport("TestDll.dll", EntryPoint = "?Double@@YAHH@Z")]
- public static extern int Double(int number);
+ [DllImport("TestDll.dll", EntryPoint = "?Double@@YAHH@Z")]
+ public static extern int Double(int number);
- public static void Main()
- {
- Console.WriteLine(Double(10));
- }
+ public static void Main() => Console.WriteLine(Double(10));
}
// The example displays the following output:
// 20
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
index 89c1739c4dc..1b9caeb025b 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
@@ -4,19 +4,20 @@
public class Example
{
- [DllImport("user32.dll")]
- public static extern int GetMyNumber();
+ [DllImport("user32.dll")]
+ public static extern int GetMyNumber();
- public static void Main()
- {
- try {
- int number = GetMyNumber();
- }
- catch (EntryPointNotFoundException e) {
- Console.WriteLine("{0}:\n {1}", e.GetType().Name,
- e.Message);
- }
- }
+ public static void Main()
+ {
+ try
+ {
+ int number = GetMyNumber();
+ }
+ catch (EntryPointNotFoundException e)
+ {
+ Console.WriteLine($"{e.GetType().Name}:\n {e.Message}");
+ }
+ }
}
// The example displays the following output:
// EntryPointNotFoundException:
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/stringutilities.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/stringutilities.cs
index 08a69242e85..ffa497fc803 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/stringutilities.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/stringutilities.cs
@@ -3,9 +3,6 @@
public static class StringUtilities
{
- public static String SayGoodMorning(String name)
- {
- return String.Format("A top of the morning to you, {0}!", name);
- }
+ public static string SayGoodMorning(string name) => $"A top of the morning to you, {name}!";
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/CompareTo/EnumCompareTo.cs b/snippets/csharp/System/Enum/CompareTo/EnumCompareTo.cs
index 160618ccded..7f2225cdc61 100644
--- a/snippets/csharp/System/Enum/CompareTo/EnumCompareTo.cs
+++ b/snippets/csharp/System/Enum/CompareTo/EnumCompareTo.cs
@@ -1,19 +1,21 @@
//
using System;
-public class CompareToTest {
+public class CompareToTest
+{
enum VehicleDoors { Motorbike = 0, Sportscar = 2, Sedan = 4, Hatchback = 5 };
- public static void Main() {
+ public static void Main()
+ {
VehicleDoors myVeh = VehicleDoors.Sportscar;
VehicleDoors yourVeh = VehicleDoors.Motorbike;
VehicleDoors otherVeh = VehicleDoors.Sedan;
- Console.WriteLine("Does a {0} have more doors than a {1}?", myVeh, yourVeh);
- Console.WriteLine( "{0}{1}", myVeh.CompareTo(yourVeh) > 0 ? "Yes" : "No", Environment.NewLine );
+ Console.WriteLine($"Does a {myVeh} have more doors than a {yourVeh}?");
+ Console.WriteLine($"{(myVeh.CompareTo(yourVeh) > 0 ? "Yes" : "No")}{Environment.NewLine}");
- Console.WriteLine("Does a {0} have more doors than a {1}?", myVeh, otherVeh);
- Console.WriteLine( "{0}", myVeh.CompareTo(otherVeh) > 0 ? "Yes" : "No" );
+ Console.WriteLine($"Does a {myVeh} have more doors than a {otherVeh}?");
+ Console.WriteLine($"{(myVeh.CompareTo(otherVeh) > 0 ? "Yes" : "No")}");
}
}
// The example displays the following output:
@@ -22,4 +24,4 @@ public static void Main() {
//
// Does a Sportscar have more doors than a Sedan?
// No
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/Equals/EnumEquals.cs b/snippets/csharp/System/Enum/Equals/EnumEquals.cs
index c99d10e4e18..1b68f442db8 100644
--- a/snippets/csharp/System/Enum/Equals/EnumEquals.cs
+++ b/snippets/csharp/System/Enum/Equals/EnumEquals.cs
@@ -1,30 +1,31 @@
//
using System;
-public class EqualsTest {
+public class EqualsTest
+{
enum Colors { Red, Green, Blue, Yellow };
enum Mammals { Cat, Dog, Horse, Dolphin };
- public static void Main() {
+ public static void Main()
+ {
Mammals myPet = Mammals.Cat;
Colors myColor = Colors.Red;
Mammals yourPet = Mammals.Dog;
Colors yourColor = Colors.Red;
- Console.WriteLine("My favorite animal is a {0}", myPet);
- Console.WriteLine("Your favorite animal is a {0}", yourPet);
- Console.WriteLine("Do we like the same animal? {0}", myPet.Equals(yourPet) ? "Yes" : "No");
+ Console.WriteLine($"My favorite animal is a {myPet}");
+ Console.WriteLine($"Your favorite animal is a {yourPet}");
+ Console.WriteLine($"Do we like the same animal? {(myPet.Equals(yourPet) ? "Yes" : "No")}");
Console.WriteLine();
- Console.WriteLine("My favorite color is {0}", myColor);
- Console.WriteLine("Your favorite color is {0}", yourColor);
- Console.WriteLine("Do we like the same color? {0}", myColor.Equals(yourColor) ? "Yes" : "No");
+ Console.WriteLine($"My favorite color is {myColor}");
+ Console.WriteLine($"Your favorite color is {yourColor}");
+ Console.WriteLine($"Do we like the same color? {(myColor.Equals(yourColor) ? "Yes" : "No")}");
Console.WriteLine();
- Console.WriteLine("The value of my color ({0}) is {1}", myColor, Enum.Format(typeof(Colors), myColor, "d"));
- Console.WriteLine("The value of my pet (a {0}) is {1}", myPet, Enum.Format(typeof(Mammals), myPet, "d"));
- Console.WriteLine("Even though they have the same value, are they equal? {0}",
- myColor.Equals(myPet) ? "Yes" : "No");
+ Console.WriteLine($"The value of my color ({myColor}) is {Enum.Format(typeof(Colors), myColor, "d")}");
+ Console.WriteLine($"The value of my pet (a {myPet}) is {Enum.Format(typeof(Mammals), myPet, "d")}");
+ Console.WriteLine($"Even though they have the same value, are they equal? {(myColor.Equals(myPet) ? "Yes" : "No")}");
}
}
// The example displays the following output:
@@ -39,4 +40,4 @@ public static void Main() {
// The value of my color (Red) is 0
// The value of my pet (a Cat) is 0
// Even though they have the same value, are they equal? No
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/Equals/enumequals1.cs b/snippets/csharp/System/Enum/Equals/enumequals1.cs
index cd0c8988790..f0516354d40 100644
--- a/snippets/csharp/System/Enum/Equals/enumequals1.cs
+++ b/snippets/csharp/System/Enum/Equals/enumequals1.cs
@@ -1,26 +1,29 @@
//
using System;
-public enum SledDog { Unknown=0, AlaskanMalamute=1, Malamute=1,
- Husky=2, SiberianHusky=2 };
+public enum SledDog
+{
+ Unknown = 0, AlaskanMalamute = 1, Malamute = 1,
+ Husky = 2, SiberianHusky = 2
+};
-public enum WorkDog { Unknown=0, Newfoundland=1, GreatPyrennes=2 };
+public enum WorkDog { Unknown = 0, Newfoundland = 1, GreatPyrennes = 2 };
public class Example
{
- public static void Main()
- {
- SledDog dog1 = SledDog.Malamute;
- SledDog dog2 = SledDog.AlaskanMalamute;
- WorkDog dog3 = WorkDog.Newfoundland;
+ public static void Main()
+ {
+ SledDog dog1 = SledDog.Malamute;
+ SledDog dog2 = SledDog.AlaskanMalamute;
+ WorkDog dog3 = WorkDog.Newfoundland;
- Console.WriteLine("{0:F} ({0:D}) = {1:F} ({1:D}): {2}",
- dog1, dog2, dog1.Equals(dog2));
- Console.WriteLine("{0:F} ({0:D}) = {1:F} ({1:D}): {2}",
- dog1, dog3, dog1.Equals(dog3));
- }
+ Console.WriteLine("{0:F} ({0:D}) = {1:F} ({1:D}): {2}",
+ dog1, dog2, dog1.Equals(dog2));
+ Console.WriteLine("{0:F} ({0:D}) = {1:F} ({1:D}): {2}",
+ dog1, dog3, dog1.Equals(dog3));
+ }
}
// The example displays the following output:
// Malamute (1) = Malamute (1): True
// Malamute (1) = Newfoundland (1): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/Format/EnumFormat.cs b/snippets/csharp/System/Enum/Format/EnumFormat.cs
index ff2454e68d9..a7c904324f6 100644
--- a/snippets/csharp/System/Enum/Format/EnumFormat.cs
+++ b/snippets/csharp/System/Enum/Format/EnumFormat.cs
@@ -3,13 +3,15 @@
enum Colors { Red, Green, Blue, Yellow };
-public class FormatTest {
- public static void Main() {
+public class FormatTest
+{
+ public static void Main()
+ {
Colors myColor = Colors.Blue;
- Console.WriteLine("My favorite color is {0}.", myColor);
- Console.WriteLine("The value of my favorite color is {0}.", Enum.Format(typeof(Colors), myColor, "d"));
- Console.WriteLine("The hex value of my favorite color is {0}.", Enum.Format(typeof(Colors), myColor, "x"));
+ Console.WriteLine($"My favorite color is {myColor}.");
+ Console.WriteLine($"The value of my favorite color is {Enum.Format(typeof(Colors), myColor, "d")}.");
+ Console.WriteLine($"The hex value of my favorite color is {Enum.Format(typeof(Colors), myColor, "x")}.");
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/Enum/GetName/EnumGetName.cs b/snippets/csharp/System/Enum/GetName/EnumGetName.cs
index 40eca6e86df..79e54fdb5a6 100644
--- a/snippets/csharp/System/Enum/GetName/EnumGetName.cs
+++ b/snippets/csharp/System/Enum/GetName/EnumGetName.cs
@@ -1,14 +1,16 @@
//
using System;
-public class GetNameTest {
+public class GetNameTest
+{
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
- public static void Main() {
+ public static void Main()
+ {
- Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
- Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
+ Console.WriteLine($"The 4th value of the Colors Enum is {Enum.GetName(typeof(Colors), 3)}");
+ Console.WriteLine($"The 4th value of the Styles Enum is {Enum.GetName(typeof(Styles), 3)}");
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/Enum/GetNames/EnumGetNames.cs b/snippets/csharp/System/Enum/GetNames/EnumGetNames.cs
index 757160a8f44..bf796e3aa40 100644
--- a/snippets/csharp/System/Enum/GetNames/EnumGetNames.cs
+++ b/snippets/csharp/System/Enum/GetNames/EnumGetNames.cs
@@ -1,20 +1,22 @@
//
using System;
-public class GetNamesTest {
+public class GetNamesTest
+{
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
- public static void Main() {
+ public static void Main()
+ {
Console.WriteLine("The members of the Colors enum are:");
- foreach(string s in Enum.GetNames(typeof(Colors)))
+ foreach (string s in Enum.GetNames(typeof(Colors)))
Console.WriteLine(s);
Console.WriteLine();
Console.WriteLine("The members of the Styles enum are:");
- foreach(string s in Enum.GetNames(typeof(Styles)))
+ foreach (string s in Enum.GetNames(typeof(Styles)))
Console.WriteLine(s);
}
}
@@ -30,4 +32,4 @@ public static void Main() {
// Striped
// Tartan
// Corduroy
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/GetNames/getnames1.cs b/snippets/csharp/System/Enum/GetNames/getnames1.cs
index 21eb00213ed..db1a4aa67b7 100644
--- a/snippets/csharp/System/Enum/GetNames/getnames1.cs
+++ b/snippets/csharp/System/Enum/GetNames/getnames1.cs
@@ -5,13 +5,15 @@ enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };
public class Example
{
- public static void Main()
- {
- foreach (var name in Enum.GetNames(typeof(SignMagnitude))) {
- Console.WriteLine("{0,3:D} 0x{0:X} {1}",
- Enum.Parse(typeof(SignMagnitude), name),
- name);
-} }
+ public static void Main()
+ {
+ foreach (string name in Enum.GetNames(typeof(SignMagnitude)))
+ {
+ Console.WriteLine("{0,3:D} 0x{0:X} {1}",
+ Enum.Parse(typeof(SignMagnitude), name),
+ name);
+ }
+ }
}
// The example displays the following output:
// 0 0x00000000 Zero
diff --git a/snippets/csharp/System/Enum/GetUnderlyingType/getunderlyingtype1.cs b/snippets/csharp/System/Enum/GetUnderlyingType/getunderlyingtype1.cs
index 3d73fc7e0b2..a495a6069e7 100644
--- a/snippets/csharp/System/Enum/GetUnderlyingType/getunderlyingtype1.cs
+++ b/snippets/csharp/System/Enum/GetUnderlyingType/getunderlyingtype1.cs
@@ -3,24 +3,22 @@
public class Example
{
- public static void Main()
- {
- Enum[] enumValues = { ConsoleColor.Red, DayOfWeek.Monday,
+ public static void Main()
+ {
+ Enum[] enumValues = { ConsoleColor.Red, DayOfWeek.Monday,
MidpointRounding.ToEven, PlatformID.Win32NT,
DateTimeKind.Utc, StringComparison.Ordinal };
- Console.WriteLine("{0,-10} {1, 18} {2,15}\n",
- "Member", "Enumeration", "Underlying Type");
- foreach (var enumValue in enumValues)
- DisplayEnumInfo(enumValue);
- }
+ Console.WriteLine($"{"Member",-10} {"Enumeration",18} {"Underlying Type",15}\n");
+ foreach (var enumValue in enumValues)
+ DisplayEnumInfo(enumValue);
+ }
- static void DisplayEnumInfo(Enum enumValue)
- {
- Type enumType = enumValue.GetType();
- Type underlyingType = Enum.GetUnderlyingType(enumType);
- Console.WriteLine("{0,-10} {1, 18} {2,15}",
- enumValue, enumType.Name, underlyingType.Name);
- }
+ static void DisplayEnumInfo(Enum enumValue)
+ {
+ Type enumType = enumValue.GetType();
+ Type underlyingType = Enum.GetUnderlyingType(enumType);
+ Console.WriteLine($"{enumValue,-10} {enumType.Name,18} {underlyingType.Name,15}");
+ }
}
// The example displays the following output:
// Member Enumeration Underlying Type
@@ -31,4 +29,4 @@ static void DisplayEnumInfo(Enum enumValue)
// Win32NT PlatformID Int32
// Utc DateTimeKind Int32
// Ordinal StringComparison Int32
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs b/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
index eec4b34f190..4eb7fb06194 100644
--- a/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
+++ b/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
@@ -1,20 +1,22 @@
//
using System;
-public class GetValuesTest {
+public class GetValuesTest
+{
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid = 0, Striped = 23, Tartan = 65, Corduroy = 78 };
- public static void Main() {
+ public static void Main()
+ {
Console.WriteLine("The values of the Colors Enum are:");
- foreach(int i in Enum.GetValues(typeof(Colors)))
+ foreach (int i in Enum.GetValues(typeof(Colors)))
Console.WriteLine(i);
Console.WriteLine();
Console.WriteLine("The values of the Styles Enum are:");
- foreach(int i in Enum.GetValues(typeof(Styles)))
+ foreach (int i in Enum.GetValues(typeof(Styles)))
Console.WriteLine(i);
}
}
diff --git a/snippets/csharp/System/Enum/GetValues/getvalues1.cs b/snippets/csharp/System/Enum/GetValues/getvalues1.cs
index f3bb66a799c..c08943cff44 100644
--- a/snippets/csharp/System/Enum/GetValues/getvalues1.cs
+++ b/snippets/csharp/System/Enum/GetValues/getvalues1.cs
@@ -5,12 +5,14 @@ enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };
public class Example
{
- public static void Main()
- {
- foreach (var value in Enum.GetValues(typeof(SignMagnitude))) {
- Console.WriteLine("{0,3} 0x{0:X8} {1}",
- (int) value, ((SignMagnitude) value));
-} }
+ public static void Main()
+ {
+ foreach (object value in Enum.GetValues(typeof(SignMagnitude)))
+ {
+ Console.WriteLine("{0,3} 0x{0:X8} {1}",
+ (int)value, ((SignMagnitude)value));
+ }
+ }
}
// The example displays the following output:
// 0 0x00000000 Zero
diff --git a/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs b/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
index 1d252982e79..6f4dd70d499 100644
--- a/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
+++ b/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
@@ -4,19 +4,19 @@
public class Example
{
- public static void Main()
- {
- Assembly assem = Assembly.ReflectionOnlyLoadFrom(@".\Enumerations.dll");
- Type typ = assem.GetType("Pets");
- FieldInfo[] fields = typ.GetFields();
+ public static void Main()
+ {
+ Assembly assem = Assembly.ReflectionOnlyLoadFrom(@".\Enumerations.dll");
+ Type typ = assem.GetType("Pets");
+ FieldInfo[] fields = typ.GetFields();
- foreach (var field in fields) {
- if (field.Name.Equals("value__")) continue;
+ foreach (var field in fields)
+ {
+ if (field.Name.Equals("value__")) continue;
- Console.WriteLine("{0,-9} {1}", field.Name + ":",
- field.GetRawConstantValue());
- }
- }
+ Console.WriteLine($"{field.Name + ":",-9} {field.GetRawConstantValue()}");
+ }
+ }
}
// The example displays the following output:
// None: 0
@@ -30,6 +30,10 @@ public static void Main()
//
//
-[Flags] enum Pets { None=0, Dog=1, Cat=2, Rodent=4, Bird=8,
- Fish=16, Reptile=32, Other=64 };
+[Flags]
+enum Pets
+{
+ None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8,
+ Fish = 16, Reptile = 32, Other = 64
+};
//
diff --git a/snippets/csharp/System/Enum/HasFlag/hasflag0.cs b/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
index b0f87dc48f8..c7631b299ff 100644
--- a/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
+++ b/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
@@ -1,37 +1,37 @@
//
using System;
-[Flags] public enum Pets {
- None = 0,
- Dog = 1,
- Cat = 2,
- Bird = 4,
- Rabbit = 8,
- Other = 16
+[Flags]
+public enum Pets
+{
+ None = 0,
+ Dog = 1,
+ Cat = 2,
+ Bird = 4,
+ Rabbit = 8,
+ Other = 16
}
public class Example
{
- public static void Main()
- {
- Pets[] petsInFamilies = { Pets.None, Pets.Dog | Pets.Cat, Pets.Dog };
- int familiesWithoutPets = 0;
- int familiesWithDog = 0;
+ public static void Main()
+ {
+ Pets[] petsInFamilies = { Pets.None, Pets.Dog | Pets.Cat, Pets.Dog };
+ int familiesWithoutPets = 0;
+ int familiesWithDog = 0;
- foreach (var petsInFamily in petsInFamilies)
- {
- // Count families that have no pets.
- if (petsInFamily.Equals(Pets.None))
- familiesWithoutPets++;
- // Of families with pets, count families that have a dog.
- else if (petsInFamily.HasFlag(Pets.Dog))
- familiesWithDog++;
- }
- Console.WriteLine("{0} of {1} families in the sample have no pets.",
- familiesWithoutPets, petsInFamilies.Length);
- Console.WriteLine("{0} of {1} families in the sample have a dog.",
- familiesWithDog, petsInFamilies.Length);
- }
+ foreach (var petsInFamily in petsInFamilies)
+ {
+ // Count families that have no pets.
+ if (petsInFamily.Equals(Pets.None))
+ familiesWithoutPets++;
+ // Of families with pets, count families that have a dog.
+ else if (petsInFamily.HasFlag(Pets.Dog))
+ familiesWithDog++;
+ }
+ Console.WriteLine($"{familiesWithoutPets} of {petsInFamilies.Length} families in the sample have no pets.");
+ Console.WriteLine($"{familiesWithDog} of {petsInFamilies.Length} families in the sample have a dog.");
+ }
}
// The example displays the following output:
// 1 of 3 families in the sample have no pets.
diff --git a/snippets/csharp/System/Enum/HasFlag/hasflag1.cs b/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
index 539fb710d99..0df90c8021c 100644
--- a/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
+++ b/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
@@ -1,27 +1,28 @@
//
using System;
-[Flags] public enum DinnerItems {
- None = 0,
- Entree = 1,
- Appetizer = 2,
- Side = 4,
- Dessert = 8,
- Beverage = 16,
- BarBeverage = 32
+[Flags]
+public enum DinnerItems
+{
+ None = 0,
+ Entree = 1,
+ Appetizer = 2,
+ Side = 4,
+ Dessert = 8,
+ Beverage = 16,
+ BarBeverage = 32
}
public class Example
{
- public static void Main()
- {
- DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
- DinnerItems.Beverage | DinnerItems.Dessert;
- DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage;
- Console.WriteLine("{0} includes {1}: {2}",
- myOrder, flagValue, myOrder.HasFlag(flagValue));
- }
+ public static void Main()
+ {
+ DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
+ DinnerItems.Beverage | DinnerItems.Dessert;
+ DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage;
+ Console.WriteLine($"{myOrder} includes {flagValue}: {myOrder.HasFlag(flagValue)}");
+ }
}
// The example displays the following output:
// Entree, Appetizer, Dessert, Beverage includes Entree, Beverage: True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
index 398eeac1a76..2abe64176d8 100644
--- a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
+++ b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
@@ -1,42 +1,43 @@
//
using System;
-[Flags] public enum PetType
+[Flags]
+public enum PetType
{
- None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
+ None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
};
public class Example
{
- public static void Main()
- {
- object value;
+ public static void Main()
+ {
+ object value;
- // Call IsDefined with underlying integral value of member.
- value = 1;
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- // Call IsDefined with invalid underlying integral value.
- value = 64;
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- // Call IsDefined with string containing member name.
- value = "Rodent";
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- // Call IsDefined with a variable of type PetType.
- value = PetType.Dog;
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- value = PetType.Dog | PetType.Cat;
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- // Call IsDefined with uppercase member name.
- value = "None";
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- value = "NONE";
- Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- // Call IsDefined with combined value
- value = PetType.Dog | PetType.Bird;
- Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- value = value.ToString();
- Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
- }
+ // Call IsDefined with underlying integral value of member.
+ value = 1;
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ // Call IsDefined with invalid underlying integral value.
+ value = 64;
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ // Call IsDefined with string containing member name.
+ value = "Rodent";
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ // Call IsDefined with a variable of type PetType.
+ value = PetType.Dog;
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ value = PetType.Dog | PetType.Cat;
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ // Call IsDefined with uppercase member name.
+ value = "None";
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ value = "NONE";
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
+ // Call IsDefined with combined value
+ value = PetType.Dog | PetType.Bird;
+ Console.WriteLine($"{value:D}: {Enum.IsDefined(typeof(PetType), value)}");
+ value = value.ToString();
+ Console.WriteLine($"{value:D}: {Enum.IsDefined(typeof(PetType), value)}");
+ }
}
// The example displays the following output:
// 1: True
diff --git a/snippets/csharp/System/Enum/IsDefined/isdefined2.cs b/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
index 882f1809ba0..45e29de6ac9 100644
--- a/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
+++ b/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
@@ -1,21 +1,22 @@
//
using System;
-[Flags] public enum Pets {
- None = 0, Dog = 1, Cat = 2, Bird = 4,
- Rodent = 8, Other = 16 };
+[Flags]
+public enum Pets
+{
+ None = 0, Dog = 1, Cat = 2, Bird = 4,
+ Rodent = 8, Other = 16
+};
public class Example
{
- public static void Main()
- {
- Pets value = Pets.Dog | Pets.Cat;
- Console.WriteLine("{0:D} Exists: {1}",
- value, Pets.IsDefined(typeof(Pets), value));
- string name = value.ToString();
- Console.WriteLine("{0} Exists: {1}",
- name, Pets.IsDefined(typeof(Pets), name));
- }
+ public static void Main()
+ {
+ Pets value = Pets.Dog | Pets.Cat;
+ Console.WriteLine($"{value:D} Exists: {Pets.IsDefined(typeof(Pets), value)}");
+ string name = value.ToString();
+ Console.WriteLine($"{name} Exists: {Pets.IsDefined(typeof(Pets), name)}");
+ }
}
// The example displays the following output:
// 3 Exists: False
diff --git a/snippets/csharp/System/Enum/Overview/EnumMain.cs b/snippets/csharp/System/Enum/Overview/EnumMain.cs
index 11ea8acf442..08c6f23b098 100644
--- a/snippets/csharp/System/Enum/Overview/EnumMain.cs
+++ b/snippets/csharp/System/Enum/Overview/EnumMain.cs
@@ -1,28 +1,30 @@
-//
+//
using System;
-public class EnumTest {
+public class EnumTest
+{
enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
enum BoilingPoints { Celsius = 100, Fahrenheit = 212 };
[Flags]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
- public static void Main() {
+ public static void Main()
+ {
Type weekdays = typeof(Days);
Type boiling = typeof(BoilingPoints);
Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");
- foreach ( string s in Enum.GetNames(weekdays) )
- Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));
+ foreach (string s in Enum.GetNames(weekdays))
+ Console.WriteLine($"{s,-11}= {Enum.Format(weekdays, Enum.Parse(weekdays, s), "d")}");
Console.WriteLine();
Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");
- foreach ( string s in Enum.GetNames(boiling) )
- Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));
+ foreach (string s in Enum.GetNames(boiling))
+ Console.WriteLine($"{s,-11}= {Enum.Format(boiling, Enum.Parse(boiling, s), "d")}");
Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
Console.WriteLine();
diff --git a/snippets/csharp/System/Enum/Overview/Extensions.cs b/snippets/csharp/System/Enum/Overview/Extensions.cs
index b5a109fb659..e10638bb766 100644
--- a/snippets/csharp/System/Enum/Overview/Extensions.cs
+++ b/snippets/csharp/System/Enum/Overview/Extensions.cs
@@ -9,10 +9,7 @@ public static class Extensions
{
public static Grades minPassing = Grades.D;
- public static bool Passing(this Grades grade)
- {
- return grade >= minPassing;
- }
+ public static bool Passing(this Grades grade) => grade >= minPassing;
}
class Example8
diff --git a/snippets/csharp/System/Enum/Overview/class1.cs b/snippets/csharp/System/Enum/Overview/class1.cs
index d0dc14f9387..c5209631c3f 100644
--- a/snippets/csharp/System/Enum/Overview/class1.cs
+++ b/snippets/csharp/System/Enum/Overview/class1.cs
@@ -1,17 +1,17 @@
-using System;
+using System;
//
-public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };
+public enum ArrivalStatus { Unknown = -3, Late = -1, OnTime = 0, Early = 1 };
//
//
public class Example
{
- public static void Main()
- {
- ArrivalStatus status = ArrivalStatus.OnTime;
- Console.WriteLine($"Arrival Status: {status} ({status:D})");
- }
+ public static void Main()
+ {
+ ArrivalStatus status = ArrivalStatus.OnTime;
+ Console.WriteLine($"Arrival Status: {status} ({status:D})");
+ }
}
// The example displays the following output:
// Arrival Status: OnTime (0)
diff --git a/snippets/csharp/System/Enum/Overview/class2.cs b/snippets/csharp/System/Enum/Overview/class2.cs
index 0e3d0d01c4c..d8175e1d0de 100644
--- a/snippets/csharp/System/Enum/Overview/class2.cs
+++ b/snippets/csharp/System/Enum/Overview/class2.cs
@@ -1,11 +1,11 @@
-using System;
+using System;
public class Example1
{
public static void Main()
{
//
- ArrivalStatus status1 = new ArrivalStatus();
+ ArrivalStatus status1 = new();
Console.WriteLine($"Arrival Status: {status1} ({status1:D})");
// The example displays the following output:
// Arrival Status: OnTime (0)
diff --git a/snippets/csharp/System/Enum/Overview/classconversion1.cs b/snippets/csharp/System/Enum/Overview/classconversion1.cs
index 0165fd21373..fd49f3acb58 100644
--- a/snippets/csharp/System/Enum/Overview/classconversion1.cs
+++ b/snippets/csharp/System/Enum/Overview/classconversion1.cs
@@ -1,12 +1,12 @@
-//
+//
using System;
public class Example3
{
public static void Main()
{
- int[] values = { -3, -1, 0, 1, 5, Int32.MaxValue };
- foreach (var value in values)
+ int[] values = { -3, -1, 0, 1, 5, int.MaxValue };
+ foreach (int value in values)
{
ArrivalStatus status;
if (Enum.IsDefined(typeof(ArrivalStatus), value))
diff --git a/snippets/csharp/System/Enum/Overview/classconversion2.cs b/snippets/csharp/System/Enum/Overview/classconversion2.cs
index 0ecfe35cc36..68594383f35 100644
--- a/snippets/csharp/System/Enum/Overview/classconversion2.cs
+++ b/snippets/csharp/System/Enum/Overview/classconversion2.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example4
{
@@ -6,7 +6,7 @@ public static void Main()
{
//
ArrivalStatus status = ArrivalStatus.Early;
- var number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus)));
+ object number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus)));
Console.WriteLine($"Converted {status} to {number}");
// The example displays the following output:
// Converted Early to 1
diff --git a/snippets/csharp/System/Enum/Overview/classformat1.cs b/snippets/csharp/System/Enum/Overview/classformat1.cs
index b621d0f931d..b5bc20ca003 100644
--- a/snippets/csharp/System/Enum/Overview/classformat1.cs
+++ b/snippets/csharp/System/Enum/Overview/classformat1.cs
@@ -7,7 +7,7 @@ public static void Main()
//
string[] formats = { "G", "F", "D", "X" };
ArrivalStatus status = ArrivalStatus.Late;
- foreach (var fmt in formats)
+ foreach (string fmt in formats)
Console.WriteLine(status.ToString(fmt));
// The example displays the following output:
diff --git a/snippets/csharp/System/Enum/Overview/classiterate.cs b/snippets/csharp/System/Enum/Overview/classiterate.cs
index f9c3667b299..0ce84e25d8e 100644
--- a/snippets/csharp/System/Enum/Overview/classiterate.cs
+++ b/snippets/csharp/System/Enum/Overview/classiterate.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example6
{
@@ -15,7 +15,7 @@ private static void GetEnumByName()
string[] names = Enum.GetNames(typeof(ArrivalStatus));
Console.WriteLine($"Members of {typeof(ArrivalStatus).Name}:");
Array.Sort(names);
- foreach (var name in names)
+ foreach (string name in names)
{
ArrivalStatus status = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), name);
Console.WriteLine($" {status} ({status:D})");
diff --git a/snippets/csharp/System/Enum/Parse/EnumParse.cs b/snippets/csharp/System/Enum/Parse/EnumParse.cs
index 79b3ac23acb..7d22c3500d5 100644
--- a/snippets/csharp/System/Enum/Parse/EnumParse.cs
+++ b/snippets/csharp/System/Enum/Parse/EnumParse.cs
@@ -11,12 +11,11 @@ public static void Main()
Console.WriteLine("The entries of the Colors enumeration are:");
foreach (string colorName in Enum.GetNames(typeof(Colors)))
{
- Console.WriteLine("{0} = {1:D}", colorName,
- Enum.Parse(typeof(Colors), colorName));
+ Console.WriteLine($"{colorName} = {Enum.Parse(typeof(Colors), colorName):D}");
}
Console.WriteLine();
- Colors orange = (Colors) Enum.Parse(typeof(Colors), "Red, Yellow");
+ Colors orange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
Console.WriteLine("The orange value {0:D} has the combined entries of {0}",
orange);
}
diff --git a/snippets/csharp/System/Enum/Parse/ParseExample1.cs b/snippets/csharp/System/Enum/Parse/ParseExample1.cs
index a65d5b5af0e..e6253e74bc2 100644
--- a/snippets/csharp/System/Enum/Parse/ParseExample1.cs
+++ b/snippets/csharp/System/Enum/Parse/ParseExample1.cs
@@ -1,27 +1,29 @@
//
using System;
-[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
- public static void Main()
- {
- string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
- foreach (string colorString in colorStrings)
- {
- try {
- Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
- Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
- else
- Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
- }
- catch (ArgumentException) {
- Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
- }
- }
- }
+ public static void Main()
+ {
+ string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
+ foreach (string colorString in colorStrings)
+ {
+ try
+ {
+ Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);
+ if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ else
+ Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
+ }
+ catch (ArgumentException)
+ {
+ Console.WriteLine($"'{colorString}' is not a member of the Colors enumeration.");
+ }
+ }
+ }
}
// The example displays the following output:
// Converted '0' to None.
diff --git a/snippets/csharp/System/Enum/Parse/ParseExample2.cs b/snippets/csharp/System/Enum/Parse/ParseExample2.cs
index e83be76bbe1..7316f695b37 100644
--- a/snippets/csharp/System/Enum/Parse/ParseExample2.cs
+++ b/snippets/csharp/System/Enum/Parse/ParseExample2.cs
@@ -1,27 +1,29 @@
//
using System;
-[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
- public static void Main()
- {
- string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
- foreach (string colorString in colorStrings)
- {
- try {
- Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString, true);
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
- Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
- else
- Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
- }
- catch (ArgumentException) {
- Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
- }
- }
- }
+ public static void Main()
+ {
+ string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
+ foreach (string colorString in colorStrings)
+ {
+ try
+ {
+ Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString, true);
+ if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ else
+ Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
+ }
+ catch (ArgumentException)
+ {
+ Console.WriteLine($"{colorString} is not a member of the Colors enumeration.");
+ }
+ }
+ }
}
// The example displays the following output:
// Converted '0' to None.
diff --git a/snippets/csharp/System/Enum/ToString/source.cs b/snippets/csharp/System/Enum/ToString/source.cs
index 85cf2ba8205..e5e8250570f 100644
--- a/snippets/csharp/System/Enum/ToString/source.cs
+++ b/snippets/csharp/System/Enum/ToString/source.cs
@@ -1,13 +1,14 @@
//
using System;
-public class EnumSample {
- enum Colors {Red = 1, Blue = 2};
+public class EnumSample
+{
+ enum Colors { Red = 1, Blue = 2 };
- public static void Main() {
+ public static void Main()
+ {
Enum myColors = Colors.Red;
- Console.WriteLine("The value of this instance is '{0}'",
- myColors.ToString());
+ Console.WriteLine($"The value of this instance is '{myColors.ToString()}'");
}
}
/*
diff --git a/snippets/csharp/System/Enum/ToString/tostr.cs b/snippets/csharp/System/Enum/ToString/tostr.cs
index f54d60210f1..2db9c880875 100644
--- a/snippets/csharp/System/Enum/ToString/tostr.cs
+++ b/snippets/csharp/System/Enum/ToString/tostr.cs
@@ -4,30 +4,30 @@
class Sample
{
- enum Colors {Red, Green, Blue, Yellow = 12};
+ enum Colors { Red, Green, Blue, Yellow = 12 };
public static void Main()
{
- Colors myColor = Colors.Yellow;
+ Colors myColor = Colors.Yellow;
- Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"));
- Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d"));
- Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"));
- Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"));
+ Console.WriteLine($"Colors.Red = {Colors.Red.ToString("d")}");
+ Console.WriteLine($"Colors.Green = {Colors.Green.ToString("d")}");
+ Console.WriteLine($"Colors.Blue = {Colors.Blue.ToString("d")}");
+ Console.WriteLine($"Colors.Yellow = {Colors.Yellow.ToString("d")}");
- Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);
+ Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);
- Console.WriteLine("myColor.ToString(\"g\") = {0}", myColor.ToString("g"));
- Console.WriteLine("myColor.ToString(\"G\") = {0}", myColor.ToString("G"));
+ Console.WriteLine($"myColor.ToString(\"g\") = {myColor.ToString("g")}");
+ Console.WriteLine($"myColor.ToString(\"G\") = {myColor.ToString("G")}");
- Console.WriteLine("myColor.ToString(\"x\") = {0}", myColor.ToString("x"));
- Console.WriteLine("myColor.ToString(\"X\") = {0}", myColor.ToString("X"));
+ Console.WriteLine($"myColor.ToString(\"x\") = {myColor.ToString("x")}");
+ Console.WriteLine($"myColor.ToString(\"X\") = {myColor.ToString("X")}");
- Console.WriteLine("myColor.ToString(\"d\") = {0}", myColor.ToString("d"));
- Console.WriteLine("myColor.ToString(\"D\") = {0}", myColor.ToString("D"));
+ Console.WriteLine($"myColor.ToString(\"d\") = {myColor.ToString("d")}");
+ Console.WriteLine($"myColor.ToString(\"D\") = {myColor.ToString("D")}");
- Console.WriteLine("myColor.ToString(\"f\") = {0}", myColor.ToString("f"));
- Console.WriteLine("myColor.ToString(\"F\") = {0}", myColor.ToString("F"));
+ Console.WriteLine($"myColor.ToString(\"f\") = {myColor.ToString("f")}");
+ Console.WriteLine($"myColor.ToString(\"F\") = {myColor.ToString("F")}");
}
}
/*
@@ -48,4 +48,4 @@ public static void Main()
myColor.ToString("f") = Yellow
myColor.ToString("F") = Yellow
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Enum/ToString/tostringbyvalue1.cs b/snippets/csharp/System/Enum/ToString/tostringbyvalue1.cs
index 05acdd2276c..36e7ba138b9 100644
--- a/snippets/csharp/System/Enum/ToString/tostringbyvalue1.cs
+++ b/snippets/csharp/System/Enum/ToString/tostringbyvalue1.cs
@@ -9,25 +9,25 @@ enum Shade
public class Example
{
- public static void Main()
- {
- CallDefault();
- CallWithFormatString();
- }
+ public static void Main()
+ {
+ CallDefault();
+ CallWithFormatString();
+ }
- private static void CallDefault()
- {
- //
- string shadeName = ((Shade) 1).ToString();
- //
- Console.WriteLine(shadeName);
- }
+ private static void CallDefault()
+ {
+ //
+ string shadeName = ((Shade)1).ToString();
+ //
+ Console.WriteLine(shadeName);
+ }
- private static void CallWithFormatString()
- {
- //
- string shadeName = ((Shade) 1).ToString("F");
- //
- Console.WriteLine(shadeName);
- }
+ private static void CallWithFormatString()
+ {
+ //
+ string shadeName = ((Shade)1).ToString("F");
+ //
+ Console.WriteLine(shadeName);
+ }
}
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs b/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
index 7f8caf6ef23..91274c5dfef 100644
--- a/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
+++ b/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
@@ -1,25 +1,25 @@
//
using System;
-[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
- public static void Main()
- {
- string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
- foreach (string colorString in colorStrings)
- {
- Colors colorValue;
- if (Enum.TryParse(colorString, out colorValue))
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
- Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ public static void Main()
+ {
+ string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
+ foreach (string colorString in colorStrings)
+ {
+ Colors colorValue;
+ if (Enum.TryParse(colorString, out colorValue))
+ if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ else
+ Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
else
- Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
- else
- Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
- }
- }
+ Console.WriteLine($"{colorString} is not a member of the Colors enumeration.");
+ }
+ }
}
// The example displays the following output:
// Converted '0' to None.
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs b/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
index 921a837fe80..9ebacd38f1d 100644
--- a/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
+++ b/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
@@ -1,25 +1,25 @@
//
using System;
-[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
- public static void Main()
- {
- string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
- foreach (string colorString in colorStrings)
- {
- Colors colorValue;
- if (Enum.TryParse(colorString, true, out colorValue))
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
- Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ public static void Main()
+ {
+ string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
+ foreach (string colorString in colorStrings)
+ {
+ Colors colorValue;
+ if (Enum.TryParse(colorString, true, out colorValue))
+ if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
+ else
+ Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
else
- Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
- else
- Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
- }
- }
+ Console.WriteLine($"{colorString} is not a member of the Colors enumeration.");
+ }
+ }
}
// The example displays the following output:
// Converted '0' to None.
diff --git a/snippets/csharp/System/Environment+SpecialFolder/Overview/getfolderpath.cs b/snippets/csharp/System/Environment+SpecialFolder/Overview/getfolderpath.cs
index 2562537561a..554fd7bb729 100644
--- a/snippets/csharp/System/Environment+SpecialFolder/Overview/getfolderpath.cs
+++ b/snippets/csharp/System/Environment+SpecialFolder/Overview/getfolderpath.cs
@@ -6,9 +6,8 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- Console.WriteLine("GetFolderPath: {0}",
- Environment.GetFolderPath(Environment.SpecialFolder.System));
+ Console.WriteLine();
+ Console.WriteLine($"GetFolderPath: {Environment.GetFolderPath(Environment.SpecialFolder.System)}");
}
}
/*
@@ -16,4 +15,4 @@ public static void Main()
GetFolderPath: C:\WINNT\System32
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/CommandLine/commandline.cs b/snippets/csharp/System/Environment/CommandLine/commandline.cs
index bda0f03e1a8..d48366c653f 100644
--- a/snippets/csharp/System/Environment/CommandLine/commandline.cs
+++ b/snippets/csharp/System/Environment/CommandLine/commandline.cs
@@ -5,13 +5,13 @@ class Example
{
public static void Main()
{
- Console.WriteLine();
- // Invoke this sample with an arbitrary set of command line arguments.
- Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
+ Console.WriteLine();
+ // Invoke this sample with an arbitrary set of command line arguments.
+ Console.WriteLine($"CommandLine: {Environment.CommandLine}");
}
}
// The example displays output like the following:
// C:\>env0 ARBITRARY TEXT
//
// CommandLine: env0 ARBITRARY TEXT
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/CurrentDirectory/Vars1.cs b/snippets/csharp/System/Environment/CurrentDirectory/Vars1.cs
index 90ddf42700a..4f5332af299 100644
--- a/snippets/csharp/System/Environment/CurrentDirectory/Vars1.cs
+++ b/snippets/csharp/System/Environment/CurrentDirectory/Vars1.cs
@@ -4,21 +4,21 @@
public class Example
{
- public static void Main()
- {
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- // Change the directory to %WINDIR%
- Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
- DirectoryInfo info = new DirectoryInfo(".");
+ public static void Main()
+ {
+ if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+ {
+ // Change the directory to %WINDIR%
+ Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
+ DirectoryInfo info = new(".");
- Console.WriteLine("Directory Info: " + info.FullName);
- }
- else
- {
- Console.WriteLine("This example runs on Windows only.");
- }
- }
+ Console.WriteLine("Directory Info: " + info.FullName);
+ }
+ else
+ {
+ Console.WriteLine("This example runs on Windows only.");
+ }
+ }
}
// The example displays output like the following on a .NET implementation running on Windows:
// Directory Info: C:\windows
diff --git a/snippets/csharp/System/Environment/CurrentDirectory/environmentsample.cs b/snippets/csharp/System/Environment/CurrentDirectory/environmentsample.cs
index e629a817ab8..baeb3b5a2a8 100644
--- a/snippets/csharp/System/Environment/CurrentDirectory/environmentsample.cs
+++ b/snippets/csharp/System/Environment/CurrentDirectory/environmentsample.cs
@@ -1,40 +1,38 @@
using System;
-using System.Xml;
-using System.IO;
-using System.Collections;
-using System.Reflection;
+
+
+
+
//
-public class EnvironmentSample {
-
- public static void Main() {
-
- //
- OuterMethod();
- //
-
- //
-
- Console.WriteLine("Initial WS:"+Environment.WorkingSet);
- int[] i1,i2,i3;
- i1 = new int[10000];
- Console.WriteLine("WS 1:"+Environment.WorkingSet);
- i2 = new int[10000];
- Console.WriteLine("WS 2:"+Environment.WorkingSet);
- i3 = new int[10000];
- Console.WriteLine("WS 3:"+Environment.WorkingSet);
-
- //
- }
-
- //
- static void OuterMethod() {
- InnerMethod();
- }
-
- static void InnerMethod() {
- Console.WriteLine("StackTrace after calling Main()->OuterMethod()->InnerMethod():" + Environment.StackTrace);
- }
- //
+public class EnvironmentSample
+{
+
+ public static void Main()
+ {
+
+ //
+ OuterMethod();
+ //
+
+ //
+
+ Console.WriteLine("Initial WS:" + Environment.WorkingSet);
+ int[] i1, i2, i3;
+ i1 = new int[10000];
+ Console.WriteLine("WS 1:" + Environment.WorkingSet);
+ i2 = new int[10000];
+ Console.WriteLine("WS 2:" + Environment.WorkingSet);
+ i3 = new int[10000];
+ Console.WriteLine("WS 3:" + Environment.WorkingSet);
+
+ //
+ }
+
+ //
+ static void OuterMethod() => InnerMethod();
+
+ static void InnerMethod() => Console.WriteLine("StackTrace after calling Main()->OuterMethod()->InnerMethod():" + Environment.StackTrace);
+ //
}
//
diff --git a/snippets/csharp/System/Environment/ExitCode/double.cs b/snippets/csharp/System/Environment/ExitCode/double.cs
index ffcad2bd200..8fd7efaff5a 100644
--- a/snippets/csharp/System/Environment/ExitCode/double.cs
+++ b/snippets/csharp/System/Environment/ExitCode/double.cs
@@ -4,27 +4,29 @@
public class Example
{
- private const int ERROR_BAD_ARGUMENTS = 0xA0;
- private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
- private const int ERROR_INVALID_COMMAND_LINE = 0x667;
+ private const int ERROR_BAD_ARGUMENTS = 0xA0;
+ private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
+ private const int ERROR_INVALID_COMMAND_LINE = 0x667;
- public static void Main()
- {
- string[] args = Environment.GetCommandLineArgs();
- if (args.Length == 1) {
- Environment.ExitCode = ERROR_INVALID_COMMAND_LINE;
- }
- else {
- BigInteger value = 0;
- if (BigInteger.TryParse(args[1], out value))
- if (value <= Int32.MinValue || value >= Int32.MaxValue)
- Environment.ExitCode = ERROR_ARITHMETIC_OVERFLOW;
- else
- Console.WriteLine("Result: {0}", value * 2);
+ public static void Main()
+ {
+ string[] args = Environment.GetCommandLineArgs();
+ if (args.Length == 1)
+ {
+ Environment.ExitCode = ERROR_INVALID_COMMAND_LINE;
+ }
+ else
+ {
+ BigInteger value = 0;
+ if (BigInteger.TryParse(args[1], out value))
+ if (value <= int.MinValue || value >= int.MaxValue)
+ Environment.ExitCode = ERROR_ARITHMETIC_OVERFLOW;
+ else
+ Console.WriteLine($"Result: {value * 2}");
- else
- Environment.ExitCode = ERROR_BAD_ARGUMENTS;
- }
- }
+ else
+ Environment.ExitCode = ERROR_BAD_ARGUMENTS;
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Environment/ExitCode/double1.cs b/snippets/csharp/System/Environment/ExitCode/double1.cs
index c95ac8900dd..58fd80c9fa4 100644
--- a/snippets/csharp/System/Environment/ExitCode/double1.cs
+++ b/snippets/csharp/System/Environment/ExitCode/double1.cs
@@ -4,29 +4,31 @@
public class Example
{
- private const int ERROR_SUCCESS = 0;
- private const int ERROR_BAD_ARGUMENTS = 0xA0;
- private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
- private const int ERROR_INVALID_COMMAND_LINE = 0x667;
+ private const int ERROR_SUCCESS = 0;
+ private const int ERROR_BAD_ARGUMENTS = 0xA0;
+ private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
+ private const int ERROR_INVALID_COMMAND_LINE = 0x667;
- public static int Main()
- {
- string[] args = Environment.GetCommandLineArgs();
- if (args.Length == 1) {
- return ERROR_INVALID_COMMAND_LINE;
- }
- else {
- BigInteger value = 0;
- if (BigInteger.TryParse(args[1], out value))
- if (value <= Int32.MinValue || value >= Int32.MaxValue)
- return ERROR_ARITHMETIC_OVERFLOW;
- else
- Console.WriteLine("Result: {0}", value * 2);
+ public static int Main()
+ {
+ string[] args = Environment.GetCommandLineArgs();
+ if (args.Length == 1)
+ {
+ return ERROR_INVALID_COMMAND_LINE;
+ }
+ else
+ {
+ BigInteger value = 0;
+ if (BigInteger.TryParse(args[1], out value))
+ if (value <= int.MinValue || value >= int.MaxValue)
+ return ERROR_ARITHMETIC_OVERFLOW;
+ else
+ Console.WriteLine($"Result: {value * 2}");
- else
- return ERROR_BAD_ARGUMENTS;
- }
- return ERROR_SUCCESS;
- }
+ else
+ return ERROR_BAD_ARGUMENTS;
+ }
+ return ERROR_SUCCESS;
+ }
}
//
diff --git a/snippets/csharp/System/Environment/FailFast/ff.cs b/snippets/csharp/System/Environment/FailFast/ff.cs
index 2598ca5898f..cc589367b06 100644
--- a/snippets/csharp/System/Environment/FailFast/ff.cs
+++ b/snippets/csharp/System/Environment/FailFast/ff.cs
@@ -5,21 +5,21 @@ class Example
{
public static void Main()
{
- string causeOfFailure = "A catastrophic failure has occurred.";
+ string causeOfFailure = "A catastrophic failure has occurred.";
- // Assume your application has failed catastrophically and must
- // terminate immediately. The try-finally block is not executed
- // and is included only to demonstrate that instructions within
- // try-catch blocks and finalizers are not performed.
- try
- {
- Environment.FailFast(causeOfFailure);
- }
- finally
- {
- Console.WriteLine("This finally block will not be executed.");
- }
- }
+ // Assume your application has failed catastrophically and must
+ // terminate immediately. The try-finally block is not executed
+ // and is included only to demonstrate that instructions within
+ // try-catch blocks and finalizers are not performed.
+ try
+ {
+ Environment.FailFast(causeOfFailure);
+ }
+ finally
+ {
+ Console.WriteLine("This finally block will not be executed.");
+ }
+ }
}
/*
The example produces no output because the application is terminated.
diff --git a/snippets/csharp/System/Environment/GetCommandLineArgs/getcommandlineargs.cs b/snippets/csharp/System/Environment/GetCommandLineArgs/getcommandlineargs.cs
index 418afb5b601..60761aab707 100644
--- a/snippets/csharp/System/Environment/GetCommandLineArgs/getcommandlineargs.cs
+++ b/snippets/csharp/System/Environment/GetCommandLineArgs/getcommandlineargs.cs
@@ -8,7 +8,7 @@ public static void Main()
Console.WriteLine();
// Invoke this sample with an arbitrary set of command line arguments.
string[] arguments = Environment.GetCommandLineArgs();
- Console.WriteLine("GetCommandLineArgs: {0}", string.Join(", ", arguments));
+ Console.WriteLine($"GetCommandLineArgs: {string.Join(", ", arguments)}");
}
}
/*
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs b/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
index 00f4188cc34..6b2823b05a5 100644
--- a/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
@@ -2,46 +2,48 @@
public class Example
{
- public static void Main()
- {
- string value;
- bool toDelete = false;
+ public static void Main()
+ {
+ string value;
+ bool toDelete = false;
- // Check whether the environment variable exists.
- value = Environment.GetEnvironmentVariable("Test1");
- // If necessary, create it.
- if (value == null)
- {
- Environment.SetEnvironmentVariable("Test1", "Value1");
- toDelete = true;
+ // Check whether the environment variable exists.
+ value = Environment.GetEnvironmentVariable("Test1");
+ // If necessary, create it.
+ if (value == null)
+ {
+ Environment.SetEnvironmentVariable("Test1", "Value1");
+ toDelete = true;
- // Now retrieve it.
- value = Environment.GetEnvironmentVariable("Test1");
- }
- // Display the value.
- Console.WriteLine($"Test1: {value}\n");
+ // Now retrieve it.
+ value = Environment.GetEnvironmentVariable("Test1");
+ }
+ // Display the value.
+ Console.WriteLine($"Test1: {value}\n");
- // Confirm that the value can only be retrieved from the process
- // environment block if running on a Windows system.
- if (Environment.OSVersion.Platform == PlatformID.Win32NT)
- {
- Console.WriteLine("Attempting to retrieve Test1 from:");
- foreach (EnvironmentVariableTarget enumValue in
- Enum.GetValues(typeof(EnvironmentVariableTarget))) {
- value = Environment.GetEnvironmentVariable("Test1", enumValue);
- Console.WriteLine($" {enumValue}: {(value != null ? "found" : "not found")}");
- }
- Console.WriteLine();
- }
+ // Confirm that the value can only be retrieved from the process
+ // environment block if running on a Windows system.
+ if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+ {
+ Console.WriteLine("Attempting to retrieve Test1 from:");
+ foreach (EnvironmentVariableTarget enumValue in
+ Enum.GetValues(typeof(EnvironmentVariableTarget)))
+ {
+ value = Environment.GetEnvironmentVariable("Test1", enumValue);
+ Console.WriteLine($" {enumValue}: {(value != null ? "found" : "not found")}");
+ }
+ Console.WriteLine();
+ }
- // If we've created it, now delete it.
- if (toDelete) {
- Environment.SetEnvironmentVariable("Test1", null);
- // Confirm the deletion.
- if (Environment.GetEnvironmentVariable("Test1") == null)
- Console.WriteLine("Test1 has been deleted.");
- }
- }
+ // If we've created it, now delete it.
+ if (toDelete)
+ {
+ Environment.SetEnvironmentVariable("Test1", null);
+ // Confirm the deletion.
+ if (Environment.GetEnvironmentVariable("Test1") == null)
+ Console.WriteLine("Test1 has been deleted.");
+ }
+ }
}
// The example displays the following output if run on a Windows system:
// Test1: Value1
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs b/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
index bd6b78bc818..8d217a23ef1 100644
--- a/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
@@ -1,6 +1,6 @@
using System;
-using System.Collections;
-using Microsoft.Win32;
+
+
class Sample
{
@@ -32,36 +32,36 @@ public static void Main()
EnvironmentVariableTarget.Machine);
// Define an array of environment variables.
- string[] envVars = { defaultEnvVar,processEnvVar, userEnvVar, machineEnvVar };
+ string[] envVars = { defaultEnvVar, processEnvVar, userEnvVar, machineEnvVar };
// Try to get the environment variables from each target.
// The default (no specified target).
Console.WriteLine("Retrieving environment variables from the default target:");
- foreach (var envVar in envVars)
+ foreach (string envVar in envVars)
{
- var value = Environment.GetEnvironmentVariable(envVar) ?? "(none)";
- Console.WriteLine($" {envVar}: {value}");
+ string value = Environment.GetEnvironmentVariable(envVar) ?? "(none)";
+ Console.WriteLine($" {envVar}: {value}");
}
// The process block.
Console.WriteLine("\nRetrieving environment variables from the Process target:");
- foreach (var envVar in envVars)
+ foreach (string envVar in envVars)
{
- var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process) ?? "(none)";
- Console.WriteLine($" {envVar}: {value}");
+ string value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process) ?? "(none)";
+ Console.WriteLine($" {envVar}: {value}");
}
// The user block.
Console.WriteLine("\nRetrieving environment variables from the User target:");
- foreach (var envVar in envVars)
+ foreach (string envVar in envVars)
{
- var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User) ?? "(none)";
- Console.WriteLine($" {envVar}: {value}");
+ string value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User) ?? "(none)";
+ Console.WriteLine($" {envVar}: {value}");
}
// The machine block.
Console.WriteLine("\nRetrieving environment variables from the Machine target:");
- foreach (var envVar in envVars)
+ foreach (string envVar in envVars)
{
- var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Machine) ?? "(none)";
- Console.WriteLine($" {envVar}: {value}");
+ string value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Machine) ?? "(none)";
+ Console.WriteLine($" {envVar}: {value}");
}
// Delete the environment variable for each target.
@@ -136,4 +136,4 @@ public static void Main()
// userEnvVar: (none)
// machineEnvVar: (none)
//
-// Deleting environment variables for each target...
\ No newline at end of file
+// Deleting environment variables for each target...
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariables/getenvironmentvariables.cs b/snippets/csharp/System/Environment/GetEnvironmentVariables/getenvironmentvariables.cs
index a8422999e83..6d1b1c2a73b 100644
--- a/snippets/csharp/System/Environment/GetEnvironmentVariables/getenvironmentvariables.cs
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariables/getenvironmentvariables.cs
@@ -7,14 +7,14 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- Console.WriteLine("GetEnvironmentVariables: ");
- foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
- Console.WriteLine(" {0} = {1}", de.Key, de.Value);
+ Console.WriteLine();
+ Console.WriteLine("GetEnvironmentVariables: ");
+ foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
+ Console.WriteLine($" {de.Key} = {de.Value}");
}
}
// Output from the example is not shown, since it is:
// Lengthy.
// Specific to the machine on which the example is run.
// May reveal information that should remain secure.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/GetLogicalDrives/getlogicaldrives.cs b/snippets/csharp/System/Environment/GetLogicalDrives/getlogicaldrives.cs
index b4597e18ada..22760533cbb 100644
--- a/snippets/csharp/System/Environment/GetLogicalDrives/getlogicaldrives.cs
+++ b/snippets/csharp/System/Environment/GetLogicalDrives/getlogicaldrives.cs
@@ -6,9 +6,9 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- String[] drives = Environment.GetLogicalDrives();
- Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
+ Console.WriteLine();
+ string[] drives = Environment.GetLogicalDrives();
+ Console.WriteLine($"GetLogicalDrives: {string.Join(", ", drives)}");
}
}
/*
@@ -16,4 +16,4 @@ public static void Main()
GetLogicalDrives: A:\, C:\, D:\
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/MachineName/machinename.cs b/snippets/csharp/System/Environment/MachineName/machinename.cs
index b5a757f3baa..92e6c8cf31f 100644
--- a/snippets/csharp/System/Environment/MachineName/machinename.cs
+++ b/snippets/csharp/System/Environment/MachineName/machinename.cs
@@ -6,9 +6,9 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
-// <-- Keep this information secure! -->
- Console.WriteLine("MachineName: {0}", Environment.MachineName);
+ Console.WriteLine();
+ // <-- Keep this information secure! -->
+ Console.WriteLine($"MachineName: {Environment.MachineName}");
}
}
/*
@@ -17,4 +17,4 @@ public static void Main()
MachineName: !---OMITTED---!
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/Overview/env0.cs b/snippets/csharp/System/Environment/Overview/env0.cs
index 902661ce87d..190e4264ace 100644
--- a/snippets/csharp/System/Environment/Overview/env0.cs
+++ b/snippets/csharp/System/Environment/Overview/env0.cs
@@ -14,67 +14,65 @@ public static void Main()
Console.WriteLine("-- Environment members --");
// Invoke this sample with an arbitrary set of command line arguments.
- Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
+ Console.WriteLine($"CommandLine: {Environment.CommandLine}");
string[] arguments = Environment.GetCommandLineArgs();
- Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
+ Console.WriteLine($"GetCommandLineArgs: {string.Join(", ", arguments)}");
// <-- Keep this information secure! -->
- Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
+ Console.WriteLine($"CurrentDirectory: {Environment.CurrentDirectory}");
- Console.WriteLine("ExitCode: {0}", Environment.ExitCode);
+ Console.WriteLine($"ExitCode: {Environment.ExitCode}");
- Console.WriteLine("HasShutdownStarted: {0}", Environment.HasShutdownStarted);
+ Console.WriteLine($"HasShutdownStarted: {Environment.HasShutdownStarted}");
// <-- Keep this information secure! -->
- Console.WriteLine("MachineName: {0}", Environment.MachineName);
+ Console.WriteLine($"MachineName: {Environment.MachineName}");
Console.WriteLine("NewLine: {0} first line{0} second line{0} third line",
Environment.NewLine);
- Console.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString());
+ Console.WriteLine($"OSVersion: {Environment.OSVersion.ToString()}");
- Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
+ Console.WriteLine($"StackTrace: '{Environment.StackTrace}'");
// <-- Keep this information secure! -->
- Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
+ Console.WriteLine($"SystemDirectory: {Environment.SystemDirectory}");
- Console.WriteLine("TickCount: {0}", Environment.TickCount);
+ Console.WriteLine($"TickCount: {Environment.TickCount}");
// <-- Keep this information secure! -->
- Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
+ Console.WriteLine($"UserDomainName: {Environment.UserDomainName}");
- Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
+ Console.WriteLine($"UserInteractive: {Environment.UserInteractive}");
// <-- Keep this information secure! -->
- Console.WriteLine("UserName: {0}", Environment.UserName);
+ Console.WriteLine($"UserName: {Environment.UserName}");
- Console.WriteLine("Version: {0}", Environment.Version.ToString());
+ Console.WriteLine($"Version: {Environment.Version.ToString()}");
- Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);
+ Console.WriteLine($"WorkingSet: {Environment.WorkingSet}");
// No example for Exit(exitCode) because doing so would terminate this example.
// <-- Keep this information secure! -->
string query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
str = Environment.ExpandEnvironmentVariables(query);
- Console.WriteLine("ExpandEnvironmentVariables: {0} {1}", nl, str);
+ Console.WriteLine($"ExpandEnvironmentVariables: {nl} {str}");
- Console.WriteLine("GetEnvironmentVariable: {0} My temporary directory is {1}.", nl,
- Environment.GetEnvironmentVariable("TEMP"));
+ Console.WriteLine($"GetEnvironmentVariable: {nl} My temporary directory is {Environment.GetEnvironmentVariable("TEMP")}.");
Console.WriteLine("GetEnvironmentVariables: ");
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry de in environmentVariables)
{
- Console.WriteLine(" {0} = {1}", de.Key, de.Value);
+ Console.WriteLine($" {de.Key} = {de.Value}");
}
- Console.WriteLine("GetFolderPath: {0}",
- Environment.GetFolderPath(Environment.SpecialFolder.System));
+ Console.WriteLine($"GetFolderPath: {Environment.GetFolderPath(Environment.SpecialFolder.System)}");
string[] drives = Environment.GetLogicalDrives();
- Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
+ Console.WriteLine($"GetLogicalDrives: {string.Join(", ", drives)}");
}
}
/*
@@ -117,4 +115,4 @@ at Sample.Main()'
GetLogicalDrives: A:\, C:\, D:\
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/ProcessorCount/pc.cs b/snippets/csharp/System/Environment/ProcessorCount/pc.cs
index 81d01ad5ba5..4fb19eb695f 100644
--- a/snippets/csharp/System/Environment/ProcessorCount/pc.cs
+++ b/snippets/csharp/System/Environment/ProcessorCount/pc.cs
@@ -5,16 +5,13 @@
class Sample
{
- public static void Main()
- {
- Console.WriteLine("The number of processors " +
+ public static void Main() => Console.WriteLine("The number of processors " +
"on this computer is {0}.",
Environment.ProcessorCount);
- }
}
/*
This example produces the following results:
The number of processors on this computer is 1.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/StackTrace/stacktrace.cs b/snippets/csharp/System/Environment/StackTrace/stacktrace.cs
index 3bcae8de82e..09572f670ed 100644
--- a/snippets/csharp/System/Environment/StackTrace/stacktrace.cs
+++ b/snippets/csharp/System/Environment/StackTrace/stacktrace.cs
@@ -6,8 +6,8 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
+ Console.WriteLine();
+ Console.WriteLine($"StackTrace: '{Environment.StackTrace}'");
}
}
/*
@@ -18,4 +18,4 @@ at System.Environment.GetStackTrace(Exception e)
at System.Environment.get_StackTrace()
at Sample.Main()'
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/SystemDirectory/systemdirectory.cs b/snippets/csharp/System/Environment/SystemDirectory/systemdirectory.cs
index 840ca701705..63f58fb0597 100644
--- a/snippets/csharp/System/Environment/SystemDirectory/systemdirectory.cs
+++ b/snippets/csharp/System/Environment/SystemDirectory/systemdirectory.cs
@@ -6,9 +6,9 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
-// <-- Keep this information secure! -->
- Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
+ Console.WriteLine();
+ // <-- Keep this information secure! -->
+ Console.WriteLine($"SystemDirectory: {Environment.SystemDirectory}");
}
}
/*
@@ -16,4 +16,4 @@ public static void Main()
SystemDirectory: C:\WINNT\System32
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/UserInteractive/userinteractive.cs b/snippets/csharp/System/Environment/UserInteractive/userinteractive.cs
index 16689fb595c..6d9d8e36d7f 100644
--- a/snippets/csharp/System/Environment/UserInteractive/userinteractive.cs
+++ b/snippets/csharp/System/Environment/UserInteractive/userinteractive.cs
@@ -6,8 +6,8 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
+ Console.WriteLine();
+ Console.WriteLine($"UserInteractive: {Environment.UserInteractive}");
}
}
/*
@@ -15,4 +15,4 @@ public static void Main()
UserInteractive: True
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/UserName/username.cs b/snippets/csharp/System/Environment/UserName/username.cs
index d8f49853198..e04a26309a5 100644
--- a/snippets/csharp/System/Environment/UserName/username.cs
+++ b/snippets/csharp/System/Environment/UserName/username.cs
@@ -6,9 +6,9 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
-// <-- Keep this information secure! -->
- Console.WriteLine("UserName: {0}", Environment.UserName);
+ Console.WriteLine();
+ // <-- Keep this information secure! -->
+ Console.WriteLine($"UserName: {Environment.UserName}");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/Version/version.cs b/snippets/csharp/System/Environment/Version/version.cs
index e49e12231d0..adf97491522 100644
--- a/snippets/csharp/System/Environment/Version/version.cs
+++ b/snippets/csharp/System/Environment/Version/version.cs
@@ -6,8 +6,8 @@ class Sample
{
public static void Main()
{
- Console.WriteLine();
- Console.WriteLine("Version: {0}", Environment.Version.ToString());
+ Console.WriteLine();
+ Console.WriteLine($"Version: {Environment.Version.ToString()}");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Environment/WorkingSet/workingset.cs b/snippets/csharp/System/Environment/WorkingSet/workingset.cs
index ec0aaf16a3e..a16444457d3 100644
--- a/snippets/csharp/System/Environment/WorkingSet/workingset.cs
+++ b/snippets/csharp/System/Environment/WorkingSet/workingset.cs
@@ -4,14 +4,11 @@
class Sample
{
- public static void Main()
- {
- Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);
- }
+ public static void Main() => Console.WriteLine($"WorkingSet: {Environment.WorkingSet}");
}
/*
This example produces the following results:
WorkingSet: 5038080
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/EventArgs/Overview/programnodata.cs b/snippets/csharp/System/EventArgs/Overview/programnodata.cs
index 9c28189de8e..4b671d8b7a8 100644
--- a/snippets/csharp/System/EventArgs/Overview/programnodata.cs
+++ b/snippets/csharp/System/EventArgs/Overview/programnodata.cs
@@ -30,10 +30,7 @@ class Counter
private readonly int _threshold;
private int _total;
- public Counter(int passedThreshold)
- {
- _threshold = passedThreshold;
- }
+ public Counter(int passedThreshold) => _threshold = passedThreshold;
public void Add(int x)
{
@@ -44,10 +41,7 @@ public void Add(int x)
}
}
- protected virtual void OnThresholdReached(EventArgs e)
- {
- ThresholdReached?.Invoke(this, e);
- }
+ protected virtual void OnThresholdReached(EventArgs e) => ThresholdReached?.Invoke(this, e);
public event EventHandler? ThresholdReached;
}
diff --git a/snippets/csharp/System/EventArgs/Overview/programtruncated.cs b/snippets/csharp/System/EventArgs/Overview/programtruncated.cs
index 09a13d6947a..ec014eb6be2 100644
--- a/snippets/csharp/System/EventArgs/Overview/programtruncated.cs
+++ b/snippets/csharp/System/EventArgs/Overview/programtruncated.cs
@@ -13,10 +13,7 @@ public static void Main()
// provide remaining implementation for the class
}
- static void c_ThresholdReached(object? sender, EventArgs e)
- {
- Console.WriteLine("The threshold was reached.");
- }
+ static void c_ThresholdReached(object? sender, EventArgs e) => Console.WriteLine("The threshold was reached.");
}
//
diff --git a/snippets/csharp/System/EventArgs/Overview/programwithdata.cs b/snippets/csharp/System/EventArgs/Overview/programwithdata.cs
index 7f93e9d112a..72c60e81c62 100644
--- a/snippets/csharp/System/EventArgs/Overview/programwithdata.cs
+++ b/snippets/csharp/System/EventArgs/Overview/programwithdata.cs
@@ -20,7 +20,7 @@ public static void Main()
static void c_ThresholdReached(object? sender, ThresholdReachedEventArgs e)
{
- Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
+ Console.WriteLine($"The threshold of {e.Threshold} was reached at {e.TimeReached}.");
Environment.Exit(0);
}
}
@@ -30,10 +30,7 @@ class Counter
private readonly int _threshold;
private int _total;
- public Counter(int passedThreshold)
- {
- _threshold = passedThreshold;
- }
+ public Counter(int passedThreshold) => _threshold = passedThreshold;
public void Add(int x)
{
@@ -49,10 +46,7 @@ public void Add(int x)
}
}
- protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
- {
- ThresholdReached?.Invoke(this, e);
- }
+ protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) => ThresholdReached?.Invoke(this, e);
public event EventHandler? ThresholdReached;
}
diff --git a/snippets/csharp/System/EventArgs/Overview/programwithdelegate.cs b/snippets/csharp/System/EventArgs/Overview/programwithdelegate.cs
index aa69b44d6ba..6eb2b358f17 100644
--- a/snippets/csharp/System/EventArgs/Overview/programwithdelegate.cs
+++ b/snippets/csharp/System/EventArgs/Overview/programwithdelegate.cs
@@ -20,7 +20,7 @@ public static void Main()
public static void c_ThresholdReached(object? sender, ThresholdReachedEventArgs e)
{
- Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
+ Console.WriteLine($"The threshold of {e.Threshold} was reached at {e.TimeReached}.");
Environment.Exit(0);
}
}
@@ -30,10 +30,7 @@ class Counter
private readonly int _threshold;
private int _total;
- public Counter(int passedThreshold)
- {
- _threshold = passedThreshold;
- }
+ public Counter(int passedThreshold) => _threshold = passedThreshold;
public void Add(int x)
{
@@ -49,10 +46,7 @@ public void Add(int x)
}
}
- protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
- {
- ThresholdReached?.Invoke(this, e);
- }
+ protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) => ThresholdReached?.Invoke(this, e);
public event ThresholdReachedEventHandler? ThresholdReached;
}
diff --git a/snippets/csharp/System/Exception/.ctor/new.cs b/snippets/csharp/System/Exception/.ctor/new.cs
index fb73d1f5f27..1ab7dcc2538 100644
--- a/snippets/csharp/System/Exception/.ctor/new.cs
+++ b/snippets/csharp/System/Exception/.ctor/new.cs
@@ -7,9 +7,9 @@ namespace NDP_UE_CS
// Derive an exception with a predefined message.
class NotEvenException : Exception
{
- public NotEvenException( ) :
- base( "The argument to a function requiring " +
- "even input is not divisible by 2." )
+ public NotEvenException() :
+ base("The argument to a function requiring " +
+ "even input is not divisible by 2.")
{ }
}
@@ -19,67 +19,65 @@ public static void Main()
{
Console.WriteLine(
"This example of the Exception( ) constructor " +
- "generates the following output." );
+ "generates the following output.");
Console.WriteLine(
"\nHere, an exception is thrown using the \n" +
- "parameterless constructor of the base class.\n" );
+ "parameterless constructor of the base class.\n");
- CalcHalf( 12 );
- CalcHalf( 15 );
+ CalcHalf(12);
+ CalcHalf(15);
Console.WriteLine(
"\nHere, an exception is thrown using the \n" +
- "parameterless constructor of a derived class.\n" );
+ "parameterless constructor of a derived class.\n");
- CalcHalf2( 24 );
- CalcHalf2( 27 );
+ CalcHalf2(24);
+ CalcHalf2(27);
}
-
+
// Half throws a base exception if the input is not even.
- static int Half( int input )
+ static int Half(int input)
{
- if( input % 2 != 0 )
- throw new Exception( );
+ if (input % 2 != 0)
+ throw new Exception();
else return input / 2;
}
// Half2 throws a derived exception if the input is not even.
- static int Half2( int input )
+ static int Half2(int input)
{
- if( input % 2 != 0 )
- throw new NotEvenException( );
+ if (input % 2 != 0)
+ throw new NotEvenException();
else return input / 2;
}
// CalcHalf calls Half and catches any thrown exceptions.
- static void CalcHalf(int input )
+ static void CalcHalf(int input)
{
try
{
- int halfInput = Half( input );
- Console.WriteLine(
- "Half of {0} is {1}.", input, halfInput );
+ int halfInput = Half(input);
+ Console.WriteLine($"Half of {input} is {halfInput}.");
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
// CalcHalf2 calls Half2 and catches any thrown exceptions.
- static void CalcHalf2(int input )
+ static void CalcHalf2(int input)
{
try
{
- int halfInput = Half2( input );
- Console.WriteLine(
- "Half of {0} is {1}.", input, halfInput );
+ int halfInput = Half2(input);
+ Console.WriteLine($"Half of {input} is {halfInput}.");
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
}
diff --git a/snippets/csharp/System/Exception/.ctor/news.cs b/snippets/csharp/System/Exception/.ctor/news.cs
index 4630ae15843..75ee5b3c102 100644
--- a/snippets/csharp/System/Exception/.ctor/news.cs
+++ b/snippets/csharp/System/Exception/.ctor/news.cs
@@ -11,13 +11,12 @@ class NotEvenException : Exception
"The argument to a function requiring " +
"even input is not divisible by 2.";
- public NotEvenException( ) :
- base( notEvenMessage )
+ public NotEvenException() :
+ base(notEvenMessage)
{ }
- public NotEvenException( string auxMessage ) :
- base( String.Format( "{0} - {1}",
- auxMessage, notEvenMessage ) )
+ public NotEvenException(string auxMessage) :
+ base($"{auxMessage} - {notEvenMessage}")
{ }
}
@@ -27,70 +26,66 @@ public static void Main()
{
Console.WriteLine(
"This example of the Exception( string )\n" +
- "constructor generates the following output." );
+ "constructor generates the following output.");
Console.WriteLine(
"\nHere, an exception is thrown using the \n" +
- "constructor of the base class.\n" );
+ "constructor of the base class.\n");
- CalcHalf( 18 );
- CalcHalf( 21 );
+ CalcHalf(18);
+ CalcHalf(21);
Console.WriteLine(
"\nHere, an exception is thrown using the \n" +
- "constructor of a derived class.\n" );
+ "constructor of a derived class.\n");
- CalcHalf2( 30 );
- CalcHalf2( 33 );
+ CalcHalf2(30);
+ CalcHalf2(33);
}
-
+
// Half throws a base exception if the input is not even.
- static int Half( int input )
+ static int Half(int input)
{
- if( input % 2 != 0 )
- throw new Exception( String.Format(
- "The argument {0} is not divisible by 2.",
- input ) );
+ if (input % 2 != 0)
+ throw new Exception($"The argument {input} is not divisible by 2.");
else return input / 2;
}
// Half2 throws a derived exception if the input is not even.
- static int Half2( int input )
+ static int Half2(int input)
{
- if( input % 2 != 0 )
+ if (input % 2 != 0)
throw new NotEvenException(
- String.Format( "Invalid argument: {0}", input ) );
+ $"Invalid argument: {input}");
else return input / 2;
}
// CalcHalf calls Half and catches any thrown exceptions.
- static void CalcHalf(int input )
+ static void CalcHalf(int input)
{
try
{
- int halfInput = Half( input );
- Console.WriteLine(
- "Half of {0} is {1}.", input, halfInput );
+ int halfInput = Half(input);
+ Console.WriteLine($"Half of {input} is {halfInput}.");
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
// CalcHalf2 calls Half2 and catches any thrown exceptions.
- static void CalcHalf2(int input )
+ static void CalcHalf2(int input)
{
try
{
- int halfInput = Half2( input );
- Console.WriteLine(
- "Half of {0} is {1}.", input, halfInput );
+ int halfInput = Half2(input);
+ Console.WriteLine($"Half of {input} is {halfInput}.");
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
}
diff --git a/snippets/csharp/System/Exception/.ctor/newsi.cs b/snippets/csharp/System/Exception/.ctor/newsi.cs
index 010338b3d25..c8f2cfed403 100644
--- a/snippets/csharp/System/Exception/.ctor/newsi.cs
+++ b/snippets/csharp/System/Exception/.ctor/newsi.cs
@@ -10,47 +10,44 @@ class LogTableOverflowException : Exception
const string overflowMessage =
"The log table has overflowed.";
- public LogTableOverflowException( ) :
- base( overflowMessage )
+ public LogTableOverflowException() :
+ base(overflowMessage)
{ }
- public LogTableOverflowException( string auxMessage ) :
- base( String.Format( "{0} - {1}",
- overflowMessage, auxMessage ) )
+ public LogTableOverflowException(string auxMessage) :
+ base($"{overflowMessage} - {auxMessage}")
{ }
public LogTableOverflowException(
- string auxMessage, Exception inner ) :
- base( String.Format( "{0} - {1}",
- overflowMessage, auxMessage ), inner )
+ string auxMessage, Exception inner) :
+ base($"{overflowMessage} - {auxMessage}", inner)
{ }
}
class LogTable
{
- public LogTable( int numElements )
+ public LogTable(int numElements)
{
- logArea = new string[ numElements ];
+ logArea = new string[numElements];
elemInUse = 0;
}
- protected string[ ] logArea;
- protected int elemInUse;
+ protected string[] logArea;
+ protected int elemInUse;
// The AddRecord method throws a derived exception
// if the array bounds exception is caught.
- public int AddRecord( string newRecord )
+ public int AddRecord(string newRecord)
{
try
{
- logArea[ elemInUse ] = newRecord;
+ logArea[elemInUse] = newRecord;
return elemInUse++;
}
- catch( Exception ex )
+ catch (Exception ex)
{
throw new LogTableOverflowException(
- String.Format( "Record \"{0}\" was not logged.",
- newRecord ), ex );
+ $"Record \"{newRecord}\" was not logged.", ex);
}
}
}
@@ -60,26 +57,25 @@ class OverflowDemo
// Create a log table and force an overflow.
public static void Main()
{
- LogTable log = new LogTable( 4 );
+ LogTable log = new(4);
Console.WriteLine(
"This example of the Exception( string, Exception )" +
- "\nconstructor generates the following output." );
+ "\nconstructor generates the following output.");
Console.WriteLine(
"\nExample of a derived exception " +
- "that references an inner exception:\n" );
+ "that references an inner exception:\n");
try
{
- for( int count = 1; ; count++ )
+ for (int count = 1; ; count++)
{
log.AddRecord(
- String.Format(
- "Log record number {0}", count ) );
+ $"Log record number {count}");
}
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
}
diff --git a/snippets/csharp/System/Exception/Data/data.cs b/snippets/csharp/System/Exception/Data/data.cs
index 516d72527e1..a8bc61da813 100644
--- a/snippets/csharp/System/Exception/Data/data.cs
+++ b/snippets/csharp/System/Exception/Data/data.cs
@@ -5,56 +5,61 @@
class Sample
{
- public static void Main()
- {
- Console.WriteLine("\nException with some extra information...");
- RunTest(false);
- Console.WriteLine("\nException with all extra information...");
- RunTest(true);
- }
+ public static void Main()
+ {
+ Console.WriteLine("\nException with some extra information...");
+ RunTest(false);
+ Console.WriteLine("\nException with all extra information...");
+ RunTest(true);
+ }
- public static void RunTest(bool displayDetails)
- {
- try {
- NestedRoutine1(displayDetails);
- }
- catch (Exception e) {
- Console.WriteLine("An exception was thrown.");
- Console.WriteLine(e.Message);
- if (e.Data.Count > 0) {
- Console.WriteLine(" Extra details:");
- foreach (DictionaryEntry de in e.Data)
- Console.WriteLine(" Key: {0,-20} Value: {1}",
- "'" + de.Key.ToString() + "'", de.Value);
- }
- }
- }
+ public static void RunTest(bool displayDetails)
+ {
+ try
+ {
+ NestedRoutine1(displayDetails);
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("An exception was thrown.");
+ Console.WriteLine(e.Message);
+ if (e.Data.Count > 0)
+ {
+ Console.WriteLine(" Extra details:");
+ foreach (DictionaryEntry de in e.Data)
+ Console.WriteLine($" Key: {"'" + de.Key.ToString() + "'",-20} Value: {de.Value}");
+ }
+ }
+ }
- public static void NestedRoutine1(bool displayDetails)
- {
- try {
- NestedRoutine2(displayDetails);
- }
- catch (Exception e) {
- e.Data["ExtraInfo"] = "Information from NestedRoutine1.";
- e.Data.Add("MoreExtraInfo", "More information from NestedRoutine1.");
- throw;
- }
- }
+ public static void NestedRoutine1(bool displayDetails)
+ {
+ try
+ {
+ NestedRoutine2(displayDetails);
+ }
+ catch (Exception e)
+ {
+ e.Data["ExtraInfo"] = "Information from NestedRoutine1.";
+ e.Data.Add("MoreExtraInfo", "More information from NestedRoutine1.");
+ throw;
+ }
+ }
- public static void NestedRoutine2(bool displayDetails)
- {
- Exception e = new Exception("This statement is the original exception message.");
- if (displayDetails) {
- string s = "Information from NestedRoutine2.";
- int i = -903;
- DateTime dt = DateTime.Now;
- e.Data.Add("stringInfo", s);
- e.Data["IntInfo"] = i;
- e.Data["DateTimeInfo"] = dt;
- }
- throw e;
- }
+ public static void NestedRoutine2(bool displayDetails)
+ {
+ Exception e = new("This statement is the original exception message.");
+ if (displayDetails)
+ {
+ string s = "Information from NestedRoutine2.";
+ int i = -903;
+ DateTime dt = DateTime.Now;
+ e.Data.Add("stringInfo", s);
+ e.Data["IntInfo"] = i;
+ e.Data["DateTimeInfo"] = dt;
+ }
+ throw e;
+ }
}
// The example displays the following output:
// Exception with some extra information...
diff --git a/snippets/csharp/System/Exception/GetBaseException/getbaseexc.cs b/snippets/csharp/System/Exception/GetBaseException/getbaseexc.cs
index a7801b731e1..9bc6835fd8a 100644
--- a/snippets/csharp/System/Exception/GetBaseException/getbaseexc.cs
+++ b/snippets/csharp/System/Exception/GetBaseException/getbaseexc.cs
@@ -7,14 +7,14 @@ namespace NDP_UE_CS
// Define two derived exceptions to demonstrate nested exceptions.
class SecondLevelException : Exception
{
- public SecondLevelException( string message, Exception inner )
- : base( message, inner )
+ public SecondLevelException(string message, Exception inner)
+ : base(message, inner)
{ }
}
class ThirdLevelException : Exception
{
- public ThirdLevelException( string message, Exception inner )
- : base( message, inner )
+ public ThirdLevelException(string message, Exception inner)
+ : base(message, inner)
{ }
}
@@ -24,42 +24,42 @@ public static void Main()
{
Console.WriteLine(
"This example of Exception.GetBaseException " +
- "generates the following output." );
+ "generates the following output.");
Console.WriteLine(
"\nThe program forces a division by 0, then " +
"throws the exception \ntwice more, " +
- "using a different derived exception each time.\n" );
+ "using a different derived exception each time.\n");
try
{
// This function calls another that forces a
// division by 0.
- Rethrow( );
+ Rethrow();
}
- catch( Exception ex )
+ catch (Exception ex)
{
Exception current;
Console.WriteLine(
"Unwind the nested exceptions " +
- "using the InnerException property:\n" );
+ "using the InnerException property:\n");
// This code unwinds the nested exceptions using the
// InnerException property.
current = ex;
- while( current != null )
+ while (current != null)
{
- Console.WriteLine( current.ToString( ) );
- Console.WriteLine( );
+ Console.WriteLine(current.ToString());
+ Console.WriteLine();
current = current.InnerException;
}
// Display the innermost exception.
Console.WriteLine(
"Display the base exception " +
- "using the GetBaseException method:\n" );
+ "using the GetBaseException method:\n");
Console.WriteLine(
- ex.GetBaseException( ).ToString( ) );
+ ex.GetBaseException().ToString());
}
}
@@ -69,30 +69,30 @@ static void Rethrow()
{
try
{
- DivideBy0( );
+ DivideBy0();
}
- catch( Exception ex )
+ catch (Exception ex)
{
throw new ThirdLevelException(
"Caught the second exception and " +
- "threw a third in response.", ex );
+ "threw a third in response.", ex);
}
}
// This function forces a division by 0 and throws a second
// exception.
- static void DivideBy0( )
+ static void DivideBy0()
{
try
{
- int zero = 0;
- int ecks = 1 / zero;
+ int zero = 0;
+ int ecks = 1 / zero;
}
- catch( Exception ex )
+ catch (Exception ex)
{
throw new SecondLevelException(
"Forced a division by 0 and threw " +
- "a second exception.", ex );
+ "a second exception.", ex);
}
}
}
diff --git a/snippets/csharp/System/Exception/HResult/hresult.cs b/snippets/csharp/System/Exception/HResult/hresult.cs
index 60547b9cc87..675d0e0f1ac 100644
--- a/snippets/csharp/System/Exception/HResult/hresult.cs
+++ b/snippets/csharp/System/Exception/HResult/hresult.cs
@@ -7,16 +7,13 @@ namespace NDP_UE_CS
// Create the derived exception class.
class SecondLevelException : Exception
{
- const int SecondLevelHResult = unchecked( (int)0x81234567 );
+ const int SecondLevelHResult = unchecked((int)0x81234567);
// Set HResult for this exception, and include it in
// the exception message.
- public SecondLevelException( string message, Exception inner ) :
- base( string.Format( "(HRESULT:0x{1:X8}) {0}",
- message, SecondLevelHResult ), inner )
- {
- HResult = SecondLevelHResult;
- }
+ public SecondLevelException(string message, Exception inner) :
+ base(string.Format("(HRESULT:0x{1:X8}) {0}",
+ message, SecondLevelHResult), inner) => HResult = SecondLevelHResult;
}
class HResultDemo
@@ -29,19 +26,19 @@ public static void Main()
{
try
{
- int zero = 0;
- int ecks = 1 / zero;
+ int zero = 0;
+ int ecks = 1 / zero;
}
- catch( Exception ex )
+ catch (Exception ex)
{
throw new SecondLevelException(
"Forced a division by 0 and threw " +
- "a second exception.", ex );
+ "a second exception.", ex);
}
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( ex.ToString( ) );
+ Console.WriteLine(ex.ToString());
}
}
}
diff --git a/snippets/csharp/System/Exception/HelpLink/properties.cs b/snippets/csharp/System/Exception/HelpLink/properties.cs
index e3030d8716f..e6ef80ec310 100644
--- a/snippets/csharp/System/Exception/HelpLink/properties.cs
+++ b/snippets/csharp/System/Exception/HelpLink/properties.cs
@@ -12,9 +12,8 @@ class LogTableOverflowException : Exception
const string overflowMessage = "The log table has overflowed.";
public LogTableOverflowException(
- string auxMessage, Exception inner ) :
- base( String.Format( "{0} - {1}",
- overflowMessage, auxMessage ), inner )
+ string auxMessage, Exception inner) :
+ base($"{overflowMessage} - {auxMessage}", inner)
{
this.HelpLink = "https://learn.microsoft.com";
this.Source = "Exception_Class_Samples";
@@ -23,29 +22,28 @@ public LogTableOverflowException(
class LogTable
{
- public LogTable( int numElements )
+ public LogTable(int numElements)
{
- logArea = new string[ numElements ];
+ logArea = new string[numElements];
elemInUse = 0;
}
- protected string[ ] logArea;
- protected int elemInUse;
+ protected string[] logArea;
+ protected int elemInUse;
// The AddRecord method throws a derived exception if
// the array bounds exception is caught.
- public int AddRecord( string newRecord )
+ public int AddRecord(string newRecord)
{
try
{
- logArea[ elemInUse ] = newRecord;
+ logArea[elemInUse] = newRecord;
return elemInUse++;
}
- catch( Exception e )
+ catch (Exception e)
{
throw new LogTableOverflowException(
- String.Format( "Record \"{0}\" was not logged.",
- newRecord ), e );
+ $"Record \"{newRecord}\" was not logged.", e);
}
}
}
@@ -55,33 +53,29 @@ class OverflowDemo
// Create a log table and force an overflow.
public static void Main()
{
- LogTable log = new LogTable( 4 );
+ LogTable log = new(4);
Console.WriteLine(
"This example of \n Exception.Message, \n" +
" Exception.HelpLink, \n Exception.Source, \n" +
" Exception.StackTrace, and \n Exception." +
- "TargetSite \ngenerates the following output." );
+ "TargetSite \ngenerates the following output.");
try
{
- for( int count = 1; ; count++ )
+ for (int count = 1; ; count++)
{
log.AddRecord(
- String.Format(
- "Log record number {0}", count ) );
+ $"Log record number {count}");
}
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( "\nMessage ---\n{0}", ex.Message );
- Console.WriteLine(
- "\nHelpLink ---\n{0}", ex.HelpLink );
- Console.WriteLine( "\nSource ---\n{0}", ex.Source );
- Console.WriteLine(
- "\nStackTrace ---\n{0}", ex.StackTrace );
- Console.WriteLine(
- "\nTargetSite ---\n{0}", ex.TargetSite );
+ Console.WriteLine($"\nMessage ---\n{ex.Message}");
+ Console.WriteLine($"\nHelpLink ---\n{ex.HelpLink}");
+ Console.WriteLine($"\nSource ---\n{ex.Source}");
+ Console.WriteLine($"\nStackTrace ---\n{ex.StackTrace}");
+ Console.WriteLine($"\nTargetSite ---\n{ex.TargetSite}");
}
}
}
diff --git a/snippets/csharp/System/Exception/InnerException/innerex.cs b/snippets/csharp/System/Exception/InnerException/innerex.cs
index 0920f553110..810da124660 100644
--- a/snippets/csharp/System/Exception/InnerException/innerex.cs
+++ b/snippets/csharp/System/Exception/InnerException/innerex.cs
@@ -3,43 +3,44 @@
public class AppException : Exception
{
- public AppException(String message) : base (message)
- {}
+ public AppException(string message) : base(message)
+ { }
- public AppException(String message, Exception inner) : base(message,inner) {}
+ public AppException(string message, Exception inner) : base(message, inner) { }
}
public class Example
{
- public static void Main()
- {
- Example ex = new Example();
+ public static void Main()
+ {
+ Example ex = new();
- try {
- ex.CatchInner();
- }
- catch(AppException e) {
- Console.WriteLine ("In catch block of Main method.");
- Console.WriteLine("Caught: {0}", e.Message);
- if (e.InnerException != null)
- Console.WriteLine("Inner exception: {0}", e.InnerException);
- }
- }
+ try
+ {
+ ex.CatchInner();
+ }
+ catch (AppException e)
+ {
+ Console.WriteLine("In catch block of Main method.");
+ Console.WriteLine($"Caught: {e.Message}");
+ if (e.InnerException != null)
+ Console.WriteLine($"Inner exception: {e.InnerException}");
+ }
+ }
- public void ThrowInner ()
- {
- throw new AppException("Exception in ThrowInner method.");
- }
+ public void ThrowInner() => throw new AppException("Exception in ThrowInner method.");
- public void CatchInner()
- {
- try {
- this.ThrowInner();
- }
- catch (AppException e) {
- throw new AppException("Error in CatchInner caused by calling the ThrowInner method.", e);
- }
- }
+ public void CatchInner()
+ {
+ try
+ {
+ this.ThrowInner();
+ }
+ catch (AppException e)
+ {
+ throw new AppException("Error in CatchInner caused by calling the ThrowInner method.", e);
+ }
+ }
}
// The example displays the following output:
// In catch block of Main method.
diff --git a/snippets/csharp/System/Exception/Overview/catchexception.cs b/snippets/csharp/System/Exception/Overview/catchexception.cs
index cc7736bf616..2fac64b726c 100644
--- a/snippets/csharp/System/Exception/Overview/catchexception.cs
+++ b/snippets/csharp/System/Exception/Overview/catchexception.cs
@@ -3,22 +3,22 @@
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}");
- }
- }
+ 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:
diff --git a/snippets/csharp/System/Exception/Overview/example.cs b/snippets/csharp/System/Exception/Overview/example.cs
index bc529ebca06..c9075eee7cd 100644
--- a/snippets/csharp/System/Exception/Overview/example.cs
+++ b/snippets/csharp/System/Exception/Overview/example.cs
@@ -4,41 +4,41 @@
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("--------");
- }
+ public static void Main()
+ {
+ int limit = 10000000;
+ PrimeNumberGenerator primes = new(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($"{e.NonPrime} is not prime");
+ 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("--------");
- }
- }
+ 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($"{e.NonPrime} is not prime");
+ Console.WriteLine(e);
+ Console.WriteLine("--------");
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Exception/Overview/notprimeexception.cs b/snippets/csharp/System/Exception/Overview/notprimeexception.cs
index d3e0e6ade39..28e92d57d18 100644
--- a/snippets/csharp/System/Exception/Overview/notprimeexception.cs
+++ b/snippets/csharp/System/Exception/Overview/notprimeexception.cs
@@ -5,36 +5,26 @@
[Serializable()]
public class NotPrimeException : Exception
{
- private int notAPrime;
+ private int notAPrime;
- protected NotPrimeException()
- : base()
- { }
+ protected NotPrimeException()
+ : base()
+ { }
- public NotPrimeException(int value) :
- base(String.Format("{0} is not a prime number.", value))
- {
- notAPrime = value;
- }
+ public NotPrimeException(int value) :
+ base($"{value} is not a prime number.") => notAPrime = value;
- public NotPrimeException(int value, string message)
- : base(message)
- {
- 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;
- }
+ public NotPrimeException(int value, string message, Exception innerException) :
+ base(message, innerException) => notAPrime = value;
- protected NotPrimeException(SerializationInfo info,
- StreamingContext context)
- : base(info, context)
- { }
+ protected NotPrimeException(SerializationInfo info,
+ StreamingContext context)
+ : base(info, context)
+ { }
- public int NonPrime
- { get { return notAPrime; } }
+ public int NonPrime => notAPrime;
}
//
diff --git a/snippets/csharp/System/Exception/Overview/primenumbergenerator.cs b/snippets/csharp/System/Exception/Overview/primenumbergenerator.cs
index d91516fc2d3..58ee002782e 100644
--- a/snippets/csharp/System/Exception/Overview/primenumbergenerator.cs
+++ b/snippets/csharp/System/Exception/Overview/primenumbergenerator.cs
@@ -5,61 +5,56 @@
[Serializable]
public class PrimeNumberGenerator
{
- private const int START = 2;
- private int maxUpperBound = 10000000;
- private int upperBound;
- private bool[] primeTable;
- private List primes = new List();
+ private const int START = 2;
+ private int maxUpperBound = 10000000;
+ private int upperBound;
+ private bool[] primeTable;
+ private List primes = new();
- 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;
+ public PrimeNumberGenerator(int upperBound)
+ {
+ if (upperBound > maxUpperBound)
+ {
+ string message = $"{upperBound} exceeds the maximum upper bound of {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;
+ // 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++;
- }
- }
- }
+ 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[] GetAllPrimes() => 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();
- }
+ public int[] GetPrimesFrom(int prime)
+ {
+ int start = primes.FindIndex((value) => value == prime);
+ if (start < 0)
+ throw new NotPrimeException(prime, $"{prime} is not a prime number.");
+ else
+ return primes.FindAll((value) => value >= prime).ToArray();
+ }
}
//
diff --git a/snippets/csharp/System/Exception/Overview/rethrow1.cs b/snippets/csharp/System/Exception/Overview/rethrow1.cs
index f479e5981e5..7959a52d16b 100644
--- a/snippets/csharp/System/Exception/Overview/rethrow1.cs
+++ b/snippets/csharp/System/Exception/Overview/rethrow1.cs
@@ -5,62 +5,65 @@
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++;
+ 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.
+ }
+ catch (ArgumentNullException e)
+ {
+ // Perform some action here, such as logging this exception.
- throw;
- }
- return indexes.ToArray();
- }
+ 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();
+ 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);
- }
- }
+ string toFind = null;
+ try
+ {
+ indexes = s.FindOccurrences(toFind);
+ ShowOccurrences(s, toFind, indexes);
+ }
+ catch (ArgumentNullException e)
+ {
+ Console.WriteLine($"An exception ({e.GetType().Name}) occurred.");
+ Console.WriteLine($"Message:\n {e.Message}\n");
+ Console.WriteLine($"Stack Trace:\n {e.StackTrace}\n");
+ }
+ }
- 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 ? "" : ", ");
+ private static void ShowOccurrences(string s, string toFind, int[] indexes)
+ {
+ Console.Write($"'{toFind}' occurs at the following character positions: ");
+ for (int ctr = 0; ctr < indexes.Length; ctr++)
+ Console.Write($"{indexes[ctr]}{(ctr == indexes.Length - 1 ? "" : ", ")}");
- Console.WriteLine();
- }
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// 'a' occurs at the following character positions: 4, 7, 15
diff --git a/snippets/csharp/System/Exception/Overview/rethrow3.cs b/snippets/csharp/System/Exception/Overview/rethrow3.cs
index 06cbeb49ee7..6d14d503ebe 100644
--- a/snippets/csharp/System/Exception/Overview/rethrow3.cs
+++ b/snippets/csharp/System/Exception/Overview/rethrow3.cs
@@ -4,88 +4,92 @@
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++;
+ 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();
- }
+ }
+ 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();
+ 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)
- //
- }
+ string toFind = null;
+ //
+ try
+ {
+ indexes = s.FindOccurrences(toFind);
+ ShowOccurrences(s, toFind, indexes);
+ }
+ catch (ArgumentNullException e)
+ {
+ Console.WriteLine($"An exception ({e.GetType().Name}) occurred.");
+ Console.WriteLine($" Message:\n{e.Message}");
+ Console.WriteLine($" Stack Trace:\n {e.StackTrace}");
+ Exception ie = e.InnerException;
+ if (ie != null)
+ {
+ Console.WriteLine(" The Inner Exception:");
+ Console.WriteLine($" Exception Name: {ie.GetType().Name}");
+ Console.WriteLine($" Message: {ie.Message}\n");
+ Console.WriteLine($" 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)
+ //
+ }
- 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 ? "" : ", ");
+ private static void ShowOccurrences(string s, string toFind, int[] indexes)
+ {
+ Console.Write($"'{toFind}' occurs at the following character positions: ");
+ for (int ctr = 0; ctr < indexes.Length; ctr++)
+ Console.Write($"{indexes[ctr]}{(ctr == indexes.Length - 1 ? "" : ", ")}");
- Console.WriteLine();
- }
+ Console.WriteLine();
+ }
}
diff --git a/snippets/csharp/System/Exception/Overview/usageerrors1.cs b/snippets/csharp/System/Exception/Overview/usageerrors1.cs
index f5d28a86675..216c47dc222 100644
--- a/snippets/csharp/System/Exception/Overview/usageerrors1.cs
+++ b/snippets/csharp/System/Exception/Overview/usageerrors1.cs
@@ -3,38 +3,37 @@
public class Person
{
- private string _name;
+ private string _name;
- public string Name
+ public string Name
{
- get { return _name; }
- set { _name = value; }
+ get => _name;
+ set => _name = value;
}
- public override int GetHashCode()
- {
- return this.Name.GetHashCode();
- }
+ public override int GetHashCode() => 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 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;
+ public static void Main()
+ {
+ Person p1 = new()
+ {
+ Name = "John"
+ };
+ Person p2 = null;
- // The following throws a NullReferenceException.
- Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));
- }
+ // The following throws a NullReferenceException.
+ Console.WriteLine($"p1 = p2: {p1.Equals(p2)}");
+ }
}
//
diff --git a/snippets/csharp/System/Exception/Overview/usageerrors2.cs b/snippets/csharp/System/Exception/Overview/usageerrors2.cs
index 56b1801fc70..371499afd5c 100644
--- a/snippets/csharp/System/Exception/Overview/usageerrors2.cs
+++ b/snippets/csharp/System/Exception/Overview/usageerrors2.cs
@@ -3,40 +3,39 @@
public class Person
{
- private string _name;
+ private string _name;
- public string Name
+ public string Name
{
- get { return _name; }
- set { _name = value; }
+ get => _name;
+ set => _name = value;
}
- public override int GetHashCode()
- {
- return this.Name.GetHashCode();
- }
+ public override int GetHashCode() => 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 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;
+ public static void Main()
+ {
+ Person p1 = new()
+ {
+ Name = "John"
+ };
+ Person p2 = null;
- Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));
- }
+ Console.WriteLine($"p1 = p2: {p1.Equals(p2)}");
+ }
}
// The example displays the following output:
// p1 = p2: False
diff --git a/snippets/csharp/System/Exception/ToString/ToStringEx1.cs b/snippets/csharp/System/Exception/ToString/ToStringEx1.cs
index d2ce79160cf..e86f027005e 100644
--- a/snippets/csharp/System/Exception/ToString/ToStringEx1.cs
+++ b/snippets/csharp/System/Exception/ToString/ToStringEx1.cs
@@ -2,32 +2,32 @@
using System;
public class TestClass
-{}
+{ }
public class Example
{
- public static void Main()
- {
- var test = new TestClass();
- Object[] objectsToCompare = { test, test.ToString(), 123,
+ public static void Main()
+ {
+ var test = new TestClass();
+ object[] objectsToCompare = { test, test.ToString(), 123,
123.ToString(), "some text",
"Some Text" };
- string s = "some text";
- foreach (var objectToCompare in objectsToCompare) {
- try {
- int i = s.CompareTo(objectToCompare);
- Console.WriteLine("Comparing '{0}' with '{1}': {2}",
- s, objectToCompare, i);
- }
- catch (ArgumentException e) {
- Console.WriteLine("Bad argument: {0} (type {1})",
- objectToCompare,
- objectToCompare.GetType().Name);
- Console.WriteLine("Exception information: {0}", e);
- }
- Console.WriteLine();
- }
- }
+ string s = "some text";
+ foreach (object objectToCompare in objectsToCompare)
+ {
+ try
+ {
+ int i = s.CompareTo(objectToCompare);
+ Console.WriteLine($"Comparing '{s}' with '{objectToCompare}': {i}");
+ }
+ catch (ArgumentException e)
+ {
+ Console.WriteLine($"Bad argument: {objectToCompare} (type {objectToCompare.GetType().Name})");
+ Console.WriteLine($"Exception information: {e}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Bad argument: TestClass (type TestClass)
@@ -47,4 +47,4 @@ public static void Main()
// Comparing 'some text' with 'some text': 0
//
// Comparing 'some text' with 'Some Text': -1
-//
\ No newline at end of file
+//
From 95b9dfda0bd68c3fdd47b89662bfe4c3cfe7171d Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Mon, 10 Aug 2026 16:25:13 -0700
Subject: [PATCH 3/5] Apply suggestions from code review
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
---
snippets/csharp/System/Char/IsSeparator/isseparator1.cs | 2 +-
snippets/csharp/System/Enum/IsDefined/isdefined1.cs | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
index 353def1fcf6..ab56bef4f2c 100644
--- a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
+++ b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
@@ -9,7 +9,7 @@ public static void Main()
{
char ch = (char)ctr;
if (char.IsSeparator(ch))
- Console.WriteLine(@"\u{(int)ch:X4} ({Char.GetUnicodeCategory(ch)})");
+ Console.WriteLine($@"\u{(int)ch:X4} ({char.GetUnicodeCategory(ch)})");
}
}
}
diff --git a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
index 2abe64176d8..119555e3977 100644
--- a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
+++ b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
@@ -36,7 +36,7 @@ public static void Main()
value = PetType.Dog | PetType.Bird;
Console.WriteLine($"{value:D}: {Enum.IsDefined(typeof(PetType), value)}");
value = value.ToString();
- Console.WriteLine($"{value:D}: {Enum.IsDefined(typeof(PetType), value)}");
+ Console.WriteLine($"{value}: {Enum.IsDefined(typeof(PetType), value)}");
}
}
// The example displays the following output:
From 2e162572c644271b8172f13f2301f91f358a86a2 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Tue, 11 Aug 2026 10:26:45 -0700
Subject: [PATCH 4/5] Revert "Modernize C# code snippets"
This reverts commit 7d910447bf00e8ebaec6a28c33c82a2d241138f1.
---
.../csharp/System/Char/CompareTo/compareto.cs | 18 +-
.../System/Char/ConvertFromUtf32/utf.cs | 114 +++----
snippets/csharp/System/Char/Equals/equals.cs | 16 +-
.../Char/GetNumericValue/getnumericvalue.cs | 14 +-
.../Char/GetNumericValue/getnumericvalue1.cs | 158 +++++-----
.../GetUnicodeCategory/getunicodecategory.cs | 18 +-
.../System/Char/IsControl/IsControl1.cs | 30 +-
.../System/Char/IsControl/IsControl2.cs | 19 +-
.../csharp/System/Char/IsControl/iscontrol.cs | 14 +-
.../csharp/System/Char/IsDigit/isdigit.cs | 14 +-
.../csharp/System/Char/IsHighSurrogate/sur.cs | 66 ++--
.../csharp/System/Char/IsLetter/isletter.cs | 14 +-
.../Char/IsLetterOrDigit/isletterordigit.cs | 14 +-
.../csharp/System/Char/IsLower/islower.cs | 14 +-
.../csharp/System/Char/IsNumber/isnumber.cs | 14 +-
.../csharp/System/Char/IsNumber/isnumber1.cs | 63 ++--
.../Char/IsPunctuation/ispunctuation.cs | 14 +-
.../System/Char/IsSeparator/isseparator.cs | 14 +-
.../System/Char/IsSeparator/isseparator1.cs | 18 +-
.../System/Char/IsSurrogate/issurrogate.cs | 14 +-
.../csharp/System/Char/IsSymbol/issymbol.cs | 14 +-
.../System/Char/IsWhiteSpace/iswhitespace.cs | 14 +-
.../Char/Overview/GetUnicodeCategory3.cs | 20 +-
.../System/Char/Overview/charstructure.cs | 24 +-
.../csharp/System/Char/Overview/grapheme1.cs | 6 +-
.../csharp/System/Char/Overview/surrogate1.cs | 6 +-
.../System/Char/Overview/textelements2.cs | 6 +-
.../System/Char/Overview/textelements2a.cs | 8 +-
snippets/csharp/System/Char/Parse/parse.cs | 10 +-
.../csharp/System/Char/ToLower/tolower.cs | 12 +-
.../csharp/System/Char/ToString/tostring.cs | 14 +-
.../csharp/System/Char/ToUpper/toupper1.cs | 13 +-
.../csharp/System/Char/ToUpper/toupper5.cs | 27 +-
snippets/csharp/System/Char/TryParse/tp.cs | 242 +++++++--------
.../Overview/CharEnumerator1.cs | 120 +++----
.../Console/BackgroundColor/Example2.cs | 19 +-
.../BackgroundColor/backgroundcolor1.cs | 41 ++-
.../BackgroundColor/foregroundcolor3.cs | 60 ++--
snippets/csharp/System/Console/Beep/b2.cs | 90 +++---
snippets/csharp/System/Console/Beep/beep.cs | 22 +-
.../csharp/System/Console/BufferHeight/hw.cs | 8 +-
.../System/Console/CancelKeyPress/ckp.cs | 2 +-
.../csharp/System/Console/Clear/clear1.cs | 150 +++++----
snippets/csharp/System/Console/Clear/lts.cs | 68 ++--
.../csharp/System/Console/CursorSize/csize.cs | 26 +-
.../System/Console/CursorVisible/vis.cs | 54 ++--
.../csharp/System/Console/Error/error1.cs | 53 ++--
.../System/Console/Error/expandtabsex.cs | 22 +-
.../System/Console/Error/viewtextfile.cs | 74 +++--
.../csharp/System/Console/In/consolein.cs | 12 +-
.../csharp/System/Console/KeyAvailable/ka.cs | 23 +-
.../Console/OpenStandardInput/decode.cs | 6 +-
.../Console/OpenStandardOutput/inserttabs.cs | 7 +-
snippets/csharp/System/Console/Out/out1.cs | 52 ++--
.../System/Console/Overview/example3.cs | 293 +++++++++---------
.../System/Console/Overview/fontlink1.cs | 126 ++++----
.../System/Console/Overview/normalize1.cs | 18 +-
.../System/Console/Overview/setfont1.cs | 129 ++++----
.../csharp/System/Console/Overview/source.cs | 5 +-
.../System/Console/Overview/unicode1.cs | 41 ++-
snippets/csharp/System/Console/Read/read.cs | 48 +--
.../csharp/System/Console/ReadKey/ReadKey1.cs | 21 +-
.../csharp/System/Console/ReadKey/ReadKey2.cs | 21 +-
snippets/csharp/System/Console/ReadKey/rk.cs | 32 +-
.../csharp/System/Console/ReadKey/rkbool.cs | 33 +-
.../System/Console/ReadLine/ReadLine2.cs | 25 +-
.../System/Console/ReadLine/ReadLine3.cs | 38 ++-
.../System/Console/ReadLine/ReadLineSimple.cs | 16 +-
.../System/Console/SetBufferSize/wlt.cs | 170 +++++-----
.../System/Console/SetError/SetError1.cs | 44 +--
.../csharp/System/Console/SetOut/source.cs | 21 +-
.../System/Console/SetWindowSize/sws.cs | 66 ++--
.../csharp/System/Console/Title/mytitle.cs | 17 +-
.../System/Console/WindowLeft/windowleft1.cs | 80 ++---
.../System/Console/Write/WriteParams1.cs | 52 ++--
.../System/Console/Write/WriteParams2.cs | 52 ++--
.../csharp/System/Console/Write/reformat.cs | 14 +-
snippets/csharp/System/Console/Write/wl.cs | 4 +-
.../System/Console/WriteLine/WriteLine6.cs | 35 +--
.../System/Console/WriteLine/WriteLine7.cs | 7 +-
.../System/Console/WriteLine/newline1.cs | 64 ++--
.../System/Console/WriteLine/tipcalc.cs | 4 +-
.../Console/WriteLine/writeline_boolean1.cs | 35 +--
.../Console/WriteLine/writeline_obj1.cs | 30 +-
.../System/ConsoleKey/Overview/ConsoleKey1.cs | 82 +++--
.../System/ConsoleKeyInfo/Equals/equals.cs | 110 ++++---
.../System/ConsoleKeyInfo/GetHashCode/hash.cs | 92 +++---
.../System/ConsoleKeyInfo/KeyChar/keychar1.cs | 90 +++---
88 files changed, 1914 insertions(+), 1986 deletions(-)
diff --git a/snippets/csharp/System/Char/CompareTo/compareto.cs b/snippets/csharp/System/Char/CompareTo/compareto.cs
index a76567483ca..cef09ab0111 100644
--- a/snippets/csharp/System/Char/CompareTo/compareto.cs
+++ b/snippets/csharp/System/Char/CompareTo/compareto.cs
@@ -1,16 +1,14 @@
//
using System;
-public class CompareToSample
-{
- public static void Main()
- {
- char chA = 'A';
- char chB = 'B';
+public class CompareToSample {
+ public static void Main() {
+ char chA = 'A';
+ char chB = 'B';
- Console.WriteLine(chA.CompareTo('A')); // Output: "0" (meaning they're equal)
- Console.WriteLine('b'.CompareTo(chB)); // Output: "32" (meaning 'b' is greater than 'B' by 32)
- Console.WriteLine(chA.CompareTo(chB)); // Output: "-1" (meaning 'A' is less than 'B' by 1)
- }
+ Console.WriteLine(chA.CompareTo('A')); // Output: "0" (meaning they're equal)
+ Console.WriteLine('b'.CompareTo(chB)); // Output: "32" (meaning 'b' is greater than 'B' by 32)
+ Console.WriteLine(chA.CompareTo(chB)); // Output: "-1" (meaning 'A' is less than 'B' by 1)
+ }
}
//
diff --git a/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs b/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
index c853a5a51f7..1006f5c344f 100644
--- a/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
+++ b/snippets/csharp/System/Char/ConvertFromUtf32/utf.cs
@@ -7,66 +7,68 @@ class Sample
{
public static void Main()
{
- int letterA = 0x0041; //U+00041 = LATIN CAPITAL LETTER A
- int music = 0x1D161; //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
- string s1;
- string comment = "Create a UTF-16 encoded string from a code point.";
- string comment1b = "Create a code point from a UTF-16 encoded string.";
- string comment2b = "Create a code point from a surrogate pair at a certain position in a string.";
- string comment2c = "Create a code point from a high surrogate and a low surrogate code point.";
-
- // Convert code point U+0041 to UTF-16. The UTF-16 equivalent of
- // U+0041 is a Char with hexadecimal value 0041.
-
- Console.WriteLine(comment);
- s1 = char.ConvertFromUtf32(letterA);
- Console.Write($" 1a) 0x{letterA:X} => ");
- Show(s1);
- Console.WriteLine();
-
- // Convert the lone UTF-16 character to a code point.
-
- Console.WriteLine(comment1b);
- letterA = char.ConvertToUtf32(s1, 0);
- Console.Write(" 1b) ");
- Show(s1);
- Console.WriteLine($" => 0x{letterA:X}");
- Console.WriteLine();
-
- // -------------------------------------------------------------------
-
- // Convert the code point U+1D161 to UTF-16. The UTF-16 equivalent of
- // U+1D161 is a surrogate pair with hexadecimal values D834 and DD61.
-
- Console.WriteLine(comment);
- s1 = char.ConvertFromUtf32(music);
- Console.Write($" 2a) 0x{music:X} => ");
- Show(s1);
- Console.WriteLine();
-
- // Convert the surrogate pair in the string at index position
- // zero to a code point.
-
- Console.WriteLine(comment2b);
- music = char.ConvertToUtf32(s1, 0);
- Console.Write(" 2b) ");
- Show(s1);
- Console.WriteLine($" => 0x{music:X}");
-
- // Convert the high and low characters in the surrogate pair into a code point.
-
- Console.WriteLine(comment2c);
- music = char.ConvertToUtf32(s1[0], s1[1]);
- Console.Write(" 2c) ");
- Show(s1);
- Console.WriteLine($" => 0x{music:X}");
+ int letterA = 0x0041; //U+00041 = LATIN CAPITAL LETTER A
+ int music = 0x1D161; //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
+ string s1;
+ string comment = "Create a UTF-16 encoded string from a code point.";
+ string comment1b = "Create a code point from a UTF-16 encoded string.";
+ string comment2b = "Create a code point from a surrogate pair at a certain position in a string.";
+ string comment2c = "Create a code point from a high surrogate and a low surrogate code point.";
+
+// Convert code point U+0041 to UTF-16. The UTF-16 equivalent of
+// U+0041 is a Char with hexadecimal value 0041.
+
+ Console.WriteLine(comment);
+ s1 = Char.ConvertFromUtf32(letterA);
+ Console.Write(" 1a) 0x{0:X} => ", letterA);
+ Show(s1);
+ Console.WriteLine();
+
+// Convert the lone UTF-16 character to a code point.
+
+ Console.WriteLine(comment1b);
+ letterA = Char.ConvertToUtf32(s1, 0);
+ Console.Write(" 1b) ");
+ Show(s1);
+ Console.WriteLine(" => 0x{0:X}", letterA);
+ Console.WriteLine();
+
+// -------------------------------------------------------------------
+
+// Convert the code point U+1D161 to UTF-16. The UTF-16 equivalent of
+// U+1D161 is a surrogate pair with hexadecimal values D834 and DD61.
+
+ Console.WriteLine(comment);
+ s1 = Char.ConvertFromUtf32(music);
+ Console.Write(" 2a) 0x{0:X} => ", music);
+ Show(s1);
+ Console.WriteLine();
+
+// Convert the surrogate pair in the string at index position
+// zero to a code point.
+
+ Console.WriteLine(comment2b);
+ music = Char.ConvertToUtf32(s1, 0);
+ Console.Write(" 2b) ");
+ Show(s1);
+ Console.WriteLine(" => 0x{0:X}", music);
+
+// Convert the high and low characters in the surrogate pair into a code point.
+
+ Console.WriteLine(comment2c);
+ music = Char.ConvertToUtf32(s1[0], s1[1]);
+ Console.Write(" 2c) ");
+ Show(s1);
+ Console.WriteLine(" => 0x{0:X}", music);
}
private static void Show(string s)
{
- for (int x = 0; x < s.Length; x++)
+ for (int x = 0; x < s.Length; x++)
{
- Console.Write($"0x{(int)s[x]:X}{((x == s.Length - 1) ? string.Empty : ", ")}");
+ Console.Write("0x{0:X}{1}",
+ (int)s[x],
+ ((x == s.Length-1)? String.Empty : ", "));
}
}
}
@@ -86,4 +88,4 @@ Create a code point from a high surrogate and a low surrogate code point.
2c) 0xD834, 0xDD61 => 0x1D161
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Char/Equals/equals.cs b/snippets/csharp/System/Char/Equals/equals.cs
index d2c263528d6..0470e9a3774 100644
--- a/snippets/csharp/System/Char/Equals/equals.cs
+++ b/snippets/csharp/System/Char/Equals/equals.cs
@@ -1,15 +1,13 @@
//
using System;
-public class EqualsSample
-{
- public static void Main()
- {
- char chA = 'A';
- char chB = 'B';
+public class EqualsSample {
+ public static void Main() {
+ char chA = 'A';
+ char chB = 'B';
- Console.WriteLine(chA.Equals('A')); // Output: "True"
- Console.WriteLine('b'.Equals(chB)); // Output: "False"
- }
+ Console.WriteLine(chA.Equals('A')); // Output: "True"
+ Console.WriteLine('b'.Equals(chB)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
index d6f2c51339d..8c8e10eb45b 100644
--- a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
+++ b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue.cs
@@ -1,14 +1,12 @@
//
using System;
-public class GetNumericValueSample
-{
- public static void Main()
- {
- string str = "input: 1";
+public class GetNumericValueSample {
+ public static void Main() {
+ string str = "input: 1";
- Console.WriteLine(char.GetNumericValue('8')); // Output: "8"
- Console.WriteLine(char.GetNumericValue(str, 7)); // Output: "1"
- }
+ Console.WriteLine(Char.GetNumericValue('8')); // Output: "8"
+ Console.WriteLine(Char.GetNumericValue(str, 7)); // Output: "1"
+ }
}
//
diff --git a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
index 6066ef271ce..7df01ad16c7 100644
--- a/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
+++ b/snippets/csharp/System/Char/GetNumericValue/getnumericvalue1.cs
@@ -2,86 +2,88 @@
public class Example
{
- public static void Main()
- {
- Overload1();
- Console.WriteLine();
- Overload2();
- }
+ public static void Main()
+ {
+ Overload1();
+ Console.WriteLine();
+ Overload2();
+ }
- private static void Overload1()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = char.ConvertFromUtf32(utf32);
- foreach (char ch in surrogate)
- Console.WriteLine($"U+{Convert.ToUInt16(ch):X4}: {char.GetNumericValue(ch)} ");
+ private static void Overload1()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = Char.ConvertFromUtf32(utf32);
+ foreach (var ch in surrogate)
+ Console.WriteLine("U+{0:X4}: {1} ", Convert.ToUInt16(ch),
+ Char.GetNumericValue(ch));
- // The example displays the following output:
- // U+D800: -1
- // U+DD07: -1
- //
- }
+ // The example displays the following output:
+ // U+D800: -1
+ // U+DD07: -1
+ //
+ }
- private static void Overload2()
- {
- //
- // Define a UTF32 value for each character in the
- // Aegean numbering system.
- for (int utf32 = 0x10107; utf32 <= 0x10133; utf32++)
- {
- string surrogate = char.ConvertFromUtf32(utf32);
- for (int ctr = 0; ctr < surrogate.Length; ctr++)
- Console.Write($"U+{Convert.ToUInt16(surrogate[ctr]):X4} at position {ctr}: {char.GetNumericValue(surrogate, ctr)} ");
+ private static void Overload2()
+ {
+ //
+ // Define a UTF32 value for each character in the
+ // Aegean numbering system.
+ for (int utf32 = 0x10107; utf32 <= 0x10133; utf32++) {
+ string surrogate = Char.ConvertFromUtf32(utf32);
+ for (int ctr = 0; ctr < surrogate.Length; ctr++)
+ Console.Write("U+{0:X4} at position {1}: {2} ",
+ Convert.ToUInt16(surrogate[ctr]), ctr,
+ Char.GetNumericValue(surrogate, ctr));
- Console.WriteLine();
- }
- // The example displays the following output:
- // U+D800 at position 0: 1 U+DD07 at position 1: -1
- // U+D800 at position 0: 2 U+DD08 at position 1: -1
- // U+D800 at position 0: 3 U+DD09 at position 1: -1
- // U+D800 at position 0: 4 U+DD0A at position 1: -1
- // U+D800 at position 0: 5 U+DD0B at position 1: -1
- // U+D800 at position 0: 6 U+DD0C at position 1: -1
- // U+D800 at position 0: 7 U+DD0D at position 1: -1
- // U+D800 at position 0: 8 U+DD0E at position 1: -1
- // U+D800 at position 0: 9 U+DD0F at position 1: -1
- // U+D800 at position 0: 10 U+DD10 at position 1: -1
- // U+D800 at position 0: 20 U+DD11 at position 1: -1
- // U+D800 at position 0: 30 U+DD12 at position 1: -1
- // U+D800 at position 0: 40 U+DD13 at position 1: -1
- // U+D800 at position 0: 50 U+DD14 at position 1: -1
- // U+D800 at position 0: 60 U+DD15 at position 1: -1
- // U+D800 at position 0: 70 U+DD16 at position 1: -1
- // U+D800 at position 0: 80 U+DD17 at position 1: -1
- // U+D800 at position 0: 90 U+DD18 at position 1: -1
- // U+D800 at position 0: 100 U+DD19 at position 1: -1
- // U+D800 at position 0: 200 U+DD1A at position 1: -1
- // U+D800 at position 0: 300 U+DD1B at position 1: -1
- // U+D800 at position 0: 400 U+DD1C at position 1: -1
- // U+D800 at position 0: 500 U+DD1D at position 1: -1
- // U+D800 at position 0: 600 U+DD1E at position 1: -1
- // U+D800 at position 0: 700 U+DD1F at position 1: -1
- // U+D800 at position 0: 800 U+DD20 at position 1: -1
- // U+D800 at position 0: 900 U+DD21 at position 1: -1
- // U+D800 at position 0: 1000 U+DD22 at position 1: -1
- // U+D800 at position 0: 2000 U+DD23 at position 1: -1
- // U+D800 at position 0: 3000 U+DD24 at position 1: -1
- // U+D800 at position 0: 4000 U+DD25 at position 1: -1
- // U+D800 at position 0: 5000 U+DD26 at position 1: -1
- // U+D800 at position 0: 6000 U+DD27 at position 1: -1
- // U+D800 at position 0: 7000 U+DD28 at position 1: -1
- // U+D800 at position 0: 8000 U+DD29 at position 1: -1
- // U+D800 at position 0: 9000 U+DD2A at position 1: -1
- // U+D800 at position 0: 10000 U+DD2B at position 1: -1
- // U+D800 at position 0: 20000 U+DD2C at position 1: -1
- // U+D800 at position 0: 30000 U+DD2D at position 1: -1
- // U+D800 at position 0: 40000 U+DD2E at position 1: -1
- // U+D800 at position 0: 50000 U+DD2F at position 1: -1
- // U+D800 at position 0: 60000 U+DD30 at position 1: -1
- // U+D800 at position 0: 70000 U+DD31 at position 1: -1
- // U+D800 at position 0: 80000 U+DD32 at position 1: -1
- // U+D800 at position 0: 90000 U+DD33 at position 1: -1
- //
- }
+ Console.WriteLine();
+ }
+ // The example displays the following output:
+ // U+D800 at position 0: 1 U+DD07 at position 1: -1
+ // U+D800 at position 0: 2 U+DD08 at position 1: -1
+ // U+D800 at position 0: 3 U+DD09 at position 1: -1
+ // U+D800 at position 0: 4 U+DD0A at position 1: -1
+ // U+D800 at position 0: 5 U+DD0B at position 1: -1
+ // U+D800 at position 0: 6 U+DD0C at position 1: -1
+ // U+D800 at position 0: 7 U+DD0D at position 1: -1
+ // U+D800 at position 0: 8 U+DD0E at position 1: -1
+ // U+D800 at position 0: 9 U+DD0F at position 1: -1
+ // U+D800 at position 0: 10 U+DD10 at position 1: -1
+ // U+D800 at position 0: 20 U+DD11 at position 1: -1
+ // U+D800 at position 0: 30 U+DD12 at position 1: -1
+ // U+D800 at position 0: 40 U+DD13 at position 1: -1
+ // U+D800 at position 0: 50 U+DD14 at position 1: -1
+ // U+D800 at position 0: 60 U+DD15 at position 1: -1
+ // U+D800 at position 0: 70 U+DD16 at position 1: -1
+ // U+D800 at position 0: 80 U+DD17 at position 1: -1
+ // U+D800 at position 0: 90 U+DD18 at position 1: -1
+ // U+D800 at position 0: 100 U+DD19 at position 1: -1
+ // U+D800 at position 0: 200 U+DD1A at position 1: -1
+ // U+D800 at position 0: 300 U+DD1B at position 1: -1
+ // U+D800 at position 0: 400 U+DD1C at position 1: -1
+ // U+D800 at position 0: 500 U+DD1D at position 1: -1
+ // U+D800 at position 0: 600 U+DD1E at position 1: -1
+ // U+D800 at position 0: 700 U+DD1F at position 1: -1
+ // U+D800 at position 0: 800 U+DD20 at position 1: -1
+ // U+D800 at position 0: 900 U+DD21 at position 1: -1
+ // U+D800 at position 0: 1000 U+DD22 at position 1: -1
+ // U+D800 at position 0: 2000 U+DD23 at position 1: -1
+ // U+D800 at position 0: 3000 U+DD24 at position 1: -1
+ // U+D800 at position 0: 4000 U+DD25 at position 1: -1
+ // U+D800 at position 0: 5000 U+DD26 at position 1: -1
+ // U+D800 at position 0: 6000 U+DD27 at position 1: -1
+ // U+D800 at position 0: 7000 U+DD28 at position 1: -1
+ // U+D800 at position 0: 8000 U+DD29 at position 1: -1
+ // U+D800 at position 0: 9000 U+DD2A at position 1: -1
+ // U+D800 at position 0: 10000 U+DD2B at position 1: -1
+ // U+D800 at position 0: 20000 U+DD2C at position 1: -1
+ // U+D800 at position 0: 30000 U+DD2D at position 1: -1
+ // U+D800 at position 0: 40000 U+DD2E at position 1: -1
+ // U+D800 at position 0: 50000 U+DD2F at position 1: -1
+ // U+D800 at position 0: 60000 U+DD30 at position 1: -1
+ // U+D800 at position 0: 70000 U+DD31 at position 1: -1
+ // U+D800 at position 0: 80000 U+DD32 at position 1: -1
+ // U+D800 at position 0: 90000 U+DD33 at position 1: -1
+ //
+ }
}
diff --git a/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs b/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
index 7171ac77733..c3d97612139 100644
--- a/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
+++ b/snippets/csharp/System/Char/GetUnicodeCategory/getunicodecategory.cs
@@ -1,16 +1,14 @@
//
using System;
-public class GetUnicodeCategorySample
-{
- public static void Main()
- {
- char ch2 = '2';
- string str = "Upper Case";
+public class GetUnicodeCategorySample {
+ public static void Main() {
+ char ch2 = '2';
+ string str = "Upper Case";
- Console.WriteLine(char.GetUnicodeCategory('a')); // Output: "LowercaseLetter"
- Console.WriteLine(char.GetUnicodeCategory(ch2)); // Output: "DecimalDigitNumber"
- Console.WriteLine(char.GetUnicodeCategory(str, 6)); // Output: "UppercaseLetter"
- }
+ Console.WriteLine(Char.GetUnicodeCategory('a')); // Output: "LowercaseLetter"
+ Console.WriteLine(Char.GetUnicodeCategory(ch2)); // Output: "DecimalDigitNumber"
+ Console.WriteLine(Char.GetUnicodeCategory(str, 6)); // Output: "UppercaseLetter"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsControl/IsControl1.cs b/snippets/csharp/System/Char/IsControl/IsControl1.cs
index 4ecdedf6fee..a83b4ad7d49 100644
--- a/snippets/csharp/System/Char/IsControl/IsControl1.cs
+++ b/snippets/csharp/System/Char/IsControl/IsControl1.cs
@@ -3,22 +3,22 @@
public class ControlChars
{
- public static void Main()
- {
- int charsWritten = 0;
+ public static void Main()
+ {
+ int charsWritten = 0;
- for (int ctr = 0x00; ctr <= 0xFFFF; ctr++)
- {
- char ch = Convert.ToChar(ctr);
- if (char.IsControl(ch))
- {
- Console.Write($"\\U{ctr:X4} ");
- charsWritten++;
- if (charsWritten % 6 == 0)
- Console.WriteLine();
- }
- }
- }
+ for (int ctr = 0x00; ctr <= 0xFFFF; ctr++)
+ {
+ char ch = Convert.ToChar(ctr);
+ if (char.IsControl(ch))
+ {
+ Console.Write(@"\U{0:X4} ", ctr);
+ charsWritten++;
+ if (charsWritten % 6 == 0)
+ Console.WriteLine();
+ }
+ }
+ }
}
// The example displays the following output to the console:
// \U0000 \U0001 \U0002 \U0003 \U0004 \U0005
diff --git a/snippets/csharp/System/Char/IsControl/IsControl2.cs b/snippets/csharp/System/Char/IsControl/IsControl2.cs
index ba6b5efdde1..f3a353e9fb3 100644
--- a/snippets/csharp/System/Char/IsControl/IsControl2.cs
+++ b/snippets/csharp/System/Char/IsControl/IsControl2.cs
@@ -3,15 +3,16 @@
public class ControlChar
{
- public static void Main()
- {
- string sentence = "This is a " + Environment.NewLine + "two-line sentence.";
- for (int ctr = 0; ctr < sentence.Length; ctr++)
- {
- if (char.IsControl(sentence, ctr))
- Console.WriteLine($"Control character \\U{Convert.ToInt32(sentence[ctr]).ToString("X4")} found in position {ctr}.");
- }
- }
+ public static void Main()
+ {
+ string sentence = "This is a " + Environment.NewLine + "two-line sentence.";
+ for (int ctr = 0; ctr < sentence.Length; ctr++)
+ {
+ if (Char.IsControl(sentence, ctr))
+ Console.WriteLine("Control character \\U{0} found in position {1}.",
+ Convert.ToInt32(sentence[ctr]).ToString("X4"), ctr);
+ }
+ }
}
// The example displays the following output to the console:
// Control character \U000D found in position 10.
diff --git a/snippets/csharp/System/Char/IsControl/iscontrol.cs b/snippets/csharp/System/Char/IsControl/iscontrol.cs
index 4d10789b134..f8519b6da5a 100644
--- a/snippets/csharp/System/Char/IsControl/iscontrol.cs
+++ b/snippets/csharp/System/Char/IsControl/iscontrol.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsControlSample
-{
- public static void Main()
- {
- string str = "sample string";
+public class IsControlSample {
+ public static void Main() {
+ string str = "sample string";
- Console.WriteLine(char.IsControl('\t')); // Output: "True"
- Console.WriteLine(char.IsControl(str, 7)); // Output: "False"
- }
+ Console.WriteLine(Char.IsControl('\t')); // Output: "True"
+ Console.WriteLine(Char.IsControl(str, 7)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsDigit/isdigit.cs b/snippets/csharp/System/Char/IsDigit/isdigit.cs
index 5af135a1c9a..76a8ba660f9 100644
--- a/snippets/csharp/System/Char/IsDigit/isdigit.cs
+++ b/snippets/csharp/System/Char/IsDigit/isdigit.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsDigitSample
-{
- public static void Main()
- {
- char ch = '8';
+public class IsDigitSample {
+ public static void Main() {
+ char ch = '8';
- Console.WriteLine(char.IsDigit(ch)); // Output: "True"
- Console.WriteLine(char.IsDigit("sample string", 7)); // Output: "False"
- }
+ Console.WriteLine(Char.IsDigit(ch)); // Output: "True"
+ Console.WriteLine(Char.IsDigit("sample string", 7)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsHighSurrogate/sur.cs b/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
index 81899436c28..a74645cc6e2 100644
--- a/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
+++ b/snippets/csharp/System/Char/IsHighSurrogate/sur.cs
@@ -8,44 +8,44 @@ class Sample
{
public static void Main()
{
- char cHigh = '\uD800';
- char cLow = '\uDC00';
- string s1 = new(new char[] { 'a', '\uD800', '\uDC00', 'z' });
- string divider = string.Concat(Environment.NewLine, new string('-', 70),
- Environment.NewLine);
+ char cHigh = '\uD800';
+ char cLow = '\uDC00';
+ string s1 = new String(new char[] {'a', '\uD800', '\uDC00', 'z'});
+ string divider = String.Concat( Environment.NewLine, new String('-', 70),
+ Environment.NewLine);
- Console.WriteLine();
- Console.WriteLine($"Hexadecimal code point of the character, cHigh: {(int)cHigh:X4}");
- Console.WriteLine($"Hexadecimal code point of the character, cLow: {(int)cLow:X4}");
- Console.WriteLine();
- Console.WriteLine("Characters in string, s1: 'a', high surrogate, low surrogate, 'z'");
- Console.WriteLine("Hexadecimal code points of the characters in string, s1: ");
- for (int i = 0; i < s1.Length; i++)
+ Console.WriteLine();
+ Console.WriteLine("Hexadecimal code point of the character, cHigh: {0:X4}", (int)cHigh);
+ Console.WriteLine("Hexadecimal code point of the character, cLow: {0:X4}", (int)cLow);
+ Console.WriteLine();
+ Console.WriteLine("Characters in string, s1: 'a', high surrogate, low surrogate, 'z'");
+ Console.WriteLine("Hexadecimal code points of the characters in string, s1: ");
+ for(int i = 0; i < s1.Length; i++)
{
- Console.WriteLine($"s1[{i}] = {(int)s1[i]:X4} ");
+ Console.WriteLine("s1[{0}] = {1:X4} ", i, (int)s1[i]);
}
- Console.WriteLine(divider);
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following characters a high surrogate?");
- Console.WriteLine($"A1) cLow? - {char.IsHighSurrogate(cLow)}");
- Console.WriteLine($"A2) cHigh? - {char.IsHighSurrogate(cHigh)}");
- Console.WriteLine($"A3) s1[0]? - {char.IsHighSurrogate(s1, 0)}");
- Console.WriteLine($"A4) s1[1]? - {char.IsHighSurrogate(s1, 1)}");
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following characters a high surrogate?");
+ Console.WriteLine("A1) cLow? - {0}", Char.IsHighSurrogate(cLow));
+ Console.WriteLine("A2) cHigh? - {0}", Char.IsHighSurrogate(cHigh));
+ Console.WriteLine("A3) s1[0]? - {0}", Char.IsHighSurrogate(s1, 0));
+ Console.WriteLine("A4) s1[1]? - {0}", Char.IsHighSurrogate(s1, 1));
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following characters a low surrogate?");
- Console.WriteLine($"B1) cLow? - {char.IsLowSurrogate(cLow)}");
- Console.WriteLine($"B2) cHigh? - {char.IsLowSurrogate(cHigh)}");
- Console.WriteLine($"B3) s1[0]? - {char.IsLowSurrogate(s1, 0)}");
- Console.WriteLine($"B4) s1[2]? - {char.IsLowSurrogate(s1, 2)}");
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following characters a low surrogate?");
+ Console.WriteLine("B1) cLow? - {0}", Char.IsLowSurrogate(cLow));
+ Console.WriteLine("B2) cHigh? - {0}", Char.IsLowSurrogate(cHigh));
+ Console.WriteLine("B3) s1[0]? - {0}", Char.IsLowSurrogate(s1, 0));
+ Console.WriteLine("B4) s1[2]? - {0}", Char.IsLowSurrogate(s1, 2));
+ Console.WriteLine(divider);
- Console.WriteLine("Is each of the following pairs of characters a surrogate pair?");
- Console.WriteLine($"C1) cHigh and cLow? - {char.IsSurrogatePair(cHigh, cLow)}");
- Console.WriteLine($"C2) s1[0] and s1[1]? - {char.IsSurrogatePair(s1, 0)}");
- Console.WriteLine($"C3) s1[1] and s1[2]? - {char.IsSurrogatePair(s1, 1)}");
- Console.WriteLine($"C4) s1[2] and s1[3]? - {char.IsSurrogatePair(s1, 2)}");
- Console.WriteLine(divider);
+ Console.WriteLine("Is each of the following pairs of characters a surrogate pair?");
+ Console.WriteLine("C1) cHigh and cLow? - {0}", Char.IsSurrogatePair(cHigh, cLow));
+ Console.WriteLine("C2) s1[0] and s1[1]? - {0}", Char.IsSurrogatePair(s1, 0));
+ Console.WriteLine("C3) s1[1] and s1[2]? - {0}", Char.IsSurrogatePair(s1, 1));
+ Console.WriteLine("C4) s1[2] and s1[3]? - {0}", Char.IsSurrogatePair(s1, 2));
+ Console.WriteLine(divider);
}
}
/*
@@ -88,4 +88,4 @@ Is each of the following pairs of characters a surrogate pair?
----------------------------------------------------------------------
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Char/IsLetter/isletter.cs b/snippets/csharp/System/Char/IsLetter/isletter.cs
index 3b22509d456..a4ba24d96cf 100644
--- a/snippets/csharp/System/Char/IsLetter/isletter.cs
+++ b/snippets/csharp/System/Char/IsLetter/isletter.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsLetterSample
-{
- public static void Main()
- {
- char ch = '8';
+public class IsLetterSample {
+ public static void Main() {
+ char ch = '8';
- Console.WriteLine(char.IsLetter(ch)); // False
- Console.WriteLine(char.IsLetter("sample string", 7)); // True
- }
+ Console.WriteLine(Char.IsLetter(ch)); // False
+ Console.WriteLine(Char.IsLetter("sample string", 7)); // True
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs b/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
index 253d41e3f6f..3a8fde0049b 100644
--- a/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
+++ b/snippets/csharp/System/Char/IsLetterOrDigit/isletterordigit.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsLetterOrDigitSample
-{
- public static void Main()
- {
- string str = "newline:\n";
+public class IsLetterOrDigitSample {
+ public static void Main() {
+ string str = "newline:\n";
- Console.WriteLine(char.IsLetterOrDigit('8')); // Output: "True"
- Console.WriteLine(char.IsLetterOrDigit(str, 8)); // Output: "False", because it's a newline
- }
+ Console.WriteLine(Char.IsLetterOrDigit('8')); // Output: "True"
+ Console.WriteLine(Char.IsLetterOrDigit(str, 8)); // Output: "False", because it's a newline
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsLower/islower.cs b/snippets/csharp/System/Char/IsLower/islower.cs
index b2a20399d04..67e7dbb06a6 100644
--- a/snippets/csharp/System/Char/IsLower/islower.cs
+++ b/snippets/csharp/System/Char/IsLower/islower.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsLowerSample
-{
- public static void Main()
- {
- char ch = 'a';
+public class IsLowerSample {
+ public static void Main() {
+ char ch = 'a';
- Console.WriteLine(char.IsLower(ch)); // Output: "True"
- Console.WriteLine(char.IsLower("upperCase", 5)); // Output: "False"
- }
+ Console.WriteLine(Char.IsLower(ch)); // Output: "True"
+ Console.WriteLine(Char.IsLower("upperCase", 5)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsNumber/isnumber.cs b/snippets/csharp/System/Char/IsNumber/isnumber.cs
index 2e0babb2655..b55268e15bc 100644
--- a/snippets/csharp/System/Char/IsNumber/isnumber.cs
+++ b/snippets/csharp/System/Char/IsNumber/isnumber.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsNumberSample
-{
- public static void Main()
- {
- string str = "non-numeric";
+public class IsNumberSample {
+ public static void Main() {
+ string str = "non-numeric";
- Console.WriteLine(char.IsNumber('8')); // Output: "True"
- Console.WriteLine(char.IsNumber(str, 3)); // Output: "False"
- }
+ Console.WriteLine(Char.IsNumber('8')); // Output: "True"
+ Console.WriteLine(Char.IsNumber(str, 3)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsNumber/isnumber1.cs b/snippets/csharp/System/Char/IsNumber/isnumber1.cs
index 1d8bce01820..cf24e3795b1 100644
--- a/snippets/csharp/System/Char/IsNumber/isnumber1.cs
+++ b/snippets/csharp/System/Char/IsNumber/isnumber1.cs
@@ -2,37 +2,40 @@
public class Example
{
- public static void Main()
- {
- Overload1();
- Console.WriteLine();
- Overload2();
- }
+ public static void Main()
+ {
+ Overload1();
+ Console.WriteLine();
+ Overload2();
+ }
- private static void Overload1()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = char.ConvertFromUtf32(utf32);
- foreach (char ch in surrogate)
- Console.WriteLine($"U+{Convert.ToUInt16(ch):X4}: {char.IsNumber(ch)}");
+ private static void Overload1()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = Char.ConvertFromUtf32(utf32);
+ foreach (var ch in surrogate)
+ Console.WriteLine("U+{0:X4}: {1}", Convert.ToUInt16(ch),
+ Char.IsNumber(ch));
- // The example displays the following output:
- // U+D800: False
- // U+DD07: False
- //
- }
+ // The example displays the following output:
+ // U+D800: False
+ // U+DD07: False
+ //
+ }
- private static void Overload2()
- {
- //
- int utf32 = 0x10107; // AEGEAN NUMBER ONE
- string surrogate = char.ConvertFromUtf32(utf32);
- for (int ctr = 0; ctr < surrogate.Length; ctr++)
- Console.WriteLine($"U+{Convert.ToUInt16(surrogate[ctr]):X4} at position {ctr}: {char.IsNumber(surrogate, ctr)}");
- // The example displays the following output:
- // U+D800 at position 0: True
- // U+DD07 at position 1: False
- //
- }
+ private static void Overload2()
+ {
+ //
+ int utf32 = 0x10107; // AEGEAN NUMBER ONE
+ string surrogate = Char.ConvertFromUtf32(utf32);
+ for (int ctr = 0; ctr < surrogate.Length; ctr++)
+ Console.WriteLine("U+{0:X4} at position {1}: {2}",
+ Convert.ToUInt16(surrogate[ctr]), ctr,
+ Char.IsNumber(surrogate, ctr));
+ // The example displays the following output:
+ // U+D800 at position 0: True
+ // U+DD07 at position 1: False
+ //
+ }
}
diff --git a/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs b/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
index 79c08f161d3..4b4f667495c 100644
--- a/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
+++ b/snippets/csharp/System/Char/IsPunctuation/ispunctuation.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsPunctuationSample
-{
- public static void Main()
- {
- char ch = '.';
+public class IsPunctuationSample {
+ public static void Main() {
+ char ch = '.';
- Console.WriteLine(char.IsPunctuation(ch)); // Output: "True"
- Console.WriteLine(char.IsPunctuation("no punctuation", 3)); // Output: "False"
- }
+ Console.WriteLine(Char.IsPunctuation(ch)); // Output: "True"
+ Console.WriteLine(Char.IsPunctuation("no punctuation", 3)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSeparator/isseparator.cs b/snippets/csharp/System/Char/IsSeparator/isseparator.cs
index 1186c007265..ccac637ab6d 100644
--- a/snippets/csharp/System/Char/IsSeparator/isseparator.cs
+++ b/snippets/csharp/System/Char/IsSeparator/isseparator.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsSeparatorSample
-{
- public static void Main()
- {
- string str = "twain1 twain2";
+public class IsSeparatorSample {
+ public static void Main() {
+ string str = "twain1 twain2";
- Console.WriteLine(char.IsSeparator('a')); // Output: "False"
- Console.WriteLine(char.IsSeparator(str, 6)); // Output: "True"
- }
+ Console.WriteLine(Char.IsSeparator('a')); // Output: "False"
+ Console.WriteLine(Char.IsSeparator(str, 6)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
index 353def1fcf6..c33c9f9591a 100644
--- a/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
+++ b/snippets/csharp/System/Char/IsSeparator/isseparator1.cs
@@ -3,15 +3,15 @@
public class Class1
{
- public static void Main()
- {
- for (int ctr = (int)(char.MinValue); ctr <= (int)(char.MaxValue); ctr++)
- {
- char ch = (char)ctr;
- if (char.IsSeparator(ch))
- Console.WriteLine(@"\u{(int)ch:X4} ({Char.GetUnicodeCategory(ch)})");
- }
- }
+ public static void Main()
+ {
+ for (int ctr = (int)(Char.MinValue); ctr <= (int)(Char.MaxValue); ctr++)
+ {
+ char ch = (Char)ctr;
+ if (Char.IsSeparator(ch))
+ Console.WriteLine(@"\u{(int)ch:X4} ({Char.GetUnicodeCategory(ch)})");
+ }
+ }
}
// The example displays the following output:
// \u0020 (SpaceSeparator)
diff --git a/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs b/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
index c9db1db5d34..362be515197 100644
--- a/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
+++ b/snippets/csharp/System/Char/IsSurrogate/issurrogate.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsSurrogateSample
-{
- public static void Main()
- {
- string str = "\U00010F00"; // Unicode values between 0x10000 and 0x10FFF are represented by two 16-bit "surrogate" characters
+public class IsSurrogateSample {
+ public static void Main() {
+ string str = "\U00010F00"; // Unicode values between 0x10000 and 0x10FFF are represented by two 16-bit "surrogate" characters
- Console.WriteLine(char.IsSurrogate('a')); // Output: "False"
- Console.WriteLine(char.IsSurrogate(str, 0)); // Output: "True"
- }
+ Console.WriteLine(Char.IsSurrogate('a')); // Output: "False"
+ Console.WriteLine(Char.IsSurrogate(str, 0)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsSymbol/issymbol.cs b/snippets/csharp/System/Char/IsSymbol/issymbol.cs
index 6bd6a86d3ab..745c2f40be8 100644
--- a/snippets/csharp/System/Char/IsSymbol/issymbol.cs
+++ b/snippets/csharp/System/Char/IsSymbol/issymbol.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsSymbolSample
-{
- public static void Main()
- {
- string str = "non-symbolic characters";
+public class IsSymbolSample {
+ public static void Main() {
+ string str = "non-symbolic characters";
- Console.WriteLine(char.IsSymbol('+')); // Output: "True"
- Console.WriteLine(char.IsSymbol(str, 8)); // Output: "False"
- }
+ Console.WriteLine(Char.IsSymbol('+')); // Output: "True"
+ Console.WriteLine(Char.IsSymbol(str, 8)); // Output: "False"
+ }
}
//
diff --git a/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs b/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
index ed9b5f0672a..2ababcb4773 100644
--- a/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
+++ b/snippets/csharp/System/Char/IsWhiteSpace/iswhitespace.cs
@@ -1,14 +1,12 @@
//
using System;
-public class IsWhiteSpaceSample
-{
- public static void Main()
- {
- string str = "black matter";
+public class IsWhiteSpaceSample {
+ public static void Main() {
+ string str = "black matter";
- Console.WriteLine(char.IsWhiteSpace('A')); // Output: "False"
- Console.WriteLine(char.IsWhiteSpace(str, 5)); // Output: "True"
- }
+ Console.WriteLine(Char.IsWhiteSpace('A')); // Output: "False"
+ Console.WriteLine(Char.IsWhiteSpace(str, 5)); // Output: "True"
+ }
}
//
diff --git a/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs b/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
index ff560ccd03c..a41456fc514 100644
--- a/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
+++ b/snippets/csharp/System/Char/Overview/GetUnicodeCategory3.cs
@@ -1,17 +1,17 @@
-//
+//
using System;
-
+using System.Globalization;
class Example
{
- public static void Main()
- {
- // Define a string with a variety of character categories.
- string s = "The red car drove down the long, narrow, secluded road.";
- // Determine the category of each character.
- foreach (char ch in s)
- Console.WriteLine($"'{ch}': {char.GetUnicodeCategory(ch)}");
- }
+ public static void Main()
+ {
+ // Define a string with a variety of character categories.
+ String s = "The red car drove down the long, narrow, secluded road.";
+ // Determine the category of each character.
+ foreach (var ch in s)
+ Console.WriteLine($"'{ch}': {Char.GetUnicodeCategory(ch)}");
+ }
}
// The example displays the following output:
// 'T': UppercaseLetter
diff --git a/snippets/csharp/System/Char/Overview/charstructure.cs b/snippets/csharp/System/Char/Overview/charstructure.cs
index 687a9e23d21..8b5600d535c 100644
--- a/snippets/csharp/System/Char/Overview/charstructure.cs
+++ b/snippets/csharp/System/Char/Overview/charstructure.cs
@@ -11,18 +11,18 @@ public static void Main()
Console.WriteLine(chA.CompareTo('B')); //----------- Output: "-1" (meaning 'A' is 1 less than 'B')
Console.WriteLine(chA.Equals('A')); //----------- Output: "True"
- Console.WriteLine(char.GetNumericValue(ch1)); //----------- Output: "1"
- Console.WriteLine(char.IsControl('\t')); //----------- Output: "True"
- Console.WriteLine(char.IsDigit(ch1)); //----------- Output: "True"
- Console.WriteLine(char.IsLetter(',')); //----------- Output: "False"
- Console.WriteLine(char.IsLower('u')); //----------- Output: "True"
- Console.WriteLine(char.IsNumber(ch1)); //----------- Output: "True"
- Console.WriteLine(char.IsPunctuation('.')); //----------- Output: "True"
- Console.WriteLine(char.IsSeparator(str, 4)); //----------- Output: "True"
- Console.WriteLine(char.IsSymbol('+')); //----------- Output: "True"
- Console.WriteLine(char.IsWhiteSpace(str, 4)); //----------- Output: "True"
- Console.WriteLine(char.Parse("S")); //----------- Output: "S"
- Console.WriteLine(char.ToLower('M')); //----------- Output: "m"
+ Console.WriteLine(Char.GetNumericValue(ch1)); //----------- Output: "1"
+ Console.WriteLine(Char.IsControl('\t')); //----------- Output: "True"
+ Console.WriteLine(Char.IsDigit(ch1)); //----------- Output: "True"
+ Console.WriteLine(Char.IsLetter(',')); //----------- Output: "False"
+ Console.WriteLine(Char.IsLower('u')); //----------- Output: "True"
+ Console.WriteLine(Char.IsNumber(ch1)); //----------- Output: "True"
+ Console.WriteLine(Char.IsPunctuation('.')); //----------- Output: "True"
+ Console.WriteLine(Char.IsSeparator(str, 4)); //----------- Output: "True"
+ Console.WriteLine(Char.IsSymbol('+')); //----------- Output: "True"
+ Console.WriteLine(Char.IsWhiteSpace(str, 4)); //----------- Output: "True"
+ Console.WriteLine(Char.Parse("S")); //----------- Output: "S"
+ Console.WriteLine(Char.ToLower('M')); //----------- Output: "m"
Console.WriteLine('x'.ToString()); //----------- Output: "x"
}
}
diff --git a/snippets/csharp/System/Char/Overview/grapheme1.cs b/snippets/csharp/System/Char/Overview/grapheme1.cs
index c426d21bad8..3282858b551 100644
--- a/snippets/csharp/System/Char/Overview/grapheme1.cs
+++ b/snippets/csharp/System/Char/Overview/grapheme1.cs
@@ -6,9 +6,9 @@ public class Example1
{
public static void Main()
{
- StreamWriter sw = new("chars1.txt");
- char[] chars = ['\u0061', '\u0308'];
- string strng = new(chars);
+ StreamWriter sw = new StreamWriter("chars1.txt");
+ char[] chars = [ '\u0061', '\u0308' ];
+ string strng = new String(chars);
sw.WriteLine(strng);
sw.Close();
}
diff --git a/snippets/csharp/System/Char/Overview/surrogate1.cs b/snippets/csharp/System/Char/Overview/surrogate1.cs
index 71088e4bdf4..767c0443120 100644
--- a/snippets/csharp/System/Char/Overview/surrogate1.cs
+++ b/snippets/csharp/System/Char/Overview/surrogate1.cs
@@ -6,9 +6,9 @@ public class Example3
{
public static void Main()
{
- StreamWriter sw = new(@".\chars2.txt");
+ StreamWriter sw = new StreamWriter(@".\chars2.txt");
int utf32 = 0x1D160;
- string surrogate = char.ConvertFromUtf32(utf32);
+ string surrogate = Char.ConvertFromUtf32(utf32);
sw.WriteLine($"U+{utf32:X6} UTF-32 = {surrogate} ({ShowCodePoints(surrogate)}) UTF-16");
sw.Close();
}
@@ -16,7 +16,7 @@ public static void Main()
private static string ShowCodePoints(string value)
{
string retval = null;
- foreach (char ch in value)
+ foreach (var ch in value)
retval += $"U+{Convert.ToUInt16(ch):X4} ";
return retval.Trim();
diff --git a/snippets/csharp/System/Char/Overview/textelements2.cs b/snippets/csharp/System/Char/Overview/textelements2.cs
index bddc5de6457..c039c618373 100644
--- a/snippets/csharp/System/Char/Overview/textelements2.cs
+++ b/snippets/csharp/System/Char/Overview/textelements2.cs
@@ -1,13 +1,13 @@
-//
+//
using System;
public class Example5
{
public static void Main()
{
- string result = string.Empty;
+ string result = String.Empty;
for (int ctr = 0x10107; ctr <= 0x10110; ctr++) // Range of Aegean numbers.
- result += char.ConvertFromUtf32(ctr);
+ result += Char.ConvertFromUtf32(ctr);
Console.WriteLine($"The string contains {result.Length} characters.");
}
diff --git a/snippets/csharp/System/Char/Overview/textelements2a.cs b/snippets/csharp/System/Char/Overview/textelements2a.cs
index 467714bae69..e6bcb56f7d7 100644
--- a/snippets/csharp/System/Char/Overview/textelements2a.cs
+++ b/snippets/csharp/System/Char/Overview/textelements2a.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using System.Globalization;
@@ -6,11 +6,11 @@ public class Example4
{
public static void Main()
{
- string result = string.Empty;
+ string result = String.Empty;
for (int ctr = 0x10107; ctr <= 0x10110; ctr++) // Range of Aegean numbers.
- result += char.ConvertFromUtf32(ctr);
+ result += Char.ConvertFromUtf32(ctr);
- StringInfo si = new(result);
+ StringInfo si = new StringInfo(result);
Console.WriteLine($"The string contains {si.LengthInTextElements} characters.");
}
}
diff --git a/snippets/csharp/System/Char/Parse/parse.cs b/snippets/csharp/System/Char/Parse/parse.cs
index 98a492d3653..f7d5733e55d 100644
--- a/snippets/csharp/System/Char/Parse/parse.cs
+++ b/snippets/csharp/System/Char/Parse/parse.cs
@@ -1,11 +1,9 @@
//
using System;
-public class ParseSample
-{
- public static void Main()
- {
- Console.WriteLine(char.Parse("A")); // Output: 'A'
- }
+public class ParseSample {
+ public static void Main() {
+ Console.WriteLine(Char.Parse("A")); // Output: 'A'
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToLower/tolower.cs b/snippets/csharp/System/Char/ToLower/tolower.cs
index 3507a0514f9..11cfa4604d9 100644
--- a/snippets/csharp/System/Char/ToLower/tolower.cs
+++ b/snippets/csharp/System/Char/ToLower/tolower.cs
@@ -1,12 +1,10 @@
//
using System;
+using System.Globalization;
-
-public class ToLowerSample
-{
- public static void Main()
- {
- Console.WriteLine(char.ToLower('A')); // Output: "a"
- }
+public class ToLowerSample {
+ public static void Main() {
+ Console.WriteLine(Char.ToLower('A')); // Output: "a"
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToString/tostring.cs b/snippets/csharp/System/Char/ToString/tostring.cs
index 1d1c0a6d7b5..2f8456a8f81 100644
--- a/snippets/csharp/System/Char/ToString/tostring.cs
+++ b/snippets/csharp/System/Char/ToString/tostring.cs
@@ -1,14 +1,12 @@
//
using System;
-public class ToStringSample
-{
- public static void Main()
- {
- char ch = 'a';
- Console.WriteLine(ch.ToString()); // Output: "a"
+public class ToStringSample {
+ public static void Main() {
+ char ch = 'a';
+ Console.WriteLine(ch.ToString()); // Output: "a"
- Console.WriteLine(char.ToString('b')); // Output: "b"
- }
+ Console.WriteLine(Char.ToString('b')); // Output: "b"
+ }
}
//
diff --git a/snippets/csharp/System/Char/ToUpper/toupper1.cs b/snippets/csharp/System/Char/ToUpper/toupper1.cs
index abd6696dea2..e37a5aad0ba 100644
--- a/snippets/csharp/System/Char/ToUpper/toupper1.cs
+++ b/snippets/csharp/System/Char/ToUpper/toupper1.cs
@@ -3,12 +3,13 @@
public class Example
{
- public static void Main()
- {
- char[] chars = { 'e', 'E', '6', ',', 'ж', 'ä' };
- foreach (char ch in chars)
- Console.WriteLine($"{ch} --> {char.ToUpper(ch)} {(ch == char.ToUpper(ch) ? "(Same Character)" : "")}");
- }
+ public static void Main()
+ {
+ char[] chars = { 'e', 'E', '6', ',', 'ж', 'ä' };
+ foreach (var ch in chars)
+ Console.WriteLine("{0} --> {1} {2}", ch, Char.ToUpper(ch),
+ ch == Char.ToUpper(ch) ? "(Same Character)" : "" );
+ }
}
// The example displays the following output:
// e --> E
diff --git a/snippets/csharp/System/Char/ToUpper/toupper5.cs b/snippets/csharp/System/Char/ToUpper/toupper5.cs
index d2079357a6a..f42420da25f 100644
--- a/snippets/csharp/System/Char/ToUpper/toupper5.cs
+++ b/snippets/csharp/System/Char/ToUpper/toupper5.cs
@@ -4,23 +4,22 @@
public class Example
{
- public static void Main()
- {
- CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
+ public static void Main()
+ {
+ CultureInfo[] cultures= { CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.InvariantCulture,
CultureInfo.CreateSpecificCulture("tr-TR") };
- char[] chars = { 'ä', 'e', 'E', 'i', 'I' };
+ Char[] chars = {'ä', 'e', 'E', 'i', 'I' };
- Console.WriteLine("Character en-US Invariant tr-TR");
- foreach (char ch in chars)
- {
- Console.Write($" {ch}");
- foreach (var culture in cultures)
- Console.Write($"{char.ToUpper(ch, culture),12}");
+ Console.WriteLine("Character en-US Invariant tr-TR");
+ foreach (var ch in chars) {
+ Console.Write(" {0}", ch);
+ foreach (var culture in cultures)
+ Console.Write("{0,12}", Char.ToUpper(ch, culture));
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Character en-US Invariant tr-TR
@@ -29,4 +28,4 @@ public static void Main()
// E E E E
// i I I İ
// I I I I
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Char/TryParse/tp.cs b/snippets/csharp/System/Char/TryParse/tp.cs
index 6c9a8695466..09410a90088 100644
--- a/snippets/csharp/System/Char/TryParse/tp.cs
+++ b/snippets/csharp/System/Char/TryParse/tp.cs
@@ -16,132 +16,132 @@ class Sample
{
public static void Main()
{
- bool success;
- CultureInfo ci;
- string nl = Environment.NewLine;
- string msg1 =
- "This example demonstrates overloads of the TryParse method for{0}" +
- "several base types, as well as the TryParseExact method for DateTime.{0}";
- string msg2 = "Non-numeric types:{0}";
- string msg3 = "{0}Numeric types:{0}";
- string msg4 = "{0}The following types are not CLS-compliant:{0}";
-
- // Non-numeric types.
- bool booleanVal;
- char charVal;
- DateTime datetimeVal;
-
- // Numeric types.
- byte byteVal;
- short int16Val;
- int int32Val;
- long int64Val;
- decimal decimalVal;
- float singleVal;
- double doubleVal;
-
- // The following types are not CLS-compliant.
- sbyte sbyteVal;
- ushort uint16Val;
- uint uint32Val;
- ulong uint64Val;
- //
- Console.WriteLine(msg1, nl);
-
- // Non-numeric types:
- Console.WriteLine(msg2, nl);
- // DateTime
- // TryParse:
- // Assume current culture is en-US, and dates of the form: MMDDYYYY.
- success = DateTime.TryParse("7/4/2004 12:34:56", out datetimeVal);
- Show(success, "DateTime #1", datetimeVal.ToString());
-
- // Use fr-FR culture, and dates of the form: DDMMYYYY.
- ci = new("fr-FR");
- success = DateTime.TryParse("4/7/2004 12:34:56",
- ci, DateTimeStyles.None, out datetimeVal);
- Show(success, "DateTime #2", datetimeVal.ToString());
-
- // TryParseExact:
- // Use fr-FR culture. The format, "G", is short date and long time.
- success = DateTime.TryParseExact("04/07/2004 12:34:56", "G",
- ci, DateTimeStyles.None, out datetimeVal);
- Show(success, "DateTime #3", datetimeVal.ToString());
-
- // Assume en-US culture.
- string[] dateFormats = { "f", "F", "g", "G" };
- success = DateTime.TryParseExact("7/4/2004 12:34:56 PM",
- dateFormats, null, DateTimeStyles.None,
- out datetimeVal);
- Show(success, "DateTime #4", datetimeVal.ToString());
-
- Console.WriteLine();
- // Boolean
- success = bool.TryParse("true", out booleanVal);
- Show(success, "Boolean", booleanVal.ToString());
- // Char
- success = char.TryParse("A", out charVal);
- Show(success, "Char", charVal.ToString());
-
- // Numeric types:
- Console.WriteLine(msg3, nl);
- // Byte
- success = byte.TryParse("1", NumberStyles.Integer, null, out byteVal);
- Show(success, "Byte", byteVal.ToString());
- // Int16
- success = short.TryParse("-2", NumberStyles.Integer, null, out int16Val);
- Show(success, "Int16", int16Val.ToString());
- // Int32
- success = int.TryParse("3", NumberStyles.Integer, null, out int32Val);
- Show(success, "Int32", int32Val.ToString());
- // Int64
- success = long.TryParse("4", NumberStyles.Integer, null, out int64Val);
- Show(success, "Int64", int64Val.ToString());
- // Decimal
- success = decimal.TryParse("-5.5", NumberStyles.Number, null, out decimalVal);
- Show(success, "Decimal", decimalVal.ToString());
- // Single
- success = float.TryParse("6.6",
- (NumberStyles.Float | NumberStyles.AllowThousands),
- null, out singleVal);
- Show(success, "Single", singleVal.ToString());
- // Double
- success = double.TryParse("-7",
- (NumberStyles.Float | NumberStyles.AllowThousands),
- null, out doubleVal);
- Show(success, "Double", doubleVal.ToString());
-
- // Use the simple Double.TryParse overload, but specify an invalid value.
-
- success = double.TryParse("abc", out doubleVal);
- Show(success, "Double #2", doubleVal.ToString());
- //
- Console.WriteLine(msg4, nl);
- // SByte
- success = sbyte.TryParse("-8", NumberStyles.Integer, null, out sbyteVal);
- Show(success, "SByte", sbyteVal.ToString());
- // UInt16
- success = ushort.TryParse("9", NumberStyles.Integer, null, out uint16Val);
- Show(success, "UInt16", uint16Val.ToString());
- // UInt32
- success = uint.TryParse("10", NumberStyles.Integer, null, out uint32Val);
- Show(success, "UInt32", uint32Val.ToString());
- // UInt64
- success = ulong.TryParse("11", NumberStyles.Integer, null, out uint64Val);
- Show(success, "UInt64", uint64Val.ToString());
+ bool success;
+ CultureInfo ci;
+ string nl = Environment.NewLine;
+ string msg1 =
+ "This example demonstrates overloads of the TryParse method for{0}" +
+ "several base types, as well as the TryParseExact method for DateTime.{0}";
+ string msg2 = "Non-numeric types:{0}";
+ string msg3 = "{0}Numeric types:{0}";
+ string msg4 = "{0}The following types are not CLS-compliant:{0}";
+
+// Non-numeric types.
+ Boolean booleanVal;
+ Char charVal;
+ DateTime datetimeVal;
+
+// Numeric types.
+ Byte byteVal;
+ Int16 int16Val;
+ Int32 int32Val;
+ Int64 int64Val;
+ Decimal decimalVal;
+ Single singleVal;
+ Double doubleVal;
+
+// The following types are not CLS-compliant.
+ SByte sbyteVal;
+ UInt16 uint16Val;
+ UInt32 uint32Val;
+ UInt64 uint64Val;
+//
+ Console.WriteLine(msg1, nl);
+
+// Non-numeric types:
+ Console.WriteLine(msg2, nl);
+// DateTime
+ // TryParse:
+ // Assume current culture is en-US, and dates of the form: MMDDYYYY.
+ success = DateTime.TryParse("7/4/2004 12:34:56", out datetimeVal);
+ Show(success, "DateTime #1", datetimeVal.ToString());
+
+ // Use fr-FR culture, and dates of the form: DDMMYYYY.
+ ci = new CultureInfo("fr-FR");
+ success = DateTime.TryParse("4/7/2004 12:34:56",
+ ci, DateTimeStyles.None, out datetimeVal);
+ Show(success, "DateTime #2", datetimeVal.ToString());
+
+ // TryParseExact:
+ // Use fr-FR culture. The format, "G", is short date and long time.
+ success = DateTime.TryParseExact("04/07/2004 12:34:56", "G",
+ ci, DateTimeStyles.None, out datetimeVal);
+ Show(success, "DateTime #3", datetimeVal.ToString());
+
+ // Assume en-US culture.
+ string[] dateFormats = {"f", "F", "g", "G"};
+ success = DateTime.TryParseExact("7/4/2004 12:34:56 PM",
+ dateFormats, null, DateTimeStyles.None,
+ out datetimeVal);
+ Show(success, "DateTime #4", datetimeVal.ToString());
+
+ Console.WriteLine();
+// Boolean
+ success = Boolean.TryParse("true", out booleanVal);
+ Show(success, "Boolean", booleanVal.ToString());
+// Char
+ success = Char.TryParse("A", out charVal);
+ Show(success, "Char", charVal.ToString());
+
+// Numeric types:
+ Console.WriteLine(msg3, nl);
+// Byte
+ success = Byte.TryParse("1", NumberStyles.Integer, null, out byteVal);
+ Show(success, "Byte", byteVal.ToString());
+// Int16
+ success = Int16.TryParse("-2", NumberStyles.Integer, null, out int16Val);
+ Show(success, "Int16", int16Val.ToString());
+// Int32
+ success = Int32.TryParse("3", NumberStyles.Integer, null, out int32Val);
+ Show(success, "Int32", int32Val.ToString());
+// Int64
+ success = Int64.TryParse("4", NumberStyles.Integer, null, out int64Val);
+ Show(success, "Int64", int64Val.ToString());
+// Decimal
+ success = Decimal.TryParse("-5.5", NumberStyles.Number, null, out decimalVal);
+ Show(success, "Decimal", decimalVal.ToString());
+// Single
+ success = Single.TryParse("6.6",
+ (NumberStyles.Float | NumberStyles.AllowThousands),
+ null, out singleVal);
+ Show(success, "Single", singleVal.ToString());
+// Double
+ success = Double.TryParse("-7",
+ (NumberStyles.Float | NumberStyles.AllowThousands),
+ null, out doubleVal);
+ Show(success, "Double", doubleVal.ToString());
+
+// Use the simple Double.TryParse overload, but specify an invalid value.
+
+ success = Double.TryParse("abc", out doubleVal);
+ Show(success, "Double #2", doubleVal.ToString());
+//
+ Console.WriteLine(msg4, nl);
+// SByte
+ success = SByte.TryParse("-8", NumberStyles.Integer, null, out sbyteVal);
+ Show(success, "SByte", sbyteVal.ToString());
+// UInt16
+ success = UInt16.TryParse("9", NumberStyles.Integer, null, out uint16Val);
+ Show(success, "UInt16", uint16Val.ToString());
+// UInt32
+ success = UInt32.TryParse("10", NumberStyles.Integer, null, out uint32Val);
+ Show(success, "UInt32", uint32Val.ToString());
+// UInt64
+ success = UInt64.TryParse("11", NumberStyles.Integer, null, out uint64Val);
+ Show(success, "UInt64", uint64Val.ToString());
}
protected static void Show(bool parseSuccess, string typeName,
string parseValue)
{
- string msgSuccess = "Parse for {0} = {1}";
- string msgFailure = "** Parse for {0} failed. Invalid input.";
- //
- if (parseSuccess)
- Console.WriteLine(msgSuccess, typeName, parseValue);
- else
- Console.WriteLine(msgFailure, typeName);
- }
+ string msgSuccess = "Parse for {0} = {1}";
+ string msgFailure = "** Parse for {0} failed. Invalid input.";
+//
+ if (parseSuccess )
+ Console.WriteLine(msgSuccess, typeName, parseValue);
+ else
+ Console.WriteLine(msgFailure, typeName);
+ }
}
/*
This example produces the following results:
diff --git a/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs b/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
index fc8b67530b4..f1cdd898f25 100644
--- a/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
+++ b/snippets/csharp/System/CharEnumerator/Overview/CharEnumerator1.cs
@@ -2,69 +2,71 @@
public class Class1
{
- public static void Main()
- {
- UseCharEnumerator();
- Console.WriteLine("-----");
- UseForEach();
- }
+ public static void Main()
+ {
+ UseCharEnumerator();
+ Console.WriteLine("-----");
+ UseForEach();
+ }
- private static void UseCharEnumerator()
- {
- //
- string title = "A Tale of Two Cities";
- CharEnumerator chEnum = title.GetEnumerator();
- int ctr = 1;
- string outputLine1 = null;
- string outputLine2 = null;
- string outputLine3 = null;
+ private static void UseCharEnumerator()
+ {
+ //
+ string title = "A Tale of Two Cities";
+ CharEnumerator chEnum = title.GetEnumerator();
+ int ctr = 1;
+ string outputLine1 = null;
+ string outputLine2 = null;
+ string outputLine3 = null;
- while (chEnum.MoveNext())
- {
- outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
- outputLine2 += (ctr % 10) + " ";
- outputLine3 += chEnum.Current + " ";
- ctr++;
- }
+ while (chEnum.MoveNext())
+ {
+ outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
+ outputLine2 += (ctr % 10) + " ";
+ outputLine3 += chEnum.Current + " ";
+ ctr++;
+ }
- Console.WriteLine($"The length of the string is {title.Length} characters:");
- Console.WriteLine(outputLine1);
- Console.WriteLine(outputLine2);
- Console.WriteLine(outputLine3);
- // The example displays the following output to the console:
- // The length of the string is 20 characters:
- // 1 2
- // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
- // A T a l e o f T w o C i t i e s
- //
- }
+ Console.WriteLine("The length of the string is {0} characters:",
+ title.Length);
+ Console.WriteLine(outputLine1);
+ Console.WriteLine(outputLine2);
+ Console.WriteLine(outputLine3);
+ // The example displays the following output to the console:
+ // The length of the string is 20 characters:
+ // 1 2
+ // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
+ // A T a l e o f T w o C i t i e s
+ //
+ }
- private static void UseForEach()
- {
- //
- string title = "A Tale of Two Cities";
- int ctr = 1;
- string outputLine1 = null;
- string outputLine2 = null;
- string outputLine3 = null;
+ private static void UseForEach()
+ {
+ //
+ string title = "A Tale of Two Cities";
+ int ctr = 1;
+ string outputLine1 = null;
+ string outputLine2 = null;
+ string outputLine3 = null;
- foreach (char ch in title)
- {
- outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
- outputLine2 += (ctr % 10) + " ";
- outputLine3 += ch + " ";
- ctr++;
- }
+ foreach (char ch in title)
+ {
+ outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
+ outputLine2 += (ctr % 10) + " ";
+ outputLine3 += ch + " ";
+ ctr++;
+ }
- Console.WriteLine($"The length of the string is {title.Length} characters:");
- Console.WriteLine(outputLine1);
- Console.WriteLine(outputLine2);
- Console.WriteLine(outputLine3);
- // The example displays the following output to the console:
- // The length of the string is 20 characters:
- // 1 2
- // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
- // A T a l e o f T w o C i t i e s
- //
- }
+ Console.WriteLine("The length of the string is {0} characters:",
+ title.Length);
+ Console.WriteLine(outputLine1);
+ Console.WriteLine(outputLine2);
+ Console.WriteLine(outputLine3);
+ // The example displays the following output to the console:
+ // The length of the string is 20 characters:
+ // 1 2
+ // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
+ // A T a l e o f T w o C i t i e s
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/BackgroundColor/Example2.cs b/snippets/csharp/System/Console/BackgroundColor/Example2.cs
index 4ed1d70b2e2..93af82b7407 100644
--- a/snippets/csharp/System/Console/BackgroundColor/Example2.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/Example2.cs
@@ -3,14 +3,13 @@
public class Example
{
- public static void Main()
- {
- if (Console.BackgroundColor == ConsoleColor.Black)
- {
- Console.BackgroundColor = ConsoleColor.Red;
- Console.ForegroundColor = ConsoleColor.Black;
- Console.Clear();
- }
- }
+ public static void Main()
+ {
+ if (Console.BackgroundColor == ConsoleColor.Black) {
+ Console.BackgroundColor = ConsoleColor.Red;
+ Console.ForegroundColor = ConsoleColor.Black;
+ Console.Clear();
+ }
+ }
}
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs b/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
index 4e3573448b3..bd79ec6e0d4 100644
--- a/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/backgroundcolor1.cs
@@ -3,29 +3,28 @@
public class Example
{
- public static void Main()
- {
- WriteCharacterStrings(1, 26, true);
- Console.MoveBufferArea(0, Console.CursorTop - 10, 30, 1,
- Console.CursorLeft, Console.CursorTop + 1);
- Console.CursorTop = Console.CursorTop + 3;
- Console.WriteLine("Press any key...");
- Console.ReadKey();
+ public static void Main()
+ {
+ WriteCharacterStrings(1, 26, true);
+ Console.MoveBufferArea(0, Console.CursorTop - 10, 30, 1,
+ Console.CursorLeft, Console.CursorTop + 1);
+ Console.CursorTop = Console.CursorTop + 3;
+ Console.WriteLine("Press any key...");
+ Console.ReadKey();
- Console.Clear();
- WriteCharacterStrings(1, 26, false);
- }
+ Console.Clear();
+ WriteCharacterStrings(1, 26, false);
+ }
- private static void WriteCharacterStrings(int start, int end,
- bool changeColor)
- {
- for (int ctr = start; ctr <= end; ctr++)
- {
- if (changeColor)
- Console.BackgroundColor = (ConsoleColor)((ctr - 1) % 16);
+ private static void WriteCharacterStrings(int start, int end,
+ bool changeColor)
+ {
+ for (int ctr = start; ctr <= end; ctr++) {
+ if (changeColor)
+ Console.BackgroundColor = (ConsoleColor) ((ctr - 1) % 16);
- Console.WriteLine(new string((char)(ctr + 64), 30));
- }
- }
+ Console.WriteLine(new String((char)(ctr + 64), 30));
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs b/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
index f651b63ca00..107b7e78c64 100644
--- a/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
+++ b/snippets/csharp/System/Console/BackgroundColor/foregroundcolor3.cs
@@ -3,41 +3,41 @@
class Example
{
- public static void Main()
- {
- // Get an array with the values of ConsoleColor enumeration members.
- ConsoleColor[] colors = (ConsoleColor[])ConsoleColor.GetValues(typeof(ConsoleColor));
- // Save the current background and foreground colors.
- ConsoleColor currentBackground = Console.BackgroundColor;
- ConsoleColor currentForeground = Console.ForegroundColor;
+ public static void Main()
+ {
+ // Get an array with the values of ConsoleColor enumeration members.
+ ConsoleColor[] colors = (ConsoleColor[]) ConsoleColor.GetValues(typeof(ConsoleColor));
+ // Save the current background and foreground colors.
+ ConsoleColor currentBackground = Console.BackgroundColor;
+ ConsoleColor currentForeground = Console.ForegroundColor;
- // Display all foreground colors except the one that matches the background.
- Console.WriteLine($"All the foreground colors except {currentBackground}, the background color:");
- foreach (var color in colors)
- {
- if (color == currentBackground) continue;
+ // Display all foreground colors except the one that matches the background.
+ Console.WriteLine("All the foreground colors except {0}, the background color:",
+ currentBackground);
+ foreach (var color in colors) {
+ if (color == currentBackground) continue;
- Console.ForegroundColor = color;
- Console.WriteLine($" The foreground color is {color}.");
- }
- Console.WriteLine();
- // Restore the foreground color.
- Console.ForegroundColor = currentForeground;
+ Console.ForegroundColor = color;
+ Console.WriteLine(" The foreground color is {0}.", color);
+ }
+ Console.WriteLine();
+ // Restore the foreground color.
+ Console.ForegroundColor = currentForeground;
- // Display each background color except the one that matches the current foreground color.
- Console.WriteLine($"All the background colors except {currentForeground}, the foreground color:");
- foreach (var color in colors)
- {
- if (color == currentForeground) continue;
+ // Display each background color except the one that matches the current foreground color.
+ Console.WriteLine("All the background colors except {0}, the foreground color:",
+ currentForeground);
+ foreach (var color in colors) {
+ if (color == currentForeground) continue;
- Console.BackgroundColor = color;
- Console.WriteLine($" The background color is {color}.");
- }
+ Console.BackgroundColor = color;
+ Console.WriteLine(" The background color is {0}.", color);
+ }
- // Restore the original console colors.
- Console.ResetColor();
- Console.WriteLine("\nOriginal colors restored...");
- }
+ // Restore the original console colors.
+ Console.ResetColor();
+ Console.WriteLine("\nOriginal colors restored...");
+ }
}
//The example displays output like the following:
// All the foreground colors except DarkCyan, the background color:
diff --git a/snippets/csharp/System/Console/Beep/b2.cs b/snippets/csharp/System/Console/Beep/b2.cs
index a7971078dba..c5ff8c085b4 100644
--- a/snippets/csharp/System/Console/Beep/b2.cs
+++ b/snippets/csharp/System/Console/Beep/b2.cs
@@ -7,9 +7,9 @@ class Sample
{
public static void Main()
{
- // Declare the first few notes of the song, "Mary Had A Little Lamb".
- Note[] Mary =
- {
+// Declare the first few notes of the song, "Mary Had A Little Lamb".
+ Note[] Mary =
+ {
new Note(Tone.B, Duration.QUARTER),
new Note(Tone.A, Duration.QUARTER),
new Note(Tone.GbelowC, Duration.QUARTER),
@@ -24,69 +24,69 @@ public static void Main()
new Note(Tone.D, Duration.QUARTER),
new Note(Tone.D, Duration.HALF)
};
- // Play the song
- Play(Mary);
+// Play the song
+ Play(Mary);
}
- // Play the notes in a song.
+// Play the notes in a song.
protected static void Play(Note[] tune)
{
- foreach (Note n in tune)
+ foreach (Note n in tune)
{
- if (n.NoteTone == Tone.REST)
- Thread.Sleep((int)n.NoteDuration);
- else
- Console.Beep((int)n.NoteTone, (int)n.NoteDuration);
+ if (n.NoteTone == Tone.REST)
+ Thread.Sleep((int)n.NoteDuration);
+ else
+ Console.Beep((int)n.NoteTone, (int)n.NoteDuration);
}
}
- // Define the frequencies of notes in an octave, as well as
- // silence (rest).
+// Define the frequencies of notes in an octave, as well as
+// silence (rest).
protected enum Tone
{
- REST = 0,
- GbelowC = 196,
- A = 220,
- Asharp = 233,
- B = 247,
- C = 262,
- Csharp = 277,
- D = 294,
- Dsharp = 311,
- E = 330,
- F = 349,
- Fsharp = 370,
- G = 392,
- Gsharp = 415,
+ REST = 0,
+ GbelowC = 196,
+ A = 220,
+ Asharp = 233,
+ B = 247,
+ C = 262,
+ Csharp = 277,
+ D = 294,
+ Dsharp = 311,
+ E = 330,
+ F = 349,
+ Fsharp = 370,
+ G = 392,
+ Gsharp = 415,
}
- // Define the duration of a note in units of milliseconds.
+// Define the duration of a note in units of milliseconds.
protected enum Duration
{
- WHOLE = 1600,
- HALF = WHOLE / 2,
- QUARTER = HALF / 2,
- EIGHTH = QUARTER / 2,
- SIXTEENTH = EIGHTH / 2,
+ WHOLE = 1600,
+ HALF = WHOLE/2,
+ QUARTER = HALF/2,
+ EIGHTH = QUARTER/2,
+ SIXTEENTH = EIGHTH/2,
}
- // Define a note as a frequency (tone) and the amount of
- // time (duration) the note plays.
+// Define a note as a frequency (tone) and the amount of
+// time (duration) the note plays.
protected struct Note
{
- Tone toneVal;
- Duration durVal;
+ Tone toneVal;
+ Duration durVal;
- // Define a constructor to create a specific note.
- public Note(Tone frequency, Duration time)
+// Define a constructor to create a specific note.
+ public Note(Tone frequency, Duration time)
{
- toneVal = frequency;
- durVal = time;
+ toneVal = frequency;
+ durVal = time;
}
- // Define properties to return the note's tone and duration.
- public Tone NoteTone => toneVal;
- public Duration NoteDuration => durVal;
+// Define properties to return the note's tone and duration.
+ public Tone NoteTone { get{ return toneVal; } }
+ public Duration NoteDuration { get{ return durVal; } }
}
}
/*
@@ -95,4 +95,4 @@ public Note(Tone frequency, Duration time)
This example plays the first few notes of "Mary Had A Little Lamb"
through the console speaker.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/Beep/beep.cs b/snippets/csharp/System/Console/Beep/beep.cs
index cd7260caaf7..7dbfc5fbc16 100644
--- a/snippets/csharp/System/Console/Beep/beep.cs
+++ b/snippets/csharp/System/Console/Beep/beep.cs
@@ -4,21 +4,21 @@
class Sample
{
- public static void Main(string[] args)
+ public static void Main(String[] args)
{
- int x = 0;
- //
- if ((args.Length == 1) &&
- (int.TryParse(args[0], out x)) &&
- ((x >= 1) && (x <= 9)))
+ int x = 0;
+//
+ if ((args.Length == 1) &&
+ (Int32.TryParse(args[0], out x)) &&
+ ((x >= 1) && (x <= 9)))
{
- for (int i = 1; i <= x; i++)
+ for (int i = 1; i <= x; i++)
{
- Console.WriteLine($"Beep number {i}.");
- Console.Beep();
+ Console.WriteLine("Beep number {0}.", i);
+ Console.Beep();
}
}
- else
+ else
{
Console.WriteLine("Usage: Enter the number of times (between 1 and 9) to beep.");
}
@@ -42,4 +42,4 @@ Beep number 8.
Beep number 9.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/BufferHeight/hw.cs b/snippets/csharp/System/Console/BufferHeight/hw.cs
index 8eb4f0ed291..a7494f02e0f 100644
--- a/snippets/csharp/System/Console/BufferHeight/hw.cs
+++ b/snippets/csharp/System/Console/BufferHeight/hw.cs
@@ -7,8 +7,10 @@ class Sample
{
public static void Main()
{
- Console.WriteLine($"The current buffer height is {Console.BufferHeight} rows.");
- Console.WriteLine($"The current buffer width is {Console.BufferWidth} columns.");
+ Console.WriteLine("The current buffer height is {0} rows.",
+ Console.BufferHeight);
+ Console.WriteLine("The current buffer width is {0} columns.",
+ Console.BufferWidth);
}
}
/*
@@ -17,4 +19,4 @@ public static void Main()
The current buffer height is 300 rows.
The current buffer width is 85 columns.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/CancelKeyPress/ckp.cs b/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
index 85990e0ffae..dfe22b6d9f3 100644
--- a/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
+++ b/snippets/csharp/System/Console/CancelKeyPress/ckp.cs
@@ -10,7 +10,7 @@ public static void Main()
Console.Clear();
// Establish an event handler to process key press events.
- Console.CancelKeyPress += new(myHandler);
+ Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
while (true)
{
Console.Write("Press any key, or 'X' to quit, or ");
diff --git a/snippets/csharp/System/Console/Clear/clear1.cs b/snippets/csharp/System/Console/Clear/clear1.cs
index d1572e44d0d..ee3a91ec720 100644
--- a/snippets/csharp/System/Console/Clear/clear1.cs
+++ b/snippets/csharp/System/Console/Clear/clear1.cs
@@ -3,87 +3,83 @@
public class Example
{
- public static void Main()
- {
- // Save colors so they can be restored when use finishes input.
- ConsoleColor dftForeColor = Console.ForegroundColor;
- ConsoleColor dftBackColor = Console.BackgroundColor;
- bool continueFlag = true;
- Console.Clear();
+ public static void Main()
+ {
+ // Save colors so they can be restored when use finishes input.
+ ConsoleColor dftForeColor = Console.ForegroundColor;
+ ConsoleColor dftBackColor = Console.BackgroundColor;
+ bool continueFlag = true;
+ Console.Clear();
- do
- {
- ConsoleColor newForeColor = ConsoleColor.White;
- ConsoleColor newBackColor = ConsoleColor.Black;
+ do {
+ ConsoleColor newForeColor = ConsoleColor.White;
+ ConsoleColor newBackColor = ConsoleColor.Black;
- char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ",
- new char[] { 'B', 'R', 'Y' });
- switch (foreColorSelection)
- {
- case 'B':
- case 'b':
- newForeColor = ConsoleColor.DarkBlue;
- break;
- case 'R':
- case 'r':
- newForeColor = ConsoleColor.DarkRed;
- break;
- case 'Y':
- case 'y':
- newForeColor = ConsoleColor.DarkYellow;
- break;
- }
- char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
- new char[] { 'W', 'G', 'M' });
- switch (backColorSelection)
- {
- case 'W':
- case 'w':
- newBackColor = ConsoleColor.White;
- break;
- case 'G':
- case 'g':
- newBackColor = ConsoleColor.Green;
- break;
- case 'M':
- case 'm':
- newBackColor = ConsoleColor.Magenta;
- break;
- }
+ Char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ",
+ new Char[] { 'B', 'R', 'Y' } );
+ switch (foreColorSelection) {
+ case 'B':
+ case 'b':
+ newForeColor = ConsoleColor.DarkBlue;
+ break;
+ case 'R':
+ case 'r':
+ newForeColor = ConsoleColor.DarkRed;
+ break;
+ case 'Y':
+ case 'y':
+ newForeColor = ConsoleColor.DarkYellow;
+ break;
+ }
+ Char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ",
+ new Char[] { 'W', 'G', 'M' });
+ switch (backColorSelection) {
+ case 'W':
+ case 'w':
+ newBackColor = ConsoleColor.White;
+ break;
+ case 'G':
+ case 'g':
+ newBackColor = ConsoleColor.Green;
+ break;
+ case 'M':
+ case 'm':
+ newBackColor = ConsoleColor.Magenta;
+ break;
+ }
- Console.WriteLine();
- Console.Write("Enter a message to display: ");
- string textToDisplay = Console.ReadLine();
- Console.WriteLine();
- Console.ForegroundColor = newForeColor;
- Console.BackgroundColor = newBackColor;
- Console.WriteLine(textToDisplay);
- Console.WriteLine();
- if (char.ToUpper(GetKeyPress("Display another message (Y/N): ", new char[] { 'Y', 'N' })) == 'N')
- continueFlag = false;
+ Console.WriteLine();
+ Console.Write("Enter a message to display: ");
+ String textToDisplay = Console.ReadLine();
+ Console.WriteLine();
+ Console.ForegroundColor = newForeColor;
+ Console.BackgroundColor = newBackColor;
+ Console.WriteLine(textToDisplay);
+ Console.WriteLine();
+ if (Char.ToUpper(GetKeyPress("Display another message (Y/N): ", new Char[] { 'Y', 'N' } )) == 'N')
+ continueFlag = false;
- // Restore the default settings and clear the screen.
- Console.ForegroundColor = dftForeColor;
- Console.BackgroundColor = dftBackColor;
- Console.Clear();
- } while (continueFlag);
- }
+ // Restore the default settings and clear the screen.
+ Console.ForegroundColor = dftForeColor;
+ Console.BackgroundColor = dftBackColor;
+ Console.Clear();
+ } while (continueFlag);
+ }
- private static char GetKeyPress(string msg, char[] validChars)
- {
- ConsoleKeyInfo keyPressed;
- bool valid = false;
+ private static Char GetKeyPress(String msg, Char[] validChars)
+ {
+ ConsoleKeyInfo keyPressed;
+ bool valid = false;
- Console.WriteLine();
- do
- {
- Console.Write(msg);
- keyPressed = Console.ReadKey();
- Console.WriteLine();
- if (Array.Exists(validChars, ch => ch.Equals(char.ToUpper(keyPressed.KeyChar))))
- valid = true;
- } while (!valid);
- return keyPressed.KeyChar;
- }
+ Console.WriteLine();
+ do {
+ Console.Write(msg);
+ keyPressed = Console.ReadKey();
+ Console.WriteLine();
+ if (Array.Exists(validChars, ch => ch.Equals(Char.ToUpper(keyPressed.KeyChar))))
+ valid = true;
+ } while (!valid);
+ return keyPressed.KeyChar;
+ }
}
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/Clear/lts.cs b/snippets/csharp/System/Console/Clear/lts.cs
index 3904927aa78..a9d328bf97c 100644
--- a/snippets/csharp/System/Console/Clear/lts.cs
+++ b/snippets/csharp/System/Console/Clear/lts.cs
@@ -13,51 +13,51 @@ class Sample
protected static void WriteAt(string s, int x, int y)
{
- try
+ try
{
- Console.SetCursorPosition(origCol + x, origRow + y);
- Console.Write(s);
+ Console.SetCursorPosition(origCol+x, origRow+y);
+ Console.Write(s);
}
- catch (ArgumentOutOfRangeException e)
+ catch (ArgumentOutOfRangeException e)
{
- Console.Clear();
- Console.WriteLine(e.Message);
+ Console.Clear();
+ Console.WriteLine(e.Message);
}
}
public static void Main()
{
- // Clear the screen, then save the top and left coordinates.
- Console.Clear();
- origRow = Console.CursorTop;
- origCol = Console.CursorLeft;
+// Clear the screen, then save the top and left coordinates.
+ Console.Clear();
+ origRow = Console.CursorTop;
+ origCol = Console.CursorLeft;
- // Draw the left side of a 5x5 rectangle, from top to bottom.
- WriteAt("+", 0, 0);
- WriteAt("|", 0, 1);
- WriteAt("|", 0, 2);
- WriteAt("|", 0, 3);
- WriteAt("+", 0, 4);
+// Draw the left side of a 5x5 rectangle, from top to bottom.
+ WriteAt("+", 0, 0);
+ WriteAt("|", 0, 1);
+ WriteAt("|", 0, 2);
+ WriteAt("|", 0, 3);
+ WriteAt("+", 0, 4);
- // Draw the bottom side, from left to right.
- WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4)
- WriteAt("-", 2, 4); // ...
- WriteAt("-", 3, 4); // ...
- WriteAt("+", 4, 4);
+// Draw the bottom side, from left to right.
+ WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4)
+ WriteAt("-", 2, 4); // ...
+ WriteAt("-", 3, 4); // ...
+ WriteAt("+", 4, 4);
- // Draw the right side, from bottom to top.
- WriteAt("|", 4, 3);
- WriteAt("|", 4, 2);
- WriteAt("|", 4, 1);
- WriteAt("+", 4, 0);
+// Draw the right side, from bottom to top.
+ WriteAt("|", 4, 3);
+ WriteAt("|", 4, 2);
+ WriteAt("|", 4, 1);
+ WriteAt("+", 4, 0);
- // Draw the top side, from right to left.
- WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0)
- WriteAt("-", 2, 0); // ...
- WriteAt("-", 1, 0); // ...
- //
- WriteAt("All done!", 0, 6);
- Console.WriteLine();
+// Draw the top side, from right to left.
+ WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0)
+ WriteAt("-", 2, 0); // ...
+ WriteAt("-", 1, 0); // ...
+//
+ WriteAt("All done!", 0, 6);
+ Console.WriteLine();
}
}
/*
@@ -72,4 +72,4 @@ public static void Main()
All done!
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/CursorSize/csize.cs b/snippets/csharp/System/Console/CursorSize/csize.cs
index 174e821eb48..e50801352ea 100644
--- a/snippets/csharp/System/Console/CursorSize/csize.cs
+++ b/snippets/csharp/System/Console/CursorSize/csize.cs
@@ -6,20 +6,20 @@ class Sample
{
public static void Main()
{
- string m0 = "This example increments the cursor size from 1% to 100%:\n";
- string m1 = "Cursor size = {0}%. (Press any key to continue...)";
- int[] sizes = { 1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
- int saveCursorSize;
- //
- saveCursorSize = Console.CursorSize;
- Console.WriteLine(m0);
- foreach (int size in sizes)
+ string m0 = "This example increments the cursor size from 1% to 100%:\n";
+ string m1 = "Cursor size = {0}%. (Press any key to continue...)";
+ int[] sizes = {1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
+ int saveCursorSize;
+//
+ saveCursorSize = Console.CursorSize;
+ Console.WriteLine(m0);
+ foreach (int size in sizes)
{
- Console.CursorSize = size;
- Console.WriteLine(m1, size);
- Console.ReadKey();
+ Console.CursorSize = size;
+ Console.WriteLine(m1, size);
+ Console.ReadKey();
}
- Console.CursorSize = saveCursorSize;
+ Console.CursorSize = saveCursorSize;
}
}
/*
@@ -40,4 +40,4 @@ public static void Main()
Cursor size = 100%. (Press any key to continue...)
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/CursorVisible/vis.cs b/snippets/csharp/System/Console/CursorVisible/vis.cs
index 8544ba7ab39..a03617a4af4 100644
--- a/snippets/csharp/System/Console/CursorVisible/vis.cs
+++ b/snippets/csharp/System/Console/CursorVisible/vis.cs
@@ -7,35 +7,35 @@ class Sample
{
public static void Main()
{
- string m1 = "\nThe cursor is {0}.\nType any text then press Enter. " +
- "Type '+' in the first column to show \n" +
- "the cursor, '-' to hide the cursor, " +
- "or lowercase 'x' to quit:";
- string s;
- bool saveCursorVisibile;
- int saveCursorSize;
- //
- Console.CursorVisible = true; // Initialize the cursor to visible.
- saveCursorVisibile = Console.CursorVisible;
- saveCursorSize = Console.CursorSize;
- Console.CursorSize = 100; // Emphasize the cursor.
+ string m1 = "\nThe cursor is {0}.\nType any text then press Enter. " +
+ "Type '+' in the first column to show \n" +
+ "the cursor, '-' to hide the cursor, " +
+ "or lowercase 'x' to quit:";
+ string s;
+ bool saveCursorVisibile;
+ int saveCursorSize;
+//
+ Console.CursorVisible = true; // Initialize the cursor to visible.
+ saveCursorVisibile = Console.CursorVisible;
+ saveCursorSize = Console.CursorSize;
+ Console.CursorSize = 100; // Emphasize the cursor.
- while (true)
+ while(true)
{
- Console.WriteLine(m1,
- ((Console.CursorVisible == true) ?
- "VISIBLE" : "HIDDEN"));
- s = Console.ReadLine();
- if (!string.IsNullOrEmpty(s))
- if (s[0] == '+')
- Console.CursorVisible = true;
- else if (s[0] == '-')
- Console.CursorVisible = false;
- else if (s[0] == 'x')
- break;
+ Console.WriteLine(m1,
+ ((Console.CursorVisible == true) ?
+ "VISIBLE" : "HIDDEN"));
+ s = Console.ReadLine();
+ if (!String.IsNullOrEmpty(s))
+ if (s[0] == '+')
+ Console.CursorVisible = true;
+ else if (s[0] == '-')
+ Console.CursorVisible = false;
+ else if (s[0] == 'x')
+ break;
}
- Console.CursorVisible = saveCursorVisibile;
- Console.CursorSize = saveCursorSize;
+ Console.CursorVisible = saveCursorVisibile;
+ Console.CursorSize = saveCursorSize;
}
}
/*
@@ -74,4 +74,4 @@ Type any text then press Enter. Type '+' in the first column to show
x
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/Error/error1.cs b/snippets/csharp/System/Console/Error/error1.cs
index 22658588652..3af1a8fb07c 100644
--- a/snippets/csharp/System/Console/Error/error1.cs
+++ b/snippets/csharp/System/Console/Error/error1.cs
@@ -3,37 +3,38 @@
public class Example
{
- public static void Main()
- {
- int increment = 0;
- bool exitFlag = false;
+ public static void Main()
+ {
+ int increment = 0;
+ bool exitFlag = false;
- while (!exitFlag)
- {
- if (Console.IsOutputRedirected)
- Console.Error.WriteLine($"Generating multiples of numbers from {increment + 1} to {increment + 10}");
+ while (!exitFlag) {
+ if (Console.IsOutputRedirected)
+ Console.Error.WriteLine("Generating multiples of numbers from {0} to {1}",
+ increment + 1, increment + 10);
- Console.WriteLine($"Generating multiples of numbers from {increment + 1} to {increment + 10}");
- for (int ctr = increment + 1; ctr <= increment + 10; ctr++)
- {
- Console.Write($"Multiples of {ctr}: ");
- for (int ctr2 = 1; ctr2 <= 10; ctr2++)
- Console.Write($"{ctr * ctr2}{(ctr2 == 10 ? "" : ", ")}");
+ Console.WriteLine("Generating multiples of numbers from {0} to {1}",
+ increment + 1, increment + 10);
+ for (int ctr = increment + 1; ctr <= increment + 10; ctr++) {
+ Console.Write("Multiples of {0}: ", ctr);
+ for (int ctr2 = 1; ctr2 <= 10; ctr2++)
+ Console.Write("{0}{1}", ctr * ctr2, ctr2 == 10 ? "" : ", ");
- Console.WriteLine();
- }
Console.WriteLine();
+ }
+ Console.WriteLine();
- increment += 10;
- Console.Error.Write($"Display multiples of {increment + 1} through {increment + 10} (y/n)? ");
- char response = Console.ReadKey(true).KeyChar;
- Console.Error.WriteLine(response);
- if (!Console.IsOutputRedirected)
- Console.CursorTop--;
+ increment += 10;
+ Console.Error.Write("Display multiples of {0} through {1} (y/n)? ",
+ increment + 1, increment + 10);
+ Char response = Console.ReadKey(true).KeyChar;
+ Console.Error.WriteLine(response);
+ if (!Console.IsOutputRedirected)
+ Console.CursorTop--;
- if (char.ToUpperInvariant(response) == 'N')
- exitFlag = true;
- }
- }
+ if (Char.ToUpperInvariant(response) == 'N')
+ exitFlag = true;
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Console/Error/expandtabsex.cs b/snippets/csharp/System/Console/Error/expandtabsex.cs
index e9814f8750b..2240a3abe6c 100644
--- a/snippets/csharp/System/Console/Error/expandtabsex.cs
+++ b/snippets/csharp/System/Console/Error/expandtabsex.cs
@@ -23,28 +23,24 @@ public static void Main(string[] args)
{
StreamWriter writer = null;
- if (args.Length < 2)
- {
+ if (args.Length < 2) {
Console.WriteLine(usageText);
return;
}
- try
- {
- writer = new(args[1]);
+ try {
+ writer = new StreamWriter(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
- catch (IOException e)
- {
+ catch(IOException e) {
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return;
}
int i;
- while ((i = Console.Read()) != -1)
- {
+ while ((i = Console.Read()) != -1) {
char c = (char)i;
if (c == '\t')
Console.Write(("").PadRight(tabSize, ' '));
@@ -54,12 +50,10 @@ public static void Main(string[] args)
writer.Close();
// Recover the standard output stream so that a
// completion message can be displayed.
- StreamWriter standardOutput = new(Console.OpenStandardOutput())
- {
- AutoFlush = true
- };
+ StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
+ standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
- Console.WriteLine($"EXPANDTABSEX has completed the processing of {args[0]}.");
+ Console.WriteLine("EXPANDTABSEX has completed the processing of {0}.", args[0]);
return;
}
}
diff --git a/snippets/csharp/System/Console/Error/viewtextfile.cs b/snippets/csharp/System/Console/Error/viewtextfile.cs
index 58a4b563bf0..93190fc9bb6 100644
--- a/snippets/csharp/System/Console/Error/viewtextfile.cs
+++ b/snippets/csharp/System/Console/Error/viewtextfile.cs
@@ -4,46 +4,44 @@
public class ViewTextFile
{
- public static void Main()
- {
- string[] args = Environment.GetCommandLineArgs();
- string errorOutput = "";
- // Make sure that there is at least one command line argument.
- if (args.Length <= 1)
- errorOutput += "You must include a filename on the command line.\n";
+ public static void Main()
+ {
+ String[] args = Environment.GetCommandLineArgs();
+ String errorOutput = "";
+ // Make sure that there is at least one command line argument.
+ if (args.Length <= 1)
+ errorOutput += "You must include a filename on the command line.\n";
- for (int ctr = 1; ctr <= args.GetUpperBound(0); ctr++)
- {
- // Check whether the file exists.
- if (!File.Exists(args[ctr]))
- {
- errorOutput += $"'{args[ctr]}' does not exist.\n";
- }
- else
- {
- // Display the contents of the file.
- StreamReader sr = new(args[ctr]);
- string contents = sr.ReadToEnd();
- sr.Close();
- Console.WriteLine($"*****Contents of file '{args[ctr]}':\n\n");
- Console.WriteLine(contents);
- Console.WriteLine("*****\n");
- }
- }
+ for (int ctr = 1; ctr <= args.GetUpperBound(0); ctr++) {
+ // Check whether the file exists.
+ if (!File.Exists(args[ctr])) {
+ errorOutput += String.Format("'{0}' does not exist.\n", args[ctr]);
+ }
+ else {
+ // Display the contents of the file.
+ StreamReader sr = new StreamReader(args[ctr]);
+ String contents = sr.ReadToEnd();
+ sr.Close();
+ Console.WriteLine("*****Contents of file '{0}':\n\n",
+ args[ctr]);
+ Console.WriteLine(contents);
+ Console.WriteLine("*****\n");
+ }
+ }
- // Check for error conditions.
- if (!string.IsNullOrEmpty(errorOutput))
- {
- // Write error information to a file.
- Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"));
- Console.Error.WriteLine(errorOutput);
- Console.Error.Close();
- // Reacquire the standard error stream.
- var standardError = new StreamWriter(Console.OpenStandardError()) { AutoFlush = true };
- Console.SetError(standardError);
- Console.Error.WriteLine("\nError information written to ViewTextFile.Err.txt");
- }
- }
+ // Check for error conditions.
+ if (!String.IsNullOrEmpty(errorOutput)) {
+ // Write error information to a file.
+ Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"));
+ Console.Error.WriteLine(errorOutput);
+ Console.Error.Close();
+ // Reacquire the standard error stream.
+ var standardError = new StreamWriter(Console.OpenStandardError());
+ standardError.AutoFlush = true;
+ Console.SetError(standardError);
+ Console.Error.WriteLine("\nError information written to ViewTextFile.Err.txt");
+ }
+ }
}
// If the example is compiled and run with the following command line:
// ViewTextFile file1.txt file2.txt
diff --git a/snippets/csharp/System/Console/In/consolein.cs b/snippets/csharp/System/Console/In/consolein.cs
index 4bc9809bf19..7306524513b 100644
--- a/snippets/csharp/System/Console/In/consolein.cs
+++ b/snippets/csharp/System/Console/In/consolein.cs
@@ -2,19 +2,17 @@
using System;
using System.IO;
-class InTest
-{
- public static void Main()
- {
+class InTest {
+ public static void Main() {
TextReader tIn = Console.In;
TextWriter tOut = Console.Out;
tOut.WriteLine("Hola Mundo!");
tOut.Write("What is your name: ");
- string name = tIn.ReadLine();
+ String name = tIn.ReadLine();
- tOut.WriteLine($"Buenos Dias, {name}!");
+ tOut.WriteLine("Buenos Dias, {0}!", name);
}
}
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/KeyAvailable/ka.cs b/snippets/csharp/System/Console/KeyAvailable/ka.cs
index a5414177168..141d556c5fa 100644
--- a/snippets/csharp/System/Console/KeyAvailable/ka.cs
+++ b/snippets/csharp/System/Console/KeyAvailable/ka.cs
@@ -6,21 +6,20 @@ class Sample
{
public static void Main()
{
- ConsoleKeyInfo cki;
+ ConsoleKeyInfo cki;
- do
- {
- Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
+ do {
+ Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
- // Your code could perform some useful task in the following loop. However,
- // for the sake of this example we'll merely pause for a quarter second.
+ // Your code could perform some useful task in the following loop. However,
+ // for the sake of this example we'll merely pause for a quarter second.
- while (!Console.KeyAvailable)
- Thread.Sleep(250); // Loop until input is entered.
+ while (!Console.KeyAvailable)
+ Thread.Sleep(250); // Loop until input is entered.
- cki = Console.ReadKey(true);
- Console.WriteLine($"You pressed the '{cki.Key}' key.");
- } while (cki.Key != ConsoleKey.X);
+ cki = Console.ReadKey(true);
+ Console.WriteLine("You pressed the '{0}' key.", cki.Key);
+ } while(cki.Key != ConsoleKey.X);
}
}
/*
@@ -41,4 +40,4 @@ You pressed the 'DownArrow' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'X' key.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/OpenStandardInput/decode.cs b/snippets/csharp/System/Console/OpenStandardInput/decode.cs
index 9c7bbe996d2..16ea92ccf82 100644
--- a/snippets/csharp/System/Console/OpenStandardInput/decode.cs
+++ b/snippets/csharp/System/Console/OpenStandardInput/decode.cs
@@ -4,10 +4,8 @@
using System.Text;
using System.IO;
-public class Decoder
-{
- public static void Main()
- {
+public class Decoder {
+ public static void Main() {
Stream inputStream = Console.OpenStandardInput();
byte[] bytes = new byte[100];
Console.WriteLine("To decode, type or paste the UTF7 encoded string and press enter:");
diff --git a/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs b/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
index 9709d09b277..8f1bbf07e64 100644
--- a/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
+++ b/snippets/csharp/System/Console/OpenStandardOutput/inserttabs.cs
@@ -1,4 +1,4 @@
-// This sample opens a file whose name is passed to it as a parameter.
+// This sample opens a file whose name is passed to it as a parameter.
// It reads each line in the file and replaces every occurrence of 4
// space characters with a tab character.
//
@@ -45,7 +45,7 @@ public static int Main(string[] args)
}
}
}
- catch (IOException e)
+ catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
@@ -55,7 +55,8 @@ public static int Main(string[] args)
// Recover the standard output stream so that a
// completion message can be displayed.
- var standardOutput = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
+ var standardOutput = new StreamWriter(Console.OpenStandardOutput());
+ standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine($"INSERTTABS has completed the processing of {args[0]}.");
return 0;
diff --git a/snippets/csharp/System/Console/Out/out1.cs b/snippets/csharp/System/Console/Out/out1.cs
index 7a5669224e8..aba012bc641 100644
--- a/snippets/csharp/System/Console/Out/out1.cs
+++ b/snippets/csharp/System/Console/Out/out1.cs
@@ -4,36 +4,34 @@
public class Example
{
- public static void Main()
- {
- // Get all files in the current directory.
- string[] files = Directory.GetFiles(".");
- Array.Sort(files);
+ public static void Main()
+ {
+ // Get all files in the current directory.
+ string[] files = Directory.GetFiles(".");
+ Array.Sort(files);
- // Display the files to the current output source to the console.
- Console.Out.WriteLine("First display of filenames to the console:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- Console.Out.WriteLine();
+ // Display the files to the current output source to the console.
+ Console.Out.WriteLine("First display of filenames to the console:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ Console.Out.WriteLine();
- // Redirect output to a file named Files.txt and write file list.
- StreamWriter sw = new(@".\Files.txt")
- {
- AutoFlush = true
- };
- Console.SetOut(sw);
- Console.Out.WriteLine("Display filenames to a file:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- Console.Out.WriteLine();
+ // Redirect output to a file named Files.txt and write file list.
+ StreamWriter sw = new StreamWriter(@".\Files.txt");
+ sw.AutoFlush = true;
+ Console.SetOut(sw);
+ Console.Out.WriteLine("Display filenames to a file:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ Console.Out.WriteLine();
- // Close previous output stream and redirect output to standard output.
- Console.Out.Close();
- sw = new(Console.OpenStandardOutput());
- sw.AutoFlush = true;
- Console.SetOut(sw);
+ // Close previous output stream and redirect output to standard output.
+ Console.Out.Close();
+ sw = new StreamWriter(Console.OpenStandardOutput());
+ sw.AutoFlush = true;
+ Console.SetOut(sw);
- // Display the files to the current output source to the console.
- Console.Out.WriteLine("Second display of filenames to the console:");
- Array.ForEach(files, s => Console.Out.WriteLine(s));
- }
+ // Display the files to the current output source to the console.
+ Console.Out.WriteLine("Second display of filenames to the console:");
+ Array.ForEach(files, s => Console.Out.WriteLine(s));
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/example3.cs b/snippets/csharp/System/Console/Overview/example3.cs
index 970e6164f79..05e7487ae35 100644
--- a/snippets/csharp/System/Console/Overview/example3.cs
+++ b/snippets/csharp/System/Console/Overview/example3.cs
@@ -7,158 +7,159 @@
public static class DisplayChars
{
- private static void Main(string[] args)
- {
- uint rangeStart = 0;
- uint rangeEnd = 0;
- bool setOutputEncodingToUnicode = true;
- // Get the current encoding so we can restore it.
- Encoding originalOutputEncoding = Console.OutputEncoding;
-
- try
- {
- switch (args.Length)
- {
- case 2:
- rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
- rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
- setOutputEncodingToUnicode = true;
- break;
- case 3:
- if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
- throw new ArgumentException($"{args[0]} is not a valid hexadecimal number.");
-
- if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
- throw new ArgumentException($"{args[1]} is not a valid hexadecimal number.");
-
- bool.TryParse(args[2], out setOutputEncodingToUnicode);
- break;
- default:
- Console.WriteLine($"Usage: {Environment.GetCommandLineArgs()[0]} <{"startingCodePointInHex"}> <{"endingCodePointInHex"}> [{""}]");
- return;
+ private static void Main(string[] args)
+ {
+ uint rangeStart = 0;
+ uint rangeEnd = 0;
+ bool setOutputEncodingToUnicode = true;
+ // Get the current encoding so we can restore it.
+ Encoding originalOutputEncoding = Console.OutputEncoding;
+
+ try
+ {
+ switch(args.Length)
+ {
+ case 2:
+ rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
+ rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
+ setOutputEncodingToUnicode = true;
+ break;
+ case 3:
+ if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
+ throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0]));
+
+ if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
+ throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1]));
+
+ bool.TryParse(args[2], out setOutputEncodingToUnicode);
+ break;
+ default:
+ Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]",
+ Environment.GetCommandLineArgs()[0],
+ "startingCodePointInHex",
+ "endingCodePointInHex",
+ "");
+ return;
+ }
+
+ if (setOutputEncodingToUnicode)
+ {
+ try {
+ // Set encoding using endianness of this system.
+ // We're interested in displaying individual Char objects, so
+ // we don't want a Unicode BOM or exceptions to be thrown on
+ // invalid Char values.
+ Console.OutputEncoding = new UnicodeEncoding(! BitConverter.IsLittleEndian, false);
+ Console.WriteLine("\nOutput encoding set to UTF-16");
}
-
- if (setOutputEncodingToUnicode)
- {
- try
- {
- // Set encoding using endianness of this system.
- // We're interested in displaying individual Char objects, so
- // we don't want a Unicode BOM or exceptions to be thrown on
- // invalid Char values.
- Console.OutputEncoding = new UnicodeEncoding(!BitConverter.IsLittleEndian, false);
- Console.WriteLine("\nOutput encoding set to UTF-16");
- }
- catch (IOException)
- {
- Console.OutputEncoding = new UTF8Encoding();
- Console.WriteLine("Output encoding set to UTF-8");
- }
+ catch (IOException) {
+ Console.OutputEncoding = new UTF8Encoding();
+ Console.WriteLine("Output encoding set to UTF-8");
}
- else
- {
- Console.WriteLine($"The console encoding is {Console.OutputEncoding.EncodingName} (code page {Console.OutputEncoding.CodePage})");
+ }
+ else {
+ Console.WriteLine("The console encoding is {0} (code page {1})",
+ Console.OutputEncoding.EncodingName,
+ Console.OutputEncoding.CodePage);
+ }
+ DisplayRange(rangeStart, rangeEnd);
+ }
+ catch (ArgumentException ex) {
+ Console.WriteLine(ex.Message);
+ }
+ finally {
+ // Restore console environment.
+ Console.OutputEncoding = originalOutputEncoding;
+ }
+ }
+
+ public static void DisplayRange(uint start, uint end)
+ {
+ const uint upperRange = 0x10FFFF;
+ const uint surrogateStart = 0xD800;
+ const uint surrogateEnd = 0xDFFF;
+
+ if (end <= start) {
+ uint t = start;
+ start = end;
+ end = t;
+ }
+
+ // Check whether the start or end range is outside of last plane.
+ if (start > upperRange)
+ throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
+ start, upperRange));
+ if (end > upperRange)
+ throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
+ end, upperRange));
+
+ // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
+ if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd ))
+ throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}",
+ start, end, surrogateStart, surrogateEnd));
+ uint last = RoundUpToMultipleOf(0x10, end);
+ uint first = RoundDownToMultipleOf(0x10, start);
+
+ uint rows = (last - first) / 0x10;
+
+ for (uint r = 0; r < rows; ++r) {
+ // Display the row header.
+ Console.Write("{0:x5} ", first + 0x10 * r);
+
+ for (uint c = 0; c < 0x10; ++c) {
+ uint cur = (first + 0x10 * r + c);
+ if (cur < start) {
+ Console.Write($" {(char)(0x20)} ");
}
- DisplayRange(rangeStart, rangeEnd);
- }
- catch (ArgumentException ex)
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- // Restore console environment.
- Console.OutputEncoding = originalOutputEncoding;
- }
- }
-
- public static void DisplayRange(uint start, uint end)
- {
- const uint upperRange = 0x10FFFF;
- const uint surrogateStart = 0xD800;
- const uint surrogateEnd = 0xDFFF;
-
- if (end <= start)
- {
- uint t = start;
- start = end;
- end = t;
- }
-
- // Check whether the start or end range is outside of last plane.
- if (start > upperRange)
- throw new ArgumentException($"0x{start:X5} is outside the upper range of Unicode code points (0x{upperRange:X5})");
- if (end > upperRange)
- throw new ArgumentException(string.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
- end, upperRange));
-
- // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF.
- if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd))
- throw new ArgumentException($"0x{start:X5}-0x{end:X5} includes the surrogate pair range 0x{surrogateStart:X5}-0x{surrogateEnd:X5}");
- uint last = RoundUpToMultipleOf(0x10, end);
- uint first = RoundDownToMultipleOf(0x10, start);
-
- uint rows = (last - first) / 0x10;
-
- for (uint r = 0; r < rows; ++r)
- {
- // Display the row header.
- Console.Write($"{first + 0x10 * r:x5} ");
-
- for (uint c = 0; c < 0x10; ++c)
- {
- uint cur = (first + 0x10 * r + c);
- if (cur < start)
- {
- Console.Write($" {(char)(0x20)} ");
- }
- else if (end < cur)
- {
- Console.Write($" {(char)(0x20)} ");
- }
- else
- {
- // the cast to int is safe, since we know that val <= upperRange.
- string chars = char.ConvertFromUtf32((int)cur);
- // Display a space for code points that are not valid characters.
- if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
- UnicodeCategory.OtherNotAssigned)
- Console.Write($" {(char)(0x20)} ");
- // Display a space for code points in the private use area.
- else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
- UnicodeCategory.PrivateUse)
- Console.Write($" {(char)(0x20)} ");
- // Is surrogate pair a valid character?
- // Note that the console will interpret the high and low surrogate
- // as separate (and unrecognizable) characters.
- else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
- UnicodeCategory.OtherNotAssigned)
- Console.Write($" {(char)(0x20)} ");
- else
- Console.Write($" {chars} ");
- }
-
- switch (c)
- {
- case 3:
- case 11:
- Console.Write("-");
- break;
- case 7:
- Console.Write("--");
- break;
- }
+ else if (end < cur) {
+ Console.Write($" {(char)(0x20)} ");
+ }
+ else {
+ // the cast to int is safe, since we know that val <= upperRange.
+ String chars = Char.ConvertFromUtf32( (int) cur);
+ // Display a space for code points that are not valid characters.
+ if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
+ UnicodeCategory.OtherNotAssigned)
+ Console.Write($" {(char)(0x20)} ");
+ // Display a space for code points in the private use area.
+ else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
+ UnicodeCategory.PrivateUse)
+ Console.Write($" {(char)(0x20)} ");
+ // Is surrogate pair a valid character?
+ // Note that the console will interpret the high and low surrogate
+ // as separate (and unrecognizable) characters.
+ else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
+ UnicodeCategory.OtherNotAssigned)
+ Console.Write($" {(char)(0x20)} ");
+ else
+ Console.Write($" {chars} ");
}
- Console.WriteLine();
- if (0 < r && r % 0x10 == 0)
- Console.WriteLine();
- }
- }
-
- private static uint RoundUpToMultipleOf(uint b, uint u) => RoundDownToMultipleOf(b, u) + b;
+ switch (c) {
+ case 3: case 11:
+ Console.Write("-");
+ break;
+ case 7:
+ Console.Write("--");
+ break;
+ }
+ }
- private static uint RoundDownToMultipleOf(uint b, uint u) => u - (u % b);
+ Console.WriteLine();
+ if (0 < r && r % 0x10 == 0)
+ Console.WriteLine();
+ }
+ }
+
+ private static uint RoundUpToMultipleOf(uint b, uint u)
+ {
+ return RoundDownToMultipleOf(b, u) + b;
+ }
+
+ private static uint RoundDownToMultipleOf(uint b, uint u)
+ {
+ return u - (u % b);
+ }
}
// If the example is run with the command line
// DisplayChars 0400 04FF true
diff --git a/snippets/csharp/System/Console/Overview/fontlink1.cs b/snippets/csharp/System/Console/Overview/fontlink1.cs
index 105a481cb5b..46a9fb5d6e3 100644
--- a/snippets/csharp/System/Console/Overview/fontlink1.cs
+++ b/snippets/csharp/System/Console/Overview/fontlink1.cs
@@ -4,79 +4,71 @@
public class Example
{
- public static void Main()
- {
- string valueName = "Lucida Console";
- string newFont = "simsun.ttc,SimSun";
- string[] fonts = null;
- RegistryValueKind kind = 0;
- bool toAdd;
+ public static void Main()
+ {
+ string valueName = "Lucida Console";
+ string newFont = "simsun.ttc,SimSun";
+ string[] fonts = null;
+ RegistryValueKind kind = 0;
+ bool toAdd;
- RegistryKey key = Registry.LocalMachine.OpenSubKey(
- @"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink",
- true);
- if (key == null)
- {
- Console.WriteLine("Font linking is not enabled.");
- }
- else
- {
- // Determine if the font is a base font.
- string[] names = key.GetValueNames();
- if (Array.Exists(names, s => s.Equals(valueName,
- StringComparison.OrdinalIgnoreCase)))
- {
- // Get the value's type.
- kind = key.GetValueKind(valueName);
+ RegistryKey key = Registry.LocalMachine.OpenSubKey(
+ @"Software\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink",
+ true);
+ if (key == null) {
+ Console.WriteLine("Font linking is not enabled.");
+ }
+ else {
+ // Determine if the font is a base font.
+ string[] names = key.GetValueNames();
+ if (Array.Exists(names, s => s.Equals(valueName,
+ StringComparison.OrdinalIgnoreCase))) {
+ // Get the value's type.
+ kind = key.GetValueKind(valueName);
- // Type should be RegistryValueKind.MultiString, but we can't be sure.
- switch (kind)
- {
- case RegistryValueKind.String:
- fonts = new string[] { (string)key.GetValue(valueName) };
- break;
- case RegistryValueKind.MultiString:
- fonts = (string[])key.GetValue(valueName);
- break;
- case RegistryValueKind.None:
- // Do nothing.
- fonts = new string[] { };
- break;
- }
- // Determine whether SimSun is a linked font.
- if (Array.FindIndex(fonts, s => s.IndexOf("SimSun",
- StringComparison.OrdinalIgnoreCase) >= 0) >= 0)
- {
- Console.WriteLine("Font is already linked.");
- toAdd = false;
- }
- else
- {
- // Font is not a linked font.
- toAdd = true;
- }
+ // Type should be RegistryValueKind.MultiString, but we can't be sure.
+ switch (kind) {
+ case RegistryValueKind.String:
+ fonts = new string[] { (string) key.GetValue(valueName) };
+ break;
+ case RegistryValueKind.MultiString:
+ fonts = (string[]) key.GetValue(valueName);
+ break;
+ case RegistryValueKind.None:
+ // Do nothing.
+ fonts = new string[] { };
+ break;
}
- else
- {
- // Font is not a base font.
- toAdd = true;
- fonts = new string[] { };
+ // Determine whether SimSun is a linked font.
+ if (Array.FindIndex(fonts, s =>s.IndexOf("SimSun",
+ StringComparison.OrdinalIgnoreCase) >=0) >= 0) {
+ Console.WriteLine("Font is already linked.");
+ toAdd = false;
}
+ else {
+ // Font is not a linked font.
+ toAdd = true;
+ }
+ }
+ else {
+ // Font is not a base font.
+ toAdd = true;
+ fonts = new string[] { };
+ }
- if (toAdd)
- {
- Array.Resize(ref fonts, fonts.Length + 1);
- fonts[fonts.GetUpperBound(0)] = newFont;
- // Change REG_SZ to REG_MULTI_SZ.
- if (kind == RegistryValueKind.String)
- key.DeleteValue(valueName, false);
+ if (toAdd) {
+ Array.Resize(ref fonts, fonts.Length + 1);
+ fonts[fonts.GetUpperBound(0)] = newFont;
+ // Change REG_SZ to REG_MULTI_SZ.
+ if (kind == RegistryValueKind.String)
+ key.DeleteValue(valueName, false);
- key.SetValue(valueName, fonts, RegistryValueKind.MultiString);
- Console.WriteLine("SimSun added to the list of linked fonts.");
- }
- }
+ key.SetValue(valueName, fonts, RegistryValueKind.MultiString);
+ Console.WriteLine("SimSun added to the list of linked fonts.");
+ }
+ }
- if (key != null) key.Close();
- }
+ if (key != null) key.Close();
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/normalize1.cs b/snippets/csharp/System/Console/Overview/normalize1.cs
index afa95e9f15c..3babe347a87 100644
--- a/snippets/csharp/System/Console/Overview/normalize1.cs
+++ b/snippets/csharp/System/Console/Overview/normalize1.cs
@@ -1,19 +1,19 @@
//
using System;
-
+using System.IO;
public class Example
{
- public static void Main()
- {
- char[] chars = { '\u0061', '\u0308' };
+ public static void Main()
+ {
+ char[] chars = { '\u0061', '\u0308' };
- string combining = new(chars);
- Console.WriteLine(combining);
+ string combining = new String(chars);
+ Console.WriteLine(combining);
- combining = combining.Normalize();
- Console.WriteLine(combining);
- }
+ combining = combining.Normalize();
+ Console.WriteLine(combining);
+ }
}
// The example displays the following output:
// a"
diff --git a/snippets/csharp/System/Console/Overview/setfont1.cs b/snippets/csharp/System/Console/Overview/setfont1.cs
index 8a51d11b9b3..c237d2aa5cf 100644
--- a/snippets/csharp/System/Console/Overview/setfont1.cs
+++ b/snippets/csharp/System/Console/Overview/setfont1.cs
@@ -4,80 +4,77 @@
public class Example
{
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern IntPtr GetStdHandle(int nStdHandle);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern IntPtr GetStdHandle(int nStdHandle);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- static extern bool GetCurrentConsoleFontEx(
- IntPtr consoleOutput,
- bool maximumWindow,
- ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ static extern bool GetCurrentConsoleFontEx(
+ IntPtr consoleOutput,
+ bool maximumWindow,
+ ref CONSOLE_FONT_INFO_EX lpConsoleCurrentFontEx);
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern bool SetCurrentConsoleFontEx(
- IntPtr consoleOutput,
- bool maximumWindow,
- CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern bool SetCurrentConsoleFontEx(
+ IntPtr consoleOutput,
+ bool maximumWindow,
+ CONSOLE_FONT_INFO_EX consoleCurrentFontEx);
- private const int STD_OUTPUT_HANDLE = -11;
- private const int TMPF_TRUETYPE = 4;
- private const int LF_FACESIZE = 32;
- private static IntPtr INVALID_HANDLE_VALUE = new(-1);
+ private const int STD_OUTPUT_HANDLE = -11;
+ private const int TMPF_TRUETYPE = 4;
+ private const int LF_FACESIZE = 32;
+ private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
- public static unsafe void Main()
- {
- string fontName = "Lucida Console";
- IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
- if (hnd != INVALID_HANDLE_VALUE)
- {
- CONSOLE_FONT_INFO_EX info = new();
- info.cbSize = (uint)Marshal.SizeOf(info);
- bool tt = false;
- // First determine whether there's already a TrueType font.
- if (GetCurrentConsoleFontEx(hnd, false, ref info))
- {
- tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
- if (tt)
- {
- Console.WriteLine("The console already is using a TrueType font.");
- return;
- }
- // Set console font to Lucida Console.
- CONSOLE_FONT_INFO_EX newInfo = new();
- newInfo.cbSize = (uint)Marshal.SizeOf(newInfo);
- newInfo.FontFamily = TMPF_TRUETYPE;
- IntPtr ptr = new(newInfo.FaceName);
- Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
- // Get some settings from current font.
- newInfo.dwFontSize = new(info.dwFontSize.X, info.dwFontSize.Y);
- newInfo.FontWeight = info.FontWeight;
- SetCurrentConsoleFontEx(hnd, false, newInfo);
+ public static unsafe void Main()
+ {
+ string fontName = "Lucida Console";
+ IntPtr hnd = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (hnd != INVALID_HANDLE_VALUE) {
+ CONSOLE_FONT_INFO_EX info = new CONSOLE_FONT_INFO_EX();
+ info.cbSize = (uint) Marshal.SizeOf(info);
+ bool tt = false;
+ // First determine whether there's already a TrueType font.
+ if (GetCurrentConsoleFontEx(hnd, false, ref info)) {
+ tt = (info.FontFamily & TMPF_TRUETYPE) == TMPF_TRUETYPE;
+ if (tt) {
+ Console.WriteLine("The console already is using a TrueType font.");
+ return;
}
- }
+ // Set console font to Lucida Console.
+ CONSOLE_FONT_INFO_EX newInfo = new CONSOLE_FONT_INFO_EX();
+ newInfo.cbSize = (uint) Marshal.SizeOf(newInfo);
+ newInfo.FontFamily = TMPF_TRUETYPE;
+ IntPtr ptr = new IntPtr(newInfo.FaceName);
+ Marshal.Copy(fontName.ToCharArray(), 0, ptr, fontName.Length);
+ // Get some settings from current font.
+ newInfo.dwFontSize = new COORD(info.dwFontSize.X, info.dwFontSize.Y);
+ newInfo.FontWeight = info.FontWeight;
+ SetCurrentConsoleFontEx(hnd, false, newInfo);
+ }
+ }
}
- [StructLayout(LayoutKind.Sequential)]
- internal struct COORD
- {
- internal short X;
- internal short Y;
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct COORD
+ {
+ internal short X;
+ internal short Y;
- internal COORD(short x, short y)
- {
- X = x;
- Y = y;
- }
- }
+ internal COORD(short x, short y)
+ {
+ X = x;
+ Y = y;
+ }
+ }
- [StructLayout(LayoutKind.Sequential)]
- internal unsafe struct CONSOLE_FONT_INFO_EX
- {
- internal uint cbSize;
- internal uint nFont;
- internal COORD dwFontSize;
- internal int FontFamily;
- internal int FontWeight;
- internal fixed char FaceName[LF_FACESIZE];
- }
+ [StructLayout(LayoutKind.Sequential)]
+ internal unsafe struct CONSOLE_FONT_INFO_EX
+ {
+ internal uint cbSize;
+ internal uint nFont;
+ internal COORD dwFontSize;
+ internal int FontFamily;
+ internal int FontWeight;
+ internal fixed char FaceName[LF_FACESIZE];
+ }
}
//
diff --git a/snippets/csharp/System/Console/Overview/source.cs b/snippets/csharp/System/Console/Overview/source.cs
index 0451dc4b837..b25867ef0df 100644
--- a/snippets/csharp/System/Console/Overview/source.cs
+++ b/snippets/csharp/System/Console/Overview/source.cs
@@ -1,8 +1,7 @@
-//
+//
using System;
-public class Example
-{
+public class Example {
public static void Main()
{
Console.Write("Hello ");
diff --git a/snippets/csharp/System/Console/Overview/unicode1.cs b/snippets/csharp/System/Console/Overview/unicode1.cs
index 8350ab587d2..e36e9a1837e 100644
--- a/snippets/csharp/System/Console/Overview/unicode1.cs
+++ b/snippets/csharp/System/Console/Overview/unicode1.cs
@@ -3,28 +3,27 @@
public class Example
{
- public static void Main()
- {
- // Create a Char array for the modern Cyrillic alphabet,
- // from U+0410 to U+044F.
- int nChars = 0x044F - 0x0410 + 1;
- char[] chars = new char[nChars];
- ushort codePoint = 0x0410;
- for (int ctr = 0; ctr < chars.Length; ctr++)
- {
- chars[ctr] = (char)codePoint;
- codePoint++;
- }
+ public static void Main()
+ {
+ // Create a Char array for the modern Cyrillic alphabet,
+ // from U+0410 to U+044F.
+ int nChars = 0x044F - 0x0410 + 1;
+ char[] chars = new char[nChars];
+ ushort codePoint = 0x0410;
+ for (int ctr = 0; ctr < chars.Length; ctr++) {
+ chars[ctr] = (char)codePoint;
+ codePoint++;
+ }
- Console.WriteLine($"Current code page: {Console.OutputEncoding.CodePage}\n");
- // Display the characters.
- foreach (char ch in chars)
- {
- Console.Write($"{ch} ");
- if (Console.CursorLeft >= 70)
- Console.WriteLine();
- }
- }
+ Console.WriteLine("Current code page: {0}\n",
+ Console.OutputEncoding.CodePage);
+ // Display the characters.
+ foreach (var ch in chars) {
+ Console.Write("{0} ", ch);
+ if (Console.CursorLeft >= 70)
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Current code page: 437
diff --git a/snippets/csharp/System/Console/Read/read.cs b/snippets/csharp/System/Console/Read/read.cs
index 9178e3ded6e..5fdc7751b1c 100644
--- a/snippets/csharp/System/Console/Read/read.cs
+++ b/snippets/csharp/System/Console/Read/read.cs
@@ -6,36 +6,36 @@ class Sample
{
public static void Main()
{
- string m1 = "\nType a string of text then press Enter. " +
- "Type '+' anywhere in the text to quit:\n";
- string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
- string m3 = "Character is hexadecimal 0x{0:x4}.";
- char ch;
- int x;
- //
- Console.WriteLine(m1);
- do
+ string m1 = "\nType a string of text then press Enter. " +
+ "Type '+' anywhere in the text to quit:\n";
+ string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
+ string m3 = "Character is hexadecimal 0x{0:x4}.";
+ char ch;
+ int x;
+//
+ Console.WriteLine(m1);
+ do
{
- x = Console.Read();
- try
+ x = Console.Read();
+ try
{
- ch = Convert.ToChar(x);
- if (char.IsWhiteSpace(ch))
- {
- Console.WriteLine(m3, x);
- if (ch == 0x0a)
- Console.WriteLine(m1);
- }
- else
+ ch = Convert.ToChar(x);
+ if (Char.IsWhiteSpace(ch))
+ {
+ Console.WriteLine(m3, x);
+ if (ch == 0x0a)
+ Console.WriteLine(m1);
+ }
+ else
{
Console.WriteLine(m2, ch, x);
}
}
- catch (OverflowException e)
+ catch (OverflowException e)
{
- Console.WriteLine($"{e.Message} Value read = {x}.");
- ch = char.MinValue;
- Console.WriteLine(m1);
+ Console.WriteLine("{0} Value read = {1}.", e.Message, x);
+ ch = Char.MinValue;
+ Console.WriteLine(m1);
}
} while (ch != '+');
}
@@ -80,4 +80,4 @@ Character is hexadecimal 0x000a.
Character '+' is hexadecimal 0x002b.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/ReadKey/ReadKey1.cs b/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
index 09165916326..263f3da42bd 100644
--- a/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
+++ b/snippets/csharp/System/Console/ReadKey/ReadKey1.cs
@@ -3,16 +3,17 @@
public class Example
{
- public static void Main()
- {
- DateTime dat = DateTime.Now;
- Console.WriteLine("The time: {0:d} at {0:t}", dat);
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Console.WriteLine($"The time zone: {(tz.IsDaylightSavingTime(dat) ?
- tz.DaylightName : tz.StandardName)}\n");
- Console.Write("Press to exit... ");
- while (Console.ReadKey().Key != ConsoleKey.Enter) { }
- }
+ public static void Main()
+ {
+ DateTime dat = DateTime.Now;
+ Console.WriteLine("The time: {0:d} at {0:t}", dat);
+ TimeZoneInfo tz = TimeZoneInfo.Local;
+ Console.WriteLine("The time zone: {0}\n",
+ tz.IsDaylightSavingTime(dat) ?
+ tz.DaylightName : tz.StandardName);
+ Console.Write("Press to exit... ");
+ while (Console.ReadKey().Key != ConsoleKey.Enter) {}
+ }
}
// The example displays output like the following:
// The time: 11/11/2015 at 4:02 PM:
diff --git a/snippets/csharp/System/Console/ReadKey/ReadKey2.cs b/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
index 509d4247b8f..9f8d14b4337 100644
--- a/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
+++ b/snippets/csharp/System/Console/ReadKey/ReadKey2.cs
@@ -3,16 +3,17 @@
public class Example
{
- public static void Main()
- {
- DateTime dat = DateTime.Now;
- Console.WriteLine("The time: {0:d} at {0:t}", dat);
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Console.WriteLine($"The time zone: {(tz.IsDaylightSavingTime(dat) ?
- tz.DaylightName : tz.StandardName)}\n");
- Console.Write("Press to exit... ");
- while (Console.ReadKey(true).Key != ConsoleKey.Enter) { }
- }
+ public static void Main()
+ {
+ DateTime dat = DateTime.Now;
+ Console.WriteLine("The time: {0:d} at {0:t}", dat);
+ TimeZoneInfo tz = TimeZoneInfo.Local;
+ Console.WriteLine("The time zone: {0}\n",
+ tz.IsDaylightSavingTime(dat) ?
+ tz.DaylightName : tz.StandardName);
+ Console.Write("Press to exit... ");
+ while (Console.ReadKey(true).Key != ConsoleKey.Enter) {}
+ }
}
// The example displays output like the following:
// The time: 11/11/2015 at 4:02 PM:
diff --git a/snippets/csharp/System/Console/ReadKey/rk.cs b/snippets/csharp/System/Console/ReadKey/rk.cs
index 66d8e08ceac..85578c6099a 100644
--- a/snippets/csharp/System/Console/ReadKey/rk.cs
+++ b/snippets/csharp/System/Console/ReadKey/rk.cs
@@ -3,23 +3,23 @@
class Example
{
- public static void Main()
- {
- ConsoleKeyInfo cki;
- // Prevent example from ending if CTL+C is pressed.
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ ConsoleKeyInfo cki;
+ // Prevent example from ending if CTL+C is pressed.
+ Console.TreatControlCAsInput = true;
- Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
- Console.WriteLine("Press the Escape (Esc) key to quit: \n");
- do
- {
- cki = Console.ReadKey();
- Console.Write(" --- You pressed ");
- if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
- if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
- if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
- Console.WriteLine(cki.Key.ToString());
- } while (cki.Key != ConsoleKey.Escape);
+ Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
+ Console.WriteLine("Press the Escape (Esc) key to quit: \n");
+ do
+ {
+ cki = Console.ReadKey();
+ Console.Write(" --- You pressed ");
+ if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
+ if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
+ if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
+ Console.WriteLine(cki.Key.ToString());
+ } while (cki.Key != ConsoleKey.Escape);
}
}
// This example displays output similar to the following:
diff --git a/snippets/csharp/System/Console/ReadKey/rkbool.cs b/snippets/csharp/System/Console/ReadKey/rkbool.cs
index b6f655a7d43..8dee6cbb5c8 100644
--- a/snippets/csharp/System/Console/ReadKey/rkbool.cs
+++ b/snippets/csharp/System/Console/ReadKey/rkbool.cs
@@ -3,24 +3,23 @@
class Example
{
- public static void Main()
- {
- ConsoleKeyInfo cki;
- // Prevent example from ending if CTL+C is pressed.
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ ConsoleKeyInfo cki;
+ // Prevent example from ending if CTL+C is pressed.
+ Console.TreatControlCAsInput = true;
- Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
- Console.WriteLine("Press the Escape (Esc) key to quit: \n");
- do
- {
- cki = Console.ReadKey(true);
- Console.Write("You pressed ");
- if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
- if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
- if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
- Console.WriteLine($"{cki.Key} (character '{cki.KeyChar}')");
- } while (cki.Key != ConsoleKey.Escape);
- }
+ Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
+ Console.WriteLine("Press the Escape (Esc) key to quit: \n");
+ do {
+ cki = Console.ReadKey(true);
+ Console.Write("You pressed ");
+ if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
+ if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
+ if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
+ Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
+ } while (cki.Key != ConsoleKey.Escape);
+ }
}
// This example displays output similar to the following:
// Press any combination of CTL, ALT, and SHIFT, and a console key.
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLine2.cs b/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
index 7c1f5b60edb..95b0bc58501 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLine2.cs
@@ -3,19 +3,18 @@
public class Example
{
- public static void Main()
- {
- string line;
- Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
- Console.WriteLine();
- do
- {
- Console.Write(" ");
- line = Console.ReadLine();
- if (line != null)
- Console.WriteLine(" " + line);
- } while (line != null);
- }
+ public static void Main()
+ {
+ string line;
+ Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
+ Console.WriteLine();
+ do {
+ Console.Write(" ");
+ line = Console.ReadLine();
+ if (line != null)
+ Console.WriteLine(" " + line);
+ } while (line != null);
+ }
}
// The following displays possible output from this example:
// Enter one or more lines of text (press CTRL+Z to exit):
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLine3.cs b/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
index f3d0aea181a..531421d7f5f 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLine3.cs
@@ -3,26 +3,24 @@
public class Example
{
- public static void Main()
- {
- if (!Console.IsInputRedirected)
- {
- Console.WriteLine("This example requires that input be redirected from a file.");
- return;
- }
+ public static void Main()
+ {
+ if (!Console.IsInputRedirected) {
+ Console.WriteLine("This example requires that input be redirected from a file.");
+ return;
+ }
- Console.WriteLine("About to call Console.ReadLine in a loop.");
- Console.WriteLine("----");
- string s;
- int ctr = 0;
- do
- {
- ctr++;
- s = Console.ReadLine();
- Console.WriteLine($"Line {ctr}: {s}");
- } while (s != null);
- Console.WriteLine("---");
- }
+ Console.WriteLine("About to call Console.ReadLine in a loop.");
+ Console.WriteLine("----");
+ String s;
+ int ctr = 0;
+ do {
+ ctr++;
+ s = Console.ReadLine();
+ Console.WriteLine("Line {0}: {1}", ctr, s);
+ } while (s != null);
+ Console.WriteLine("---");
+ }
}
// The example displays the following output:
// About to call Console.ReadLine in a loop.
@@ -33,4 +31,4 @@ public static void Main()
// Line 4: This is the fourth line.
// Line 5:
// ---
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs b/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
index 49e07aac22a..3adb24727de 100644
--- a/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
+++ b/snippets/csharp/System/Console/ReadLine/ReadLineSimple.cs
@@ -3,16 +3,16 @@
public class Example
{
- public static void Main()
- {
- Console.Clear();
+ public static void Main()
+ {
+ Console.Clear();
- DateTime dat = DateTime.Now;
+ DateTime dat = DateTime.Now;
- Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
- Console.Write("\nPress any key to continue... ");
- Console.ReadLine();
- }
+ Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
+ Console.Write("\nPress any key to continue... ");
+ Console.ReadLine();
+ }
}
// The example displays output like the following:
// Today is 10/26/2015 at 12:22:22 PM.
diff --git a/snippets/csharp/System/Console/SetBufferSize/wlt.cs b/snippets/csharp/System/Console/SetBufferSize/wlt.cs
index fdde5bdd3aa..406d5c83a57 100644
--- a/snippets/csharp/System/Console/SetBufferSize/wlt.cs
+++ b/snippets/csharp/System/Console/SetBufferSize/wlt.cs
@@ -12,101 +12,101 @@ class Sample
public static int saveWindowHeight;
public static int saveWindowWidth;
public static bool saveCursorVisible;
- //
+//
public static void Main()
{
- string m1 = "1) Press the cursor keys to move the console window.\n" +
- "2) Press any key to begin. When you're finished...\n" +
- "3) Press the Escape key to quit.";
- string g1 = "+----";
- string g2 = "| ";
- string grid1;
- string grid2;
- StringBuilder sbG1 = new();
- StringBuilder sbG2 = new();
- ConsoleKeyInfo cki;
- int y;
- //
- try
- {
- saveBufferWidth = Console.BufferWidth;
- saveBufferHeight = Console.BufferHeight;
- saveWindowHeight = Console.WindowHeight;
- saveWindowWidth = Console.WindowWidth;
- saveCursorVisible = Console.CursorVisible;
- //
- Console.Clear();
- Console.WriteLine(m1);
- Console.ReadKey(true);
+ string m1 = "1) Press the cursor keys to move the console window.\n" +
+ "2) Press any key to begin. When you're finished...\n" +
+ "3) Press the Escape key to quit.";
+ string g1 = "+----";
+ string g2 = "| ";
+ string grid1;
+ string grid2;
+ StringBuilder sbG1 = new StringBuilder();
+ StringBuilder sbG2 = new StringBuilder();
+ ConsoleKeyInfo cki;
+ int y;
+//
+ try
+ {
+ saveBufferWidth = Console.BufferWidth;
+ saveBufferHeight = Console.BufferHeight;
+ saveWindowHeight = Console.WindowHeight;
+ saveWindowWidth = Console.WindowWidth;
+ saveCursorVisible = Console.CursorVisible;
+//
+ Console.Clear();
+ Console.WriteLine(m1);
+ Console.ReadKey(true);
- // Set the smallest possible window size before setting the buffer size.
- Console.SetWindowSize(1, 1);
- Console.SetBufferSize(80, 80);
- Console.SetWindowSize(40, 20);
+// Set the smallest possible window size before setting the buffer size.
+ Console.SetWindowSize(1, 1);
+ Console.SetBufferSize(80, 80);
+ Console.SetWindowSize(40, 20);
- // Create grid lines to fit the buffer. (The buffer width is 80, but
- // this same technique could be used with an arbitrary buffer width.)
- for (y = 0; y < Console.BufferWidth / g1.Length; y++)
- {
- sbG1.Append(g1);
- sbG2.Append(g2);
- }
- sbG1.Append(g1, 0, Console.BufferWidth % g1.Length);
- sbG2.Append(g2, 0, Console.BufferWidth % g2.Length);
- grid1 = sbG1.ToString();
- grid2 = sbG2.ToString();
+// Create grid lines to fit the buffer. (The buffer width is 80, but
+// this same technique could be used with an arbitrary buffer width.)
+ for (y = 0; y < Console.BufferWidth/g1.Length; y++)
+ {
+ sbG1.Append(g1);
+ sbG2.Append(g2);
+ }
+ sbG1.Append(g1, 0, Console.BufferWidth%g1.Length);
+ sbG2.Append(g2, 0, Console.BufferWidth%g2.Length);
+ grid1 = sbG1.ToString();
+ grid2 = sbG2.ToString();
- Console.CursorVisible = false;
- Console.Clear();
- for (y = 0; y < Console.BufferHeight - 1; y++)
- {
- if (y % 3 == 0)
- Console.Write(grid1);
- else
- Console.Write(grid2);
- }
+ Console.CursorVisible = false;
+ Console.Clear();
+ for (y = 0; y < Console.BufferHeight-1; y++)
+ {
+ if (y%3 == 0)
+ Console.Write(grid1);
+ else
+ Console.Write(grid2);
+ }
- Console.SetWindowPosition(0, 0);
- do
+ Console.SetWindowPosition(0, 0);
+ do
+ {
+ cki = Console.ReadKey(true);
+ switch (cki.Key)
{
- cki = Console.ReadKey(true);
- switch (cki.Key)
- {
- case ConsoleKey.LeftArrow:
- if (Console.WindowLeft > 0)
- Console.SetWindowPosition(
- Console.WindowLeft - 1, Console.WindowTop);
- break;
- case ConsoleKey.UpArrow:
- if (Console.WindowTop > 0)
- Console.SetWindowPosition(
- Console.WindowLeft, Console.WindowTop - 1);
- break;
- case ConsoleKey.RightArrow:
- if (Console.WindowLeft < (Console.BufferWidth - Console.WindowWidth))
- Console.SetWindowPosition(
- Console.WindowLeft + 1, Console.WindowTop);
- break;
- case ConsoleKey.DownArrow:
- if (Console.WindowTop < (Console.BufferHeight - Console.WindowHeight))
- Console.SetWindowPosition(
- Console.WindowLeft, Console.WindowTop + 1);
- break;
- }
+ case ConsoleKey.LeftArrow:
+ if (Console.WindowLeft > 0)
+ Console.SetWindowPosition(
+ Console.WindowLeft-1, Console.WindowTop);
+ break;
+ case ConsoleKey.UpArrow:
+ if (Console.WindowTop > 0)
+ Console.SetWindowPosition(
+ Console.WindowLeft, Console.WindowTop-1);
+ break;
+ case ConsoleKey.RightArrow:
+ if (Console.WindowLeft < (Console.BufferWidth-Console.WindowWidth))
+ Console.SetWindowPosition(
+ Console.WindowLeft+1, Console.WindowTop);
+ break;
+ case ConsoleKey.DownArrow:
+ if (Console.WindowTop < (Console.BufferHeight-Console.WindowHeight))
+ Console.SetWindowPosition(
+ Console.WindowLeft, Console.WindowTop+1);
+ break;
}
- while (cki.Key != ConsoleKey.Escape); // end do-while
- } // end try
- catch (IOException e)
+ }
+ while (cki.Key != ConsoleKey.Escape); // end do-while
+ } // end try
+ catch (IOException e)
{
- Console.WriteLine(e.Message);
+ Console.WriteLine(e.Message);
}
- finally
+ finally
{
- Console.Clear();
- Console.SetWindowSize(1, 1);
- Console.SetBufferSize(saveBufferWidth, saveBufferHeight);
- Console.SetWindowSize(saveWindowWidth, saveWindowHeight);
- Console.CursorVisible = saveCursorVisible;
+ Console.Clear();
+ Console.SetWindowSize(1, 1);
+ Console.SetBufferSize(saveBufferWidth, saveBufferHeight);
+ Console.SetWindowSize(saveWindowWidth, saveWindowHeight);
+ Console.CursorVisible = saveCursorVisible;
}
} // end Main
} // end Sample
@@ -128,4 +128,4 @@ public static void Main()
+----+----+----+-
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/SetError/SetError1.cs b/snippets/csharp/System/Console/SetError/SetError1.cs
index 5025a062a80..c4eaff4b0e5 100644
--- a/snippets/csharp/System/Console/SetError/SetError1.cs
+++ b/snippets/csharp/System/Console/SetError/SetError1.cs
@@ -1,30 +1,30 @@
//
using System;
using System.IO;
-
+using System.Reflection;
public class RedirectStdErr
{
- public static void Main()
- {
- // Define file to receive error stream.
- DateTime appStart = DateTime.Now;
- string fn = @"c:\temp\errlog" + appStart.ToString("yyyyMMddHHmm") + ".log";
- TextWriter errStream = new StreamWriter(fn);
- string appName = typeof(RedirectStdErr).Assembly.Location;
- appName = appName.Substring(appName.LastIndexOf('\\') + 1);
- // Redirect standard error stream to file.
- Console.SetError(errStream);
- // Write file header.
- Console.Error.WriteLine($"Error Log for Application {appName}");
- Console.Error.WriteLine();
- Console.Error.WriteLine($"Application started at {appStart}.");
- Console.Error.WriteLine();
- //
- // Application code along with error output
- //
- // Close redirected error stream.
- Console.Error.Close();
- }
+ public static void Main()
+ {
+ // Define file to receive error stream.
+ DateTime appStart = DateTime.Now;
+ string fn = @"c:\temp\errlog" + appStart.ToString("yyyyMMddHHmm") + ".log";
+ TextWriter errStream = new StreamWriter(fn);
+ string appName = typeof(RedirectStdErr).Assembly.Location;
+ appName = appName.Substring(appName.LastIndexOf('\\') + 1);
+ // Redirect standard error stream to file.
+ Console.SetError(errStream);
+ // Write file header.
+ Console.Error.WriteLine("Error Log for Application {0}", appName);
+ Console.Error.WriteLine();
+ Console.Error.WriteLine("Application started at {0}.", appStart);
+ Console.Error.WriteLine();
+ //
+ // Application code along with error output
+ //
+ // Close redirected error stream.
+ Console.Error.Close();
+ }
}
//
diff --git a/snippets/csharp/System/Console/SetOut/source.cs b/snippets/csharp/System/Console/SetOut/source.cs
index 6368bc63c2f..c5fbd1f19b1 100644
--- a/snippets/csharp/System/Console/SetOut/source.cs
+++ b/snippets/csharp/System/Console/SetOut/source.cs
@@ -5,25 +5,24 @@ class SetOutSample
{
public static void Main()
{
- try
- {
- //
+ try {
+//
Console.WriteLine("Hello World");
- FileStream fs = new("Test.txt", FileMode.Create);
+ FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
- StreamWriter sw = new(fs);
+ StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();
- //
+//
}
catch (Exception ex)
{
- Console.WriteLine(ex.Message);
- Console.WriteLine(ex.StackTrace);
- }
- }
-}
+ Console.WriteLine(ex.Message);
+ Console.WriteLine(ex.StackTrace);
+ }
+ }
+}
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/SetWindowSize/sws.cs b/snippets/csharp/System/Console/SetWindowSize/sws.cs
index 2c30e51e186..8b4f1413538 100644
--- a/snippets/csharp/System/Console/SetWindowSize/sws.cs
+++ b/snippets/csharp/System/Console/SetWindowSize/sws.cs
@@ -8,38 +8,38 @@ class Sample
{
public static void Main()
{
- int origWidth, width;
- int origHeight, height;
- string m1 = "The current window width is {0}, and the " +
- "current window height is {1}.";
- string m2 = "The new window width is {0}, and the new " +
- "window height is {1}.";
- string m4 = " (Press any key to continue...)";
- //
- // Step 1: Get the current window dimensions.
- //
- origWidth = Console.WindowWidth;
- origHeight = Console.WindowHeight;
- Console.WriteLine(m1, Console.WindowWidth,
- Console.WindowHeight);
- Console.WriteLine(m4);
- Console.ReadKey(true);
- //
- // Step 2: Cut the window to 1/4 its original size.
- //
- width = origWidth / 2;
- height = origHeight / 2;
- Console.SetWindowSize(width, height);
- Console.WriteLine(m2, Console.WindowWidth,
- Console.WindowHeight);
- Console.WriteLine(m4);
- Console.ReadKey(true);
- //
- // Step 3: Restore the window to its original size.
- //
- Console.SetWindowSize(origWidth, origHeight);
- Console.WriteLine(m1, Console.WindowWidth,
- Console.WindowHeight);
+ int origWidth, width;
+ int origHeight, height;
+ string m1 = "The current window width is {0}, and the " +
+ "current window height is {1}.";
+ string m2 = "The new window width is {0}, and the new " +
+ "window height is {1}.";
+ string m4 = " (Press any key to continue...)";
+//
+// Step 1: Get the current window dimensions.
+//
+ origWidth = Console.WindowWidth;
+ origHeight = Console.WindowHeight;
+ Console.WriteLine(m1, Console.WindowWidth,
+ Console.WindowHeight);
+ Console.WriteLine(m4);
+ Console.ReadKey(true);
+//
+// Step 2: Cut the window to 1/4 its original size.
+//
+ width = origWidth/2;
+ height = origHeight/2;
+ Console.SetWindowSize(width, height);
+ Console.WriteLine(m2, Console.WindowWidth,
+ Console.WindowHeight);
+ Console.WriteLine(m4);
+ Console.ReadKey(true);
+//
+// Step 3: Restore the window to its original size.
+//
+ Console.SetWindowSize(origWidth, origHeight);
+ Console.WriteLine(m1, Console.WindowWidth,
+ Console.WindowHeight);
}
}
/*
@@ -52,4 +52,4 @@ public static void Main()
The current window width is 85, and the current window height is 43.
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/Title/mytitle.cs b/snippets/csharp/System/Console/Title/mytitle.cs
index 68ec4e50937..2718a9095d7 100644
--- a/snippets/csharp/System/Console/Title/mytitle.cs
+++ b/snippets/csharp/System/Console/Title/mytitle.cs
@@ -6,13 +6,14 @@ class Sample
{
public static void Main()
{
- Console.WriteLine($"The current console title is: \"{Console.Title}\"");
- Console.WriteLine(" (Press any key to change the console title.)");
- Console.ReadKey(true);
- Console.Title = "The title has changed!";
- Console.WriteLine("Note that the new console title is \"{0}\"\n" +
- " (Press any key to quit.)", Console.Title);
- Console.ReadKey(true);
+ Console.WriteLine("The current console title is: \"{0}\"",
+ Console.Title);
+ Console.WriteLine(" (Press any key to change the console title.)");
+ Console.ReadKey(true);
+ Console.Title = "The title has changed!";
+ Console.WriteLine("Note that the new console title is \"{0}\"\n" +
+ " (Press any key to quit.)", Console.Title);
+ Console.ReadKey(true);
}
}
/*
@@ -25,4 +26,4 @@ public static void Main()
(Press any key to quit.)
*/
-//
+//
\ No newline at end of file
diff --git a/snippets/csharp/System/Console/WindowLeft/windowleft1.cs b/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
index d7a0af10c3c..b25d1af0b13 100644
--- a/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
+++ b/snippets/csharp/System/Console/WindowLeft/windowleft1.cs
@@ -3,52 +3,52 @@
public class Example
{
- public static void Main()
- {
- ConsoleKeyInfo key;
- bool moved = false;
+ public static void Main()
+ {
+ ConsoleKeyInfo key;
+ bool moved = false;
- Console.BufferWidth += 4;
- Console.Clear();
+ Console.BufferWidth += 4;
+ Console.Clear();
- ShowConsoleStatistics();
- do
- {
- key = Console.ReadKey(true);
- if (key.Key == ConsoleKey.LeftArrow)
+ ShowConsoleStatistics();
+ do
+ {
+ key = Console.ReadKey(true);
+ if (key.Key == ConsoleKey.LeftArrow)
+ {
+ int pos = Console.WindowLeft - 1;
+ if (pos >= 0 && pos + Console.WindowWidth <= Console.BufferWidth)
{
- int pos = Console.WindowLeft - 1;
- if (pos >= 0 && pos + Console.WindowWidth <= Console.BufferWidth)
- {
- Console.WindowLeft = pos;
- moved = true;
- }
+ Console.WindowLeft = pos;
+ moved = true;
}
- else if (key.Key == ConsoleKey.RightArrow)
+ }
+ else if (key.Key == ConsoleKey.RightArrow)
+ {
+ int pos = Console.WindowLeft + 1;
+ if (pos + Console.WindowWidth <= Console.BufferWidth)
{
- int pos = Console.WindowLeft + 1;
- if (pos + Console.WindowWidth <= Console.BufferWidth)
- {
- Console.WindowLeft = pos;
- moved = true;
- }
+ Console.WindowLeft = pos;
+ moved = true;
}
- if (moved)
- {
- ShowConsoleStatistics();
- moved = false;
- }
- Console.WriteLine();
- } while (true);
- }
+ }
+ if (moved)
+ {
+ ShowConsoleStatistics();
+ moved = false;
+ }
+ Console.WriteLine();
+ } while (true);
+ }
- private static void ShowConsoleStatistics()
- {
- Console.WriteLine("Console statistics:");
- Console.WriteLine($" Buffer: {Console.BufferHeight} x {Console.BufferWidth}");
- Console.WriteLine($" Window: {Console.WindowHeight} x {Console.WindowWidth}");
- Console.WriteLine($" Window starts at {Console.WindowLeft}.");
- Console.WriteLine("Press <- or -> to move window, Ctrl+C to exit.");
- }
+ private static void ShowConsoleStatistics()
+ {
+ Console.WriteLine("Console statistics:");
+ Console.WriteLine(" Buffer: {0} x {1}", Console.BufferHeight, Console.BufferWidth);
+ Console.WriteLine(" Window: {0} x {1}", Console.WindowHeight, Console.WindowWidth);
+ Console.WriteLine(" Window starts at {0}.", Console.WindowLeft);
+ Console.WriteLine("Press <- or -> to move window, Ctrl+C to exit.");
+ }
}
//
diff --git a/snippets/csharp/System/Console/Write/WriteParams1.cs b/snippets/csharp/System/Console/Write/WriteParams1.cs
index dcf92542cc0..e55a9737241 100644
--- a/snippets/csharp/System/Console/Write/WriteParams1.cs
+++ b/snippets/csharp/System/Console/Write/WriteParams1.cs
@@ -3,38 +3,36 @@
public class Person
{
- public string Name { get; set; }
- public DateTime BirthDate { get; set; }
- public double Height { get; set; }
- public double Weight { get; set; }
- public char Gender { get; set; }
- public string Remarks { get; set; }
+ public String Name { get; set; }
+ public DateTime BirthDate { get; set; }
+ public Double Height { get; set; }
+ public Double Weight { get; set; }
+ public Char Gender { get; set; }
+ public String Remarks { get; set; }
- public object[] GetDescription() => new object[] { Name, Gender, Height, Weight, BirthDate };
+ public object[] GetDescription()
+ {
+ return new object[] { Name, Gender, Height, Weight, BirthDate};
+ }
}
public class Example
{
- public static void Main()
- {
- var p1 = new Person()
- {
- Name = "John",
- Gender = 'M',
- BirthDate = new DateTime(1992, 5, 10),
- Height = 73.5,
- Weight = 207,
- Remarks = "Client since 1/3/2012"
- };
- Console.Write("{0}: {1}, born {4:d} Height {2} inches, Weight {3} lbs ",
- p1.GetDescription());
- if (string.IsNullOrEmpty(p1.Remarks))
- Console.WriteLine();
- else
- Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
- Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
- "\n " : "");
- }
+ public static void Main()
+ {
+ var p1 = new Person() { Name = "John", Gender = 'M',
+ BirthDate = new DateTime(1992, 5, 10),
+ Height = 73.5, Weight = 207 };
+ p1.Remarks = "Client since 1/3/2012";
+ Console.Write("{0}: {1}, born {4:d} Height {2} inches, Weight {3} lbs ",
+ p1.GetDescription());
+ if (String.IsNullOrEmpty(p1.Remarks))
+ Console.WriteLine();
+ else
+ Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
+ Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
+ "\n " : "");
+ }
}
// The example displays the following output:
// John: M, born 5/10/1992 Height 73.5 inches, Weight 207 lbs Remarks: Client since 1/3/2012
diff --git a/snippets/csharp/System/Console/Write/WriteParams2.cs b/snippets/csharp/System/Console/Write/WriteParams2.cs
index b9cd2cd4c9a..9aaf17c3103 100644
--- a/snippets/csharp/System/Console/Write/WriteParams2.cs
+++ b/snippets/csharp/System/Console/Write/WriteParams2.cs
@@ -3,38 +3,36 @@
public class Person
{
- public string Name { get; set; }
- public DateTime BirthDate { get; set; }
- public double Height { get; set; }
- public double Weight { get; set; }
- public char Gender { get; set; }
- public string Remarks { get; set; }
+ public String Name { get; set; }
+ public DateTime BirthDate { get; set; }
+ public Double Height { get; set; }
+ public Double Weight { get; set; }
+ public Char Gender { get; set; }
+ public String Remarks { get; set; }
- public object[] GetDescription() => new object[] { Name, Gender, Height, Weight, BirthDate };
+ public object[] GetDescription()
+ {
+ return new object[] { Name, Gender, Height, Weight, BirthDate};
+ }
}
public class Example
{
- public static void Main()
- {
- var p1 = new Person()
- {
- Name = "John",
- Gender = 'M',
- BirthDate = new DateTime(1992, 5, 10),
- Height = 73.5,
- Weight = 207,
- Remarks = "Client since 1/3/2012"
- };
- Console.Write("{0}: {1}, born {2:d} Height {3} inches, Weight {4} lbs ",
- p1.Name, p1.Gender, p1.BirthDate, p1.Height, p1.Weight);
- if (string.IsNullOrEmpty(p1.Remarks))
- Console.WriteLine();
- else
- Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
- Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
- "\n " : "");
- }
+ public static void Main()
+ {
+ var p1 = new Person() { Name = "John", Gender = 'M',
+ BirthDate = new DateTime(1992, 5, 10),
+ Height = 73.5, Weight = 207 };
+ p1.Remarks = "Client since 1/3/2012";
+ Console.Write("{0}: {1}, born {2:d} Height {3} inches, Weight {4} lbs ",
+ p1.Name, p1.Gender, p1.BirthDate, p1.Height, p1.Weight);
+ if (String.IsNullOrEmpty(p1.Remarks))
+ Console.WriteLine();
+ else
+ Console.WriteLine("{1}Remarks: {0}", p1.Remarks,
+ Console.CursorLeft + p1.Remarks.Length + 10 > Console.WindowWidth ?
+ "\n " : "");
+ }
}
// The example displays the following output:
// John: M, born 5/10/1992 Height 73.5 inches, Weight 207 lbs Remarks: Client since 1/3/2012
diff --git a/snippets/csharp/System/Console/Write/reformat.cs b/snippets/csharp/System/Console/Write/reformat.cs
index e169951b7c5..38dd8a95995 100644
--- a/snippets/csharp/System/Console/Write/reformat.cs
+++ b/snippets/csharp/System/Console/Write/reformat.cs
@@ -13,9 +13,9 @@ public static void Main(string[] args)
string lineInput;
while ((lineInput = Console.ReadLine()) != null)
{
- string[] fields = lineInput.Split(new char[] { '\t' });
+ string[] fields = lineInput.Split(new char[] {'\t'});
bool isFirstField = true;
- foreach (string item in fields)
+ foreach (var item in fields)
{
if (isFirstField)
isFirstField = false;
@@ -23,11 +23,11 @@ public static void Main(string[] args)
Console.Write(',');
// If the field represents a boolean, replace with a numeric representation.
- bool itemBool;
- if (bool.TryParse(item, out itemBool))
- Console.Write(Convert.ToByte(itemBool));
- else
- Console.Write(item);
+ bool itemBool;
+ if (Boolean.TryParse(item, out itemBool))
+ Console.Write(Convert.ToByte(itemBool));
+ else
+ Console.Write(item);
}
Console.WriteLine();
}
diff --git a/snippets/csharp/System/Console/Write/wl.cs b/snippets/csharp/System/Console/Write/wl.cs
index 2ebd52baa74..3aafac9d489 100644
--- a/snippets/csharp/System/Console/Write/wl.cs
+++ b/snippets/csharp/System/Console/Write/wl.cs
@@ -1,11 +1,11 @@
-//
+//
// This code example demonstrates the Console.WriteLine() method.
// Formatting for this example uses the "en-US" culture.
using System;
class Sample
{
- enum Color { Yellow = 1, Blue, Green };
+ enum Color {Yellow = 1, Blue, Green};
static DateTime thisDate = DateTime.Now;
public static void Main()
diff --git a/snippets/csharp/System/Console/WriteLine/WriteLine6.cs b/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
index 1fc696ec4ff..ce3afce161b 100644
--- a/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
+++ b/snippets/csharp/System/Console/WriteLine/WriteLine6.cs
@@ -2,23 +2,22 @@
public class Example
{
- public static void Main()
- {
- //
- Random rnd = new();
- // Generate five random Boolean values.
- for (int ctr = 1; ctr <= 5; ctr++)
- {
- bool bln = rnd.Next(0, 2) == 1;
- Console.WriteLine($"True or False: {bln}");
- }
+ public static void Main()
+ {
+ //
+ Random rnd = new Random();
+ // Generate five random Boolean values.
+ for (int ctr = 1; ctr <= 5; ctr++) {
+ bool bln = rnd.Next(0, 2) == 1;
+ Console.WriteLine($"True or False: {bln}");
+ }
- // The example displays an output similar to the following:
- // True or False: False
- // True or False: True
- // True or False: False
- // True or False: False
- // True or False: True
- //
- }
+ // The example displays an output similar to the following:
+ // True or False: False
+ // True or False: True
+ // True or False: False
+ // True or False: False
+ // True or False: True
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/WriteLine7.cs b/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
index 40347ff1ad5..e48fe44472f 100644
--- a/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
+++ b/snippets/csharp/System/Console/WriteLine/WriteLine7.cs
@@ -1,9 +1,12 @@
-//
+//
using System;
public class Example
{
- public static void Main() => Console.WriteLine("Today's date: {0:D}", DateTime.Now);
+ public static void Main()
+ {
+ Console.WriteLine("Today's date: {0:D}", DateTime.Now);
+ }
}
// The example displays output like the following:
// Today's date: Monday, April 1, 2019
diff --git a/snippets/csharp/System/Console/WriteLine/newline1.cs b/snippets/csharp/System/Console/WriteLine/newline1.cs
index 14e95f1f860..5b6f51fed3c 100644
--- a/snippets/csharp/System/Console/WriteLine/newline1.cs
+++ b/snippets/csharp/System/Console/WriteLine/newline1.cs
@@ -2,40 +2,40 @@
public class Example
{
- public static void Main()
- {
- //
- string[] lines = { "This is the first line.",
+ public static void Main()
+ {
+ //
+ string[] lines = { "This is the first line.",
"This is the second line." };
- // Output the lines using the default newline sequence.
- Console.WriteLine("With the default new line characters:");
- Console.WriteLine();
- foreach (string line in lines)
- Console.WriteLine(line);
+ // Output the lines using the default newline sequence.
+ Console.WriteLine("With the default new line characters:");
+ Console.WriteLine();
+ foreach (string line in lines)
+ Console.WriteLine(line);
- Console.WriteLine();
+ Console.WriteLine();
- // Redefine the newline characters to double space.
- Console.Out.NewLine = "\r\n\r\n";
- // Output the lines using the new newline sequence.
- Console.WriteLine("With redefined new line characters:");
- Console.WriteLine();
- foreach (string line in lines)
- Console.WriteLine(line);
+ // Redefine the newline characters to double space.
+ Console.Out.NewLine = "\r\n\r\n";
+ // Output the lines using the new newline sequence.
+ Console.WriteLine("With redefined new line characters:");
+ Console.WriteLine();
+ foreach (string line in lines)
+ Console.WriteLine(line);
- // The example displays the following output:
- // With the default new line characters:
- //
- // This is the first line.
- // This is the second line.
- //
- // With redefined new line characters:
- //
- //
- //
- // This is the first line.
- //
- // This is the second line.
- //
- }
+ // The example displays the following output:
+ // With the default new line characters:
+ //
+ // This is the first line.
+ // This is the second line.
+ //
+ // With redefined new line characters:
+ //
+ //
+ //
+ // This is the first line.
+ //
+ // This is the second line.
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/tipcalc.cs b/snippets/csharp/System/Console/WriteLine/tipcalc.cs
index 882529a1b43..82719638d30 100644
--- a/snippets/csharp/System/Console/WriteLine/tipcalc.cs
+++ b/snippets/csharp/System/Console/WriteLine/tipcalc.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
public class TipCalculator
@@ -7,7 +7,7 @@ public class TipCalculator
public static void Main(string[] args)
{
double billTotal;
- if (args.Length == 0 || !double.TryParse(args[0], out billTotal))
+ if (args.Length == 0 || ! Double.TryParse(args[0], out billTotal))
{
Console.WriteLine("usage: TIPCALC total");
return;
diff --git a/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs b/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
index 207acb5e018..b84e282754f 100644
--- a/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
+++ b/snippets/csharp/System/Console/WriteLine/writeline_boolean1.cs
@@ -2,23 +2,22 @@
public class Example
{
- public static void Main()
- {
- //
- // Assign 10 random integers to an array.
- Random rnd = new();
- int[] numbers = new int[10];
- for (int ctr = 0; ctr <= numbers.GetUpperBound(0); ctr++)
- numbers[ctr] = rnd.Next();
+ public static void Main()
+ {
+ //
+ // Assign 10 random integers to an array.
+ Random rnd = new Random();
+ int[] numbers = new int[10];
+ for (int ctr = 0; ctr <= numbers.GetUpperBound(0); ctr++)
+ numbers[ctr] = rnd.Next();
- // Determine whether the numbers are even or odd.
- foreach (int number in numbers)
- {
- bool even = (number % 2 == 0);
- Console.WriteLine("Is {0} even:", number);
- Console.WriteLine(even);
- Console.WriteLine();
- }
- //
- }
+ // Determine whether the numbers are even or odd.
+ foreach (var number in numbers) {
+ bool even = (number % 2 == 0);
+ Console.WriteLine("Is {0} even:", number);
+ Console.WriteLine(even);
+ Console.WriteLine();
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs b/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
index 765fc9623d5..d9e5c533435 100644
--- a/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
+++ b/snippets/csharp/System/Console/WriteLine/writeline_obj1.cs
@@ -2,21 +2,21 @@
public class Example
{
- public static void Main()
- {
- //
- object[] values = { true, 12.632, 17908, "stringValue",
+ public static void Main()
+ {
+ //
+ Object[] values = { true, 12.632, 17908, "stringValue",
'a', 16907.32m };
- foreach (object value in values)
- Console.WriteLine(value);
+ foreach (var value in values)
+ Console.WriteLine(value);
- // The example displays the following output:
- // True
- // 12.632
- // 17908
- // stringValue
- // a
- // 16907.32
- //
- }
+ // The example displays the following output:
+ // True
+ // 12.632
+ // 17908
+ // stringValue
+ // a
+ // 16907.32
+ //
+ }
}
diff --git a/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs b/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
index eba1ea1a6d8..f57fb36b858 100644
--- a/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
+++ b/snippets/csharp/System/ConsoleKey/Overview/ConsoleKey1.cs
@@ -4,55 +4,49 @@
public class ConsoleKeyExample
{
- public static void Main()
- {
- ConsoleKeyInfo input;
- do
- {
- Console.WriteLine("Press a key, together with Alt, Ctrl, or Shift.");
- Console.WriteLine("Press Esc to exit.");
- input = Console.ReadKey(true);
+ public static void Main()
+ {
+ ConsoleKeyInfo input;
+ do {
+ Console.WriteLine("Press a key, together with Alt, Ctrl, or Shift.");
+ Console.WriteLine("Press Esc to exit.");
+ input = Console.ReadKey(true);
- StringBuilder output = new(
- $"You pressed {input.Key.ToString()}");
- bool modifiers = false;
+ StringBuilder output = new StringBuilder(
+ String.Format("You pressed {0}", input.Key.ToString()));
+ bool modifiers = false;
- if (input.Modifiers.HasFlag(ConsoleModifiers.Alt))
- {
- output.Append(", together with " + ConsoleModifiers.Alt.ToString());
- modifiers = true;
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Alt)) {
+ output.Append(", together with " + ConsoleModifiers.Alt.ToString());
+ modifiers = true;
+ }
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Control))
+ {
+ if (modifiers) {
+ output.Append(" and ");
}
- if (input.Modifiers.HasFlag(ConsoleModifiers.Control))
- {
- if (modifiers)
- {
- output.Append(" and ");
- }
- else
- {
- output.Append(", together with ");
- modifiers = true;
- }
- output.Append(ConsoleModifiers.Control.ToString());
+ else {
+ output.Append(", together with ");
+ modifiers = true;
}
- if (input.Modifiers.HasFlag(ConsoleModifiers.Shift))
- {
- if (modifiers)
- {
- output.Append(" and ");
- }
- else
- {
- output.Append(", together with ");
- modifiers = true;
- }
- output.Append(ConsoleModifiers.Shift.ToString());
+ output.Append(ConsoleModifiers.Control.ToString());
+ }
+ if (input.Modifiers.HasFlag(ConsoleModifiers.Shift))
+ {
+ if (modifiers) {
+ output.Append(" and ");
}
- output.Append(".");
- Console.WriteLine(output.ToString());
- Console.WriteLine();
- } while (input.Key != ConsoleKey.Escape);
- }
+ else {
+ output.Append(", together with ");
+ modifiers = true;
+ }
+ output.Append(ConsoleModifiers.Shift.ToString());
+ }
+ output.Append(".");
+ Console.WriteLine(output.ToString());
+ Console.WriteLine();
+ } while (input.Key != ConsoleKey.Escape);
+ }
}
// The output from a sample console session might appear as follows:
// Press a key, together with Alt, Ctrl, or Shift.
diff --git a/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs b/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
index 7065e1f3ec8..aed90927338 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/Equals/equals.cs
@@ -8,71 +8,69 @@ class Sample
{
public static void Main()
{
- string k1 = "\nEnter a key ......... ";
- string k2 = "\nEnter another key ... ";
- string key1 = "";
- string key2 = "";
- string areKeysEqual = "The {0} and {1} keys are {2}equal.";
- string equalValue = "";
- string prompt = "Press the escape key (ESC) to quit, " +
- "or any other key to continue.";
- ConsoleKeyInfo cki1;
- ConsoleKeyInfo cki2;
+ string k1 = "\nEnter a key ......... ";
+ string k2 = "\nEnter another key ... ";
+ string key1 = "";
+ string key2 = "";
+ string areKeysEqual = "The {0} and {1} keys are {2}equal.";
+ string equalValue = "";
+ string prompt = "Press the escape key (ESC) to quit, " +
+ "or any other key to continue.";
+ ConsoleKeyInfo cki1;
+ ConsoleKeyInfo cki2;
- //
- // The Console.TreatControlCAsInput property prevents this example from
- // ending if you press CTL+C, however all other operating system keys and
- // shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
- //
- Console.TreatControlCAsInput = true;
+//
+// The Console.TreatControlCAsInput property prevents this example from
+// ending if you press CTL+C, however all other operating system keys and
+// shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
+//
+ Console.TreatControlCAsInput = true;
- // Request that the user enter two key presses. A key press and any
- // combination shift, CTRL, and ALT modifier keys is permitted.
- do
- {
- Console.Write(k1);
- cki1 = Console.ReadKey(false);
- Console.Write(k2);
- cki2 = Console.ReadKey(false);
- Console.WriteLine();
- //
- key1 = KeyCombination(cki1);
- key2 = KeyCombination(cki2);
- if (cki1.Equals(cki2))
- equalValue = "";
- else
- equalValue = "not ";
- Console.WriteLine(areKeysEqual, key1, key2, equalValue);
- //
- Console.WriteLine(prompt);
- cki1 = Console.ReadKey(true);
- } while (cki1.Key != ConsoleKey.Escape);
- // Note: This example requires the Escape (Esc) key.
+// Request that the user enter two key presses. A key press and any
+// combination shift, CTRL, and ALT modifier keys is permitted.
+ do
+ {
+ Console.Write(k1);
+ cki1 = Console.ReadKey(false);
+ Console.Write(k2);
+ cki2 = Console.ReadKey(false);
+ Console.WriteLine();
+//
+ key1 = KeyCombination(cki1);
+ key2 = KeyCombination(cki2);
+ if (cki1.Equals(cki2))
+ equalValue = "";
+ else
+ equalValue = "not ";
+ Console.WriteLine(areKeysEqual, key1, key2, equalValue);
+//
+ Console.WriteLine(prompt);
+ cki1 = Console.ReadKey(true);
+ } while (cki1.Key != ConsoleKey.Escape);
+// Note: This example requires the Escape (Esc) key.
}
- // The KeyCombination() method creates a string that specifies what
- // key and what combination of shift, CTRL, and ALT modifier keys
- // were pressed simultaneously.
+// The KeyCombination() method creates a string that specifies what
+// key and what combination of shift, CTRL, and ALT modifier keys
+// were pressed simultaneously.
protected static string KeyCombination(ConsoleKeyInfo sourceCki)
{
- StringBuilder sb = new()
- {
- Length = 0
- };
- string keyCombo;
- if (sourceCki.Modifiers != 0)
+ StringBuilder sb = new StringBuilder();
+ sb.Length = 0;
+ string keyCombo;
+ if (sourceCki.Modifiers != 0)
{
- if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
- sb.Append("ALT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
- sb.Append("SHIFT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
- sb.Append("CTL+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
+ sb.Append("ALT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
+ sb.Append("SHIFT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
+ sb.Append("CTL+");
}
- sb.Append(sourceCki.Key.ToString());
- keyCombo = sb.ToString();
- return keyCombo;
+ sb.Append(sourceCki.Key.ToString());
+ keyCombo = sb.ToString();
+ return keyCombo;
}
}
diff --git a/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs b/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
index 53668489262..42107343468 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/GetHashCode/hash.cs
@@ -8,62 +8,60 @@ class Sample
{
public static void Main()
{
- string k1 = "\nEnter a key ......... ";
- string key1 = "";
- string hashCodeFmt = "The hash code for the {0} key is {1}.";
- string prompt = "Press the escape key (ESC) to quit, " +
- "or any other key to continue.";
- ConsoleKeyInfo cki1;
- int hashCode = 0;
+ string k1 = "\nEnter a key ......... ";
+ string key1 = "";
+ string hashCodeFmt = "The hash code for the {0} key is {1}.";
+ string prompt = "Press the escape key (ESC) to quit, " +
+ "or any other key to continue.";
+ ConsoleKeyInfo cki1;
+ int hashCode = 0;
- //
- // The Console.TreatControlCAsInput property prevents this example from
- // ending if you press CTL+C, however all other operating system keys and
- // shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
- //
- Console.TreatControlCAsInput = true;
+//
+// The Console.TreatControlCAsInput property prevents this example from
+// ending if you press CTL+C, however all other operating system keys and
+// shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect.
+//
+ Console.TreatControlCAsInput = true;
- // Request that the user enter two key presses. A key press and any
- // combination shift, CTRL, and ALT modifier keys is permitted.
- do
- {
- Console.Write(k1);
- cki1 = Console.ReadKey(false);
- Console.WriteLine();
- //
- key1 = KeyCombination(cki1);
- hashCode = cki1.GetHashCode();
- Console.WriteLine(hashCodeFmt, key1, hashCode);
- //
- Console.WriteLine(prompt);
- cki1 = Console.ReadKey(true);
- } while (cki1.Key != ConsoleKey.Escape);
- // Note: This example requires the Escape (Esc) key.
+// Request that the user enter two key presses. A key press and any
+// combination shift, CTRL, and ALT modifier keys is permitted.
+ do
+ {
+ Console.Write(k1);
+ cki1 = Console.ReadKey(false);
+ Console.WriteLine();
+//
+ key1 = KeyCombination(cki1);
+ hashCode = cki1.GetHashCode();
+ Console.WriteLine(hashCodeFmt, key1, hashCode);
+//
+ Console.WriteLine(prompt);
+ cki1 = Console.ReadKey(true);
+ } while (cki1.Key != ConsoleKey.Escape);
+// Note: This example requires the Escape (Esc) key.
}
- // The KeyCombination() method creates a string that specifies what
- // key and what combination of shift, CTRL, and ALT modifier keys
- // were pressed simultaneously.
+// The KeyCombination() method creates a string that specifies what
+// key and what combination of shift, CTRL, and ALT modifier keys
+// were pressed simultaneously.
protected static string KeyCombination(ConsoleKeyInfo sourceCki)
{
- StringBuilder sb = new()
- {
- Length = 0
- };
- string keyCombo;
- if (sourceCki.Modifiers != 0)
+ StringBuilder sb = new StringBuilder();
+ sb.Length = 0;
+ string keyCombo;
+ if (sourceCki.Modifiers != 0)
{
- if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
- sb.Append("ALT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
- sb.Append("SHIFT+");
- if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
- sb.Append("CTL+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Alt) != 0)
+ sb.Append("ALT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Shift) != 0)
+ sb.Append("SHIFT+");
+ if ((sourceCki.Modifiers & ConsoleModifiers.Control) != 0)
+ sb.Append("CTL+");
}
- sb.Append(sourceCki.Key.ToString());
- keyCombo = sb.ToString();
- return keyCombo;
+ sb.Append(sourceCki.Key.ToString());
+ keyCombo = sb.ToString();
+ return keyCombo;
}
}
diff --git a/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs b/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
index 57adc40a6e2..9426ae7aec5 100644
--- a/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
+++ b/snippets/csharp/System/ConsoleKeyInfo/KeyChar/keychar1.cs
@@ -3,55 +3,53 @@
public class Example
{
- public static void Main()
- {
- // Configure console.
- Console.BufferWidth = 80;
- Console.WindowWidth = Console.BufferWidth;
- Console.TreatControlCAsInput = true;
+ public static void Main()
+ {
+ // Configure console.
+ Console.BufferWidth = 80;
+ Console.WindowWidth = Console.BufferWidth;
+ Console.TreatControlCAsInput = true;
- string inputString = string.Empty;
- ConsoleKeyInfo keyInfo;
+ string inputString = String.Empty;
+ ConsoleKeyInfo keyInfo;
- Console.WriteLine("Enter a string. Press or Esc to exit.");
- do
- {
- keyInfo = Console.ReadKey(true);
- // Ignore if Alt or Ctrl is pressed.
- if ((keyInfo.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt)
- continue;
- if ((keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
- continue;
- // Ignore if KeyChar value is \u0000.
- if (keyInfo.KeyChar == '\u0000') continue;
- // Ignore tab key.
- if (keyInfo.Key == ConsoleKey.Tab) continue;
- // Handle backspace.
- if (keyInfo.Key == ConsoleKey.Backspace)
- {
- // Are there any characters to erase?
- if (inputString.Length >= 1)
- {
- // Determine where we are in the console buffer.
- int cursorCol = Console.CursorLeft - 1;
- int oldLength = inputString.Length;
- int extraRows = oldLength / 80;
+ Console.WriteLine("Enter a string. Press or Esc to exit.");
+ do {
+ keyInfo = Console.ReadKey(true);
+ // Ignore if Alt or Ctrl is pressed.
+ if ((keyInfo.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt)
+ continue;
+ if ((keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
+ continue;
+ // Ignore if KeyChar value is \u0000.
+ if (keyInfo.KeyChar == '\u0000') continue;
+ // Ignore tab key.
+ if (keyInfo.Key == ConsoleKey.Tab) continue;
+ // Handle backspace.
+ if (keyInfo.Key == ConsoleKey.Backspace) {
+ // Are there any characters to erase?
+ if (inputString.Length >= 1) {
+ // Determine where we are in the console buffer.
+ int cursorCol = Console.CursorLeft - 1;
+ int oldLength = inputString.Length;
+ int extraRows = oldLength / 80;
- inputString = inputString.Substring(0, oldLength - 1);
- Console.CursorLeft = 0;
- Console.CursorTop = Console.CursorTop - extraRows;
- Console.Write(inputString + new string(' ', oldLength - inputString.Length));
- Console.CursorLeft = cursorCol;
- }
- continue;
+ inputString = inputString.Substring(0, oldLength - 1);
+ Console.CursorLeft = 0;
+ Console.CursorTop = Console.CursorTop - extraRows;
+ Console.Write(inputString + new String(' ', oldLength - inputString.Length));
+ Console.CursorLeft = cursorCol;
}
- // Handle Escape key.
- if (keyInfo.Key == ConsoleKey.Escape) break;
- // Handle key by adding it to input string.
- Console.Write(keyInfo.KeyChar);
- inputString += keyInfo.KeyChar;
- } while (keyInfo.Key != ConsoleKey.Enter);
- Console.WriteLine($"\n\nYou entered:\n {(string.IsNullOrEmpty(inputString) ? "" : inputString)}");
- }
+ continue;
+ }
+ // Handle Escape key.
+ if (keyInfo.Key == ConsoleKey.Escape) break;
+ // Handle key by adding it to input string.
+ Console.Write(keyInfo.KeyChar);
+ inputString += keyInfo.KeyChar;
+ } while (keyInfo.Key != ConsoleKey.Enter);
+ Console.WriteLine("\n\nYou entered:\n {0}",
+ String.IsNullOrEmpty(inputString) ? "" : inputString);
+ }
}
//
From 2edbe5cb8504d3893dc5cfb02860f5f4df8ae3f8 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Tue, 11 Aug 2026 10:40:31 -0700
Subject: [PATCH 5/5] add missing project files
---
.../EntryPointNotFoundException/Overview/Program.cs | 6 ++++++
.../Overview/Project.csproj | 6 ++++++
.../EntryPointNotFoundException/Overview/badcall1.cs | 4 ++--
.../Overview/fiximportassembly1.cs | 4 ++--
.../Overview/importassembly1.cs | 4 ++--
.../EntryPointNotFoundException/Overview/mangle1.cs | 4 ++--
.../EntryPointNotFoundException/Overview/mangle2.cs | 4 ++--
.../Overview/nofunction1.cs | 4 ++--
snippets/csharp/System/Enum/GetValues/EnumGetValues.cs | 2 +-
snippets/csharp/System/Enum/GetValues/Program.cs | 3 +++
snippets/csharp/System/Enum/GetValues/Project.csproj | 6 ++++++
snippets/csharp/System/Enum/GetValues/getvalues1.cs | 4 ++--
.../System/Enum/GetValues/getvalues_reflectiononly.cs | 4 ++--
snippets/csharp/System/Enum/HasFlag/Program.cs | 2 ++
snippets/csharp/System/Enum/HasFlag/Project.csproj | 6 ++++++
snippets/csharp/System/Enum/HasFlag/hasflag0.cs | 4 ++--
snippets/csharp/System/Enum/HasFlag/hasflag1.cs | 4 ++--
snippets/csharp/System/Enum/IsDefined/Program.cs | 2 ++
snippets/csharp/System/Enum/IsDefined/Project.csproj | 6 ++++++
snippets/csharp/System/Enum/IsDefined/isdefined1.cs | 4 ++--
snippets/csharp/System/Enum/IsDefined/isdefined2.cs | 4 ++--
snippets/csharp/System/Enum/Parse/EnumParse.cs | 2 +-
snippets/csharp/System/Enum/Parse/ParseExample1.cs | 10 +++++-----
snippets/csharp/System/Enum/Parse/ParseExample2.cs | 10 +++++-----
snippets/csharp/System/Enum/Parse/Program.cs | 3 +++
snippets/csharp/System/Enum/Parse/Project.csproj | 6 ++++++
snippets/csharp/System/Enum/TryParseTEnum/Program.cs | 2 ++
.../csharp/System/Enum/TryParseTEnum/Project.csproj | 6 ++++++
snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs | 10 +++++-----
snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs | 10 +++++-----
snippets/csharp/System/Environment/ExitCode/Program.cs | 2 ++
.../csharp/System/Environment/ExitCode/Project.csproj | 6 ++++++
snippets/csharp/System/Environment/ExitCode/double.cs | 4 ++--
snippets/csharp/System/Environment/ExitCode/double1.cs | 4 ++--
.../Environment/GetEnvironmentVariable/Program.cs | 2 ++
.../Environment/GetEnvironmentVariable/Project.csproj | 6 ++++++
.../getenvironmentvariableex1.cs | 4 ++--
.../System/Environment/GetEnvironmentVariable/gsev.cs | 2 +-
38 files changed, 123 insertions(+), 53 deletions(-)
create mode 100644 snippets/csharp/System/EntryPointNotFoundException/Overview/Program.cs
create mode 100644 snippets/csharp/System/EntryPointNotFoundException/Overview/Project.csproj
create mode 100644 snippets/csharp/System/Enum/GetValues/Program.cs
create mode 100644 snippets/csharp/System/Enum/GetValues/Project.csproj
create mode 100644 snippets/csharp/System/Enum/HasFlag/Program.cs
create mode 100644 snippets/csharp/System/Enum/HasFlag/Project.csproj
create mode 100644 snippets/csharp/System/Enum/IsDefined/Program.cs
create mode 100644 snippets/csharp/System/Enum/IsDefined/Project.csproj
create mode 100644 snippets/csharp/System/Enum/Parse/Program.cs
create mode 100644 snippets/csharp/System/Enum/Parse/Project.csproj
create mode 100644 snippets/csharp/System/Enum/TryParseTEnum/Program.cs
create mode 100644 snippets/csharp/System/Enum/TryParseTEnum/Project.csproj
create mode 100644 snippets/csharp/System/Environment/ExitCode/Program.cs
create mode 100644 snippets/csharp/System/Environment/ExitCode/Project.csproj
create mode 100644 snippets/csharp/System/Environment/GetEnvironmentVariable/Program.cs
create mode 100644 snippets/csharp/System/Environment/GetEnvironmentVariable/Project.csproj
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/Program.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/Program.cs
new file mode 100644
index 00000000000..476015f2d96
--- /dev/null
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/Program.cs
@@ -0,0 +1,6 @@
+BadCallExample.Run();
+FixImportAssemblyExample.Run();
+ImportAssemblyExample.Run();
+MangleMissingExample.Run();
+MangleFixedExample.Run();
+NoFunctionExample.Run();
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/Project.csproj b/snippets/csharp/System/EntryPointNotFoundException/Overview/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
index ffa218fa50c..572111577f4 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/badcall1.cs
@@ -2,7 +2,7 @@
using System;
using System.Runtime.InteropServices;
-public class Example
+public class BadCallExample
{
[DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern int MessageBox(IntPtr hwnd, string text, string caption, uint type);
@@ -10,7 +10,7 @@ public class Example
[DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern int MessageBoxW(IntPtr hwnd, string text, string caption, uint type);
- public static void Main()
+ public static void Run()
{
try
{
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
index 3def163c260..de9746463da 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/fiximportassembly1.cs
@@ -1,9 +1,9 @@
//
using System;
-public class Example
+public class FixImportAssemblyExample
{
- public static void Main() => Console.WriteLine(StringUtilities.SayGoodMorning("Dakota"));
+ public static void Run() => Console.WriteLine(StringUtilities.SayGoodMorning("Dakota"));
}
// The example displays the following output:
// A top of the morning to you, Dakota!
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
index 65adebedfd0..d5d2ef91fa5 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/importassembly1.cs
@@ -2,12 +2,12 @@
using System;
using System.Runtime.InteropServices;
-public class Example
+public class ImportAssemblyExample
{
[DllImport("StringUtilities.dll", CharSet = CharSet.Unicode)]
public static extern string SayGoodMorning(string name);
- public static void Main() => Console.WriteLine(SayGoodMorning("Dakota"));
+ public static void Run() => Console.WriteLine(SayGoodMorning("Dakota"));
}
// The example displays the following output:
// Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
index a54acbd5ff6..54b0ee3754a 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle1.cs
@@ -2,12 +2,12 @@
using System;
using System.Runtime.InteropServices;
-public class Example
+public class MangleMissingExample
{
[DllImport("TestDll.dll")]
public static extern int Double(int number);
- public static void Main() => Console.WriteLine(Double(10));
+ public static void Run() => Console.WriteLine(Double(10));
}
// The example displays the following output:
// Unhandled Exception: System.EntryPointNotFoundException: Unable to find
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
index 19fc3684403..83cb0656d39 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/mangle2.cs
@@ -2,12 +2,12 @@
using System;
using System.Runtime.InteropServices;
-public class Example
+public class MangleFixedExample
{
[DllImport("TestDll.dll", EntryPoint = "?Double@@YAHH@Z")]
public static extern int Double(int number);
- public static void Main() => Console.WriteLine(Double(10));
+ public static void Run() => Console.WriteLine(Double(10));
}
// The example displays the following output:
// 20
diff --git a/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs b/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
index 1b9caeb025b..81e8f6b49e6 100644
--- a/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
+++ b/snippets/csharp/System/EntryPointNotFoundException/Overview/nofunction1.cs
@@ -2,12 +2,12 @@
using System;
using System.Runtime.InteropServices;
-public class Example
+public class NoFunctionExample
{
[DllImport("user32.dll")]
public static extern int GetMyNumber();
- public static void Main()
+ public static void Run()
{
try
{
diff --git a/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs b/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
index 4eb7fb06194..f212d828293 100644
--- a/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
+++ b/snippets/csharp/System/Enum/GetValues/EnumGetValues.cs
@@ -6,7 +6,7 @@ public class GetValuesTest
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid = 0, Striped = 23, Tartan = 65, Corduroy = 78 };
- public static void Main()
+ public static void Run()
{
Console.WriteLine("The values of the Colors Enum are:");
diff --git a/snippets/csharp/System/Enum/GetValues/Program.cs b/snippets/csharp/System/Enum/GetValues/Program.cs
new file mode 100644
index 00000000000..77f08a7187b
--- /dev/null
+++ b/snippets/csharp/System/Enum/GetValues/Program.cs
@@ -0,0 +1,3 @@
+GetValuesTest.Run();
+SignMagnitudeExample.Run();
+ReflectionOnlyGetValuesExample.Run();
diff --git a/snippets/csharp/System/Enum/GetValues/Project.csproj b/snippets/csharp/System/Enum/GetValues/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Enum/GetValues/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Enum/GetValues/getvalues1.cs b/snippets/csharp/System/Enum/GetValues/getvalues1.cs
index c08943cff44..3b7da4ff5e7 100644
--- a/snippets/csharp/System/Enum/GetValues/getvalues1.cs
+++ b/snippets/csharp/System/Enum/GetValues/getvalues1.cs
@@ -3,9 +3,9 @@
enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };
-public class Example
+public class SignMagnitudeExample
{
- public static void Main()
+ public static void Run()
{
foreach (object value in Enum.GetValues(typeof(SignMagnitude)))
{
diff --git a/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs b/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
index 6f4dd70d499..24eb109b11d 100644
--- a/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
+++ b/snippets/csharp/System/Enum/GetValues/getvalues_reflectiononly.cs
@@ -2,9 +2,9 @@
using System;
using System.Reflection;
-public class Example
+public class ReflectionOnlyGetValuesExample
{
- public static void Main()
+ public static void Run()
{
Assembly assem = Assembly.ReflectionOnlyLoadFrom(@".\Enumerations.dll");
Type typ = assem.GetType("Pets");
diff --git a/snippets/csharp/System/Enum/HasFlag/Program.cs b/snippets/csharp/System/Enum/HasFlag/Program.cs
new file mode 100644
index 00000000000..05040ee1c00
--- /dev/null
+++ b/snippets/csharp/System/Enum/HasFlag/Program.cs
@@ -0,0 +1,2 @@
+PetsHasFlagExample.Run();
+DinnerItemsHasFlagExample.Run();
diff --git a/snippets/csharp/System/Enum/HasFlag/Project.csproj b/snippets/csharp/System/Enum/HasFlag/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Enum/HasFlag/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Enum/HasFlag/hasflag0.cs b/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
index c7631b299ff..21b06887e02 100644
--- a/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
+++ b/snippets/csharp/System/Enum/HasFlag/hasflag0.cs
@@ -12,9 +12,9 @@ public enum Pets
Other = 16
}
-public class Example
+public class PetsHasFlagExample
{
- public static void Main()
+ public static void Run()
{
Pets[] petsInFamilies = { Pets.None, Pets.Dog | Pets.Cat, Pets.Dog };
int familiesWithoutPets = 0;
diff --git a/snippets/csharp/System/Enum/HasFlag/hasflag1.cs b/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
index 0df90c8021c..4467c0b0fe9 100644
--- a/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
+++ b/snippets/csharp/System/Enum/HasFlag/hasflag1.cs
@@ -13,9 +13,9 @@ public enum DinnerItems
BarBeverage = 32
}
-public class Example
+public class DinnerItemsHasFlagExample
{
- public static void Main()
+ public static void Run()
{
DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
DinnerItems.Beverage | DinnerItems.Dessert;
diff --git a/snippets/csharp/System/Enum/IsDefined/Program.cs b/snippets/csharp/System/Enum/IsDefined/Program.cs
new file mode 100644
index 00000000000..75d97efddb7
--- /dev/null
+++ b/snippets/csharp/System/Enum/IsDefined/Program.cs
@@ -0,0 +1,2 @@
+PetTypeIsDefinedExample.Run();
+PetsIsDefinedExample.Run();
diff --git a/snippets/csharp/System/Enum/IsDefined/Project.csproj b/snippets/csharp/System/Enum/IsDefined/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Enum/IsDefined/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
index 2abe64176d8..1cb496f3b4e 100644
--- a/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
+++ b/snippets/csharp/System/Enum/IsDefined/isdefined1.cs
@@ -7,9 +7,9 @@ public enum PetType
None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
};
-public class Example
+public class PetTypeIsDefinedExample
{
- public static void Main()
+ public static void Run()
{
object value;
diff --git a/snippets/csharp/System/Enum/IsDefined/isdefined2.cs b/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
index 45e29de6ac9..330777a7558 100644
--- a/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
+++ b/snippets/csharp/System/Enum/IsDefined/isdefined2.cs
@@ -8,9 +8,9 @@ public enum Pets
Rodent = 8, Other = 16
};
-public class Example
+public class PetsIsDefinedExample
{
- public static void Main()
+ public static void Run()
{
Pets value = Pets.Dog | Pets.Cat;
Console.WriteLine($"{value:D} Exists: {Pets.IsDefined(typeof(Pets), value)}");
diff --git a/snippets/csharp/System/Enum/Parse/EnumParse.cs b/snippets/csharp/System/Enum/Parse/EnumParse.cs
index 7d22c3500d5..fa43b9df020 100644
--- a/snippets/csharp/System/Enum/Parse/EnumParse.cs
+++ b/snippets/csharp/System/Enum/Parse/EnumParse.cs
@@ -6,7 +6,7 @@ public class ParseTest
[Flags]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
- public static void Main()
+ public static void Run()
{
Console.WriteLine("The entries of the Colors enumeration are:");
foreach (string colorName in Enum.GetNames(typeof(Colors)))
diff --git a/snippets/csharp/System/Enum/Parse/ParseExample1.cs b/snippets/csharp/System/Enum/Parse/ParseExample1.cs
index e6253e74bc2..18c0bf4e17f 100644
--- a/snippets/csharp/System/Enum/Parse/ParseExample1.cs
+++ b/snippets/csharp/System/Enum/Parse/ParseExample1.cs
@@ -1,19 +1,19 @@
//
using System;
-[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum CaseSensitiveColors { None = 0, Red = 1, Green = 2, Blue = 4 };
-public class Example
+public class CaseSensitiveParseExample
{
- public static void Main()
+ public static void Run()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
try
{
- Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ CaseSensitiveColors colorValue = (CaseSensitiveColors)Enum.Parse(typeof(CaseSensitiveColors), colorString);
+ if (Enum.IsDefined(typeof(CaseSensitiveColors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
diff --git a/snippets/csharp/System/Enum/Parse/ParseExample2.cs b/snippets/csharp/System/Enum/Parse/ParseExample2.cs
index 7316f695b37..8d04e2447fc 100644
--- a/snippets/csharp/System/Enum/Parse/ParseExample2.cs
+++ b/snippets/csharp/System/Enum/Parse/ParseExample2.cs
@@ -1,19 +1,19 @@
//
using System;
-[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum IgnoreCaseColors { None = 0, Red = 1, Green = 2, Blue = 4 };
-public class Example
+public class IgnoreCaseParseExample
{
- public static void Main()
+ public static void Run()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
try
{
- Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString, true);
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ IgnoreCaseColors colorValue = (IgnoreCaseColors)Enum.Parse(typeof(IgnoreCaseColors), colorString, true);
+ if (Enum.IsDefined(typeof(IgnoreCaseColors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
diff --git a/snippets/csharp/System/Enum/Parse/Program.cs b/snippets/csharp/System/Enum/Parse/Program.cs
new file mode 100644
index 00000000000..61618afce08
--- /dev/null
+++ b/snippets/csharp/System/Enum/Parse/Program.cs
@@ -0,0 +1,3 @@
+ParseTest.Run();
+CaseSensitiveParseExample.Run();
+IgnoreCaseParseExample.Run();
diff --git a/snippets/csharp/System/Enum/Parse/Project.csproj b/snippets/csharp/System/Enum/Parse/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Enum/Parse/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/Program.cs b/snippets/csharp/System/Enum/TryParseTEnum/Program.cs
new file mode 100644
index 00000000000..5135a5de554
--- /dev/null
+++ b/snippets/csharp/System/Enum/TryParseTEnum/Program.cs
@@ -0,0 +1,2 @@
+CaseSensitiveTryParseExample.Run();
+IgnoreCaseTryParseExample.Run();
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/Project.csproj b/snippets/csharp/System/Enum/TryParseTEnum/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Enum/TryParseTEnum/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs b/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
index 91274c5dfef..c105ec7da0a 100644
--- a/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
+++ b/snippets/csharp/System/Enum/TryParseTEnum/tryparse1.cs
@@ -1,18 +1,18 @@
//
using System;
-[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum CaseSensitiveColors { None = 0, Red = 1, Green = 2, Blue = 4 };
-public class Example
+public class CaseSensitiveTryParseExample
{
- public static void Main()
+ public static void Run()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
- Colors colorValue;
+ CaseSensitiveColors colorValue;
if (Enum.TryParse(colorString, out colorValue))
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ if (Enum.IsDefined(typeof(CaseSensitiveColors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
diff --git a/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs b/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
index 9ebacd38f1d..b95c270ed19 100644
--- a/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
+++ b/snippets/csharp/System/Enum/TryParseTEnum/tryparse2.cs
@@ -1,18 +1,18 @@
//
using System;
-[Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };
+[Flags] enum IgnoreCaseColors { None = 0, Red = 1, Green = 2, Blue = 4 };
-public class Example
+public class IgnoreCaseTryParseExample
{
- public static void Main()
+ public static void Run()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
- Colors colorValue;
+ IgnoreCaseColors colorValue;
if (Enum.TryParse(colorString, true, out colorValue))
- if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
+ if (Enum.IsDefined(typeof(IgnoreCaseColors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine($"{colorString} is not an underlying value of the Colors enumeration.");
diff --git a/snippets/csharp/System/Environment/ExitCode/Program.cs b/snippets/csharp/System/Environment/ExitCode/Program.cs
new file mode 100644
index 00000000000..811711b93d2
--- /dev/null
+++ b/snippets/csharp/System/Environment/ExitCode/Program.cs
@@ -0,0 +1,2 @@
+ExitCodePropertyExample.Run();
+_ = ExitCodeReturnExample.Run();
diff --git a/snippets/csharp/System/Environment/ExitCode/Project.csproj b/snippets/csharp/System/Environment/ExitCode/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Environment/ExitCode/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Environment/ExitCode/double.cs b/snippets/csharp/System/Environment/ExitCode/double.cs
index 8fd7efaff5a..b22b898ec36 100644
--- a/snippets/csharp/System/Environment/ExitCode/double.cs
+++ b/snippets/csharp/System/Environment/ExitCode/double.cs
@@ -2,13 +2,13 @@
using System;
using System.Numerics;
-public class Example
+public class ExitCodePropertyExample
{
private const int ERROR_BAD_ARGUMENTS = 0xA0;
private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
private const int ERROR_INVALID_COMMAND_LINE = 0x667;
- public static void Main()
+ public static void Run()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length == 1)
diff --git a/snippets/csharp/System/Environment/ExitCode/double1.cs b/snippets/csharp/System/Environment/ExitCode/double1.cs
index 58fd80c9fa4..f3bdb23eb8c 100644
--- a/snippets/csharp/System/Environment/ExitCode/double1.cs
+++ b/snippets/csharp/System/Environment/ExitCode/double1.cs
@@ -2,14 +2,14 @@
using System;
using System.Numerics;
-public class Example
+public class ExitCodeReturnExample
{
private const int ERROR_SUCCESS = 0;
private const int ERROR_BAD_ARGUMENTS = 0xA0;
private const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
private const int ERROR_INVALID_COMMAND_LINE = 0x667;
- public static int Main()
+ public static int Run()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length == 1)
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/Program.cs b/snippets/csharp/System/Environment/GetEnvironmentVariable/Program.cs
new file mode 100644
index 00000000000..88c2b9ee688
--- /dev/null
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/Program.cs
@@ -0,0 +1,2 @@
+GetEnvironmentVariableExample.Run();
+Sample.Run();
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/Project.csproj b/snippets/csharp/System/Environment/GetEnvironmentVariable/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs b/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
index 6b2823b05a5..37e27518d93 100644
--- a/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/getenvironmentvariableex1.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class GetEnvironmentVariableExample
{
- public static void Main()
+ public static void Run()
{
string value;
bool toDelete = false;
diff --git a/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs b/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
index 8d217a23ef1..c9ada8a20ca 100644
--- a/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
+++ b/snippets/csharp/System/Environment/GetEnvironmentVariable/gsev.cs
@@ -4,7 +4,7 @@
class Sample
{
- public static void Main()
+ public static void Run()
{
// Environment variable names for default, process, user, and machine targets.
string defaultEnvVar = nameof(defaultEnvVar);