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..ab56bef4f2c 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..e564abe4a5a 100644 --- a/snippets/csharp/System/Console/Overview/example3.cs +++ b/snippets/csharp/System/Console/Overview/example3.cs @@ -7,159 +7,157 @@ 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($"0x{end:X5} is outside the upper range of Unicode code points (0x{upperRange:X5})"); + + // 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..aef9b651a4b 100644 --- a/snippets/csharp/System/Console/Overview/setfont1.cs +++ b/snippets/csharp/System/Console/Overview/setfont1.cs @@ -4,77 +4,83 @@ 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; + fixed (char* faceName = newInfo.FaceName) + { + Marshal.Copy(fontName.ToCharArray(), 0, (IntPtr)faceName, fontName.Length); + faceName[fontName.Length] = '\0'; + } + // 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)}"); + } } //