From a01a296a0ae00c2515513152f820ee92586c07c1 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 13 Aug 2026 13:56:09 -0700 Subject: [PATCH 1/9] Modernize C# code snippets - System/S* (#12970) --- .../csharp/System/SByte/MaxValue/MaxValue1.cs | 65 ++- snippets/csharp/System/SByte/Parse/Program.cs | 4 + .../csharp/System/SByte/Parse/Project.csproj | 6 + snippets/csharp/System/SByte/Parse/parse_1.cs | 135 +++--- .../csharp/System/SByte/Parse/parseex1.cs | 72 +-- .../csharp/System/SByte/Parse/parseex2.cs | 87 ++-- .../csharp/System/SByte/Parse/parseex3.cs | 56 +-- .../csharp/System/SByte/ToString/Program.cs | 4 + .../System/SByte/ToString/Project.csproj | 6 + .../csharp/System/SByte/ToString/tostring2.cs | 28 +- .../csharp/System/SByte/ToString/tostring3.cs | 44 +- .../csharp/System/SByte/ToString/tostring4.cs | 36 +- .../csharp/System/SByte/ToString/tostring5.cs | 53 ++- .../csharp/System/SByte/TryParse/TryParse1.cs | 54 +-- .../csharp/System/SByte/TryParse/tryparse2.cs | 94 ++-- .../System/Single/CompareTo/compareto2.cs | 22 +- .../System/Single/CompareTo/compareto3.cs | 22 +- .../System/Single/CompareTo/singlesample.cs | 95 ++-- .../Single/Epsilon/SingleEquals_25051.cs | 130 +++--- .../csharp/System/Single/Epsilon/epsilon.cs | 30 +- .../csharp/System/Single/Epsilon/epsilon1.cs | 66 +-- .../csharp/System/Single/Equals/equalsabs1.cs | 66 +-- .../System/Single/Equals/equalsoverl.cs | 76 ++-- .../System/Single/MaxValue/maxvalueex.cs | 18 +- .../System/Single/MinValue/minvalueex.cs | 18 +- snippets/csharp/System/Single/NaN/Program.cs | 2 + .../csharp/System/Single/NaN/Project.csproj | 6 + snippets/csharp/System/Single/NaN/nan1.cs | 55 ++- .../csharp/System/Single/NaN/single.nan4.cs | 38 +- .../System/Single/Overview/comparison1.cs | 14 +- .../System/Single/Overview/comparison2.cs | 4 +- .../System/Single/Overview/comparison4.cs | 6 +- .../csharp/System/Single/Overview/convert1.cs | 20 +- .../csharp/System/Single/Overview/convert2.cs | 20 +- .../System/Single/Overview/exceptional2.cs | 10 +- .../System/Single/Overview/precisionlist1.cs | 8 +- .../System/Single/Overview/precisionlist3.cs | 8 +- .../System/Single/Overview/representation1.cs | 8 +- .../System/Single/Overview/representation2.cs | 4 +- .../csharp/System/Single/Parse/Program.cs | 3 + .../csharp/System/Single/Parse/Project.csproj | 6 + snippets/csharp/System/Single/Parse/parse1.cs | 45 +- snippets/csharp/System/Single/Parse/parse2.cs | 106 +++-- snippets/csharp/System/Single/Parse/parse3.cs | 77 ++-- .../System/Single/ToString/ToString1.cs | 409 +++++++++--------- .../System/Single/ToString/ToString7.cs | 20 +- .../System/Single/TryParse/tryparse1.cs | 172 ++++---- .../csharp/System/Span.Enumerator/Program.cs | 8 +- .../csharp/System/Span.Enumerator/Program2.cs | 4 +- .../csharp/System/Span/Overview/program.cs | 12 +- snippets/csharp/System/Span/Slice/Program.cs | 4 +- snippets/csharp/System/Span/Slice/Program2.cs | 2 +- .../Overview/example1a.cs | 40 +- 53 files changed, 1213 insertions(+), 1185 deletions(-) create mode 100644 snippets/csharp/System/SByte/Parse/Program.cs create mode 100644 snippets/csharp/System/SByte/Parse/Project.csproj create mode 100644 snippets/csharp/System/SByte/ToString/Program.cs create mode 100644 snippets/csharp/System/SByte/ToString/Project.csproj create mode 100644 snippets/csharp/System/Single/NaN/Program.cs create mode 100644 snippets/csharp/System/Single/NaN/Project.csproj create mode 100644 snippets/csharp/System/Single/Parse/Program.cs create mode 100644 snippets/csharp/System/Single/Parse/Project.csproj diff --git a/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs b/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs index ddf3b1c4b76..4070fb14c4a 100644 --- a/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs +++ b/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs @@ -2,39 +2,36 @@ public class SByteRangeExample { - public static void Main() - { - // - long longValue = -130; - sbyte byteValue; - - if (longValue <= sbyte.MaxValue && - longValue >= sbyte.MinValue) - { - byteValue = (sbyte) longValue; - Console.WriteLine("Converted long integer value to {0}.", byteValue); - } - else - { - sbyte rangeLimit; - string relationship; - - if (longValue > sbyte.MaxValue) - { - rangeLimit = sbyte.MaxValue; - relationship = "greater"; - } - else - { - rangeLimit = sbyte.MinValue; - relationship = "less"; - } + public static void Main() + { + // + long longValue = -130; + sbyte byteValue; - Console.WriteLine("Conversion failure: {0:n0} is {1} than {2}.", - longValue, - relationship, - rangeLimit); - } - // - } + if (longValue <= sbyte.MaxValue && + longValue >= sbyte.MinValue) + { + byteValue = (sbyte)longValue; + Console.WriteLine($"Converted long integer value to {byteValue}."); + } + else + { + sbyte rangeLimit; + string relationship; + + if (longValue > sbyte.MaxValue) + { + rangeLimit = sbyte.MaxValue; + relationship = "greater"; + } + else + { + rangeLimit = sbyte.MinValue; + relationship = "less"; + } + + Console.WriteLine($"Conversion failure: {longValue:n0} is {relationship} than {rangeLimit}."); + } + // + } } diff --git a/snippets/csharp/System/SByte/Parse/Program.cs b/snippets/csharp/System/SByte/Parse/Program.cs new file mode 100644 index 00000000000..ddcbf34259a --- /dev/null +++ b/snippets/csharp/System/SByte/Parse/Program.cs @@ -0,0 +1,4 @@ +SByteParseDefaultExample.Run(); +SByteParseStylesExample.Run(); +SByteConversion.Run(); +SByteParseProviderExample.Run(); diff --git a/snippets/csharp/System/SByte/Parse/Project.csproj b/snippets/csharp/System/SByte/Parse/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/SByte/Parse/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/SByte/Parse/parse_1.cs b/snippets/csharp/System/SByte/Parse/parse_1.cs index 270d3a5c0cb..2b0b413595d 100644 --- a/snippets/csharp/System/SByte/Parse/parse_1.cs +++ b/snippets/csharp/System/SByte/Parse/parse_1.cs @@ -4,77 +4,74 @@ public class SByteConversion { - NumberFormatInfo provider = NumberFormatInfo.CurrentInfo; + NumberFormatInfo provider = NumberFormatInfo.CurrentInfo; - public static void Main() - { - string stringValue; - NumberStyles style; + public static void Run() + { + string stringValue; + NumberStyles style; - stringValue = " 123 "; - style = NumberStyles.None; - CallParseOperation(stringValue, style); - - stringValue = "000,000,123"; - style = NumberStyles.Integer | NumberStyles.AllowThousands; - CallParseOperation(stringValue, style); - - stringValue = "-100"; - style = NumberStyles.AllowLeadingSign; - CallParseOperation(stringValue, style); - - stringValue = "100-"; - style = NumberStyles.AllowLeadingSign; - CallParseOperation(stringValue, style); - - stringValue = "100-"; - style = NumberStyles.AllowTrailingSign; - CallParseOperation(stringValue, style); - - stringValue = "$100"; - style = NumberStyles.AllowCurrencySymbol; - CallParseOperation(stringValue, style); - - style = NumberStyles.Integer; - CallParseOperation(stringValue, style); - - style = NumberStyles.AllowDecimalPoint; - CallParseOperation("100.0", style); - - stringValue = "1e02"; - style = NumberStyles.AllowExponent; - CallParseOperation(stringValue, style); - - stringValue = "(100)"; - style = NumberStyles.AllowParentheses; - CallParseOperation(stringValue, style); - } - - private static void CallParseOperation(string stringValue, - NumberStyles style) - { - sbyte number; - - if (stringValue == null) - Console.WriteLine("Cannot parse a null string..."); - - try - { - number = sbyte.Parse(stringValue, style); - Console.WriteLine("SByte.Parse('{0}', {1})) = {2}", - stringValue, style, number); - } - catch (FormatException) - { - Console.WriteLine("'{0}' and {1} throw a FormatException", - stringValue, style); - } - catch (OverflowException) - { - Console.WriteLine("'{0}' is outside the range of a signed byte", - stringValue); - } - } + stringValue = " 123 "; + style = NumberStyles.None; + CallParseOperation(stringValue, style); + + stringValue = "000,000,123"; + style = NumberStyles.Integer | NumberStyles.AllowThousands; + CallParseOperation(stringValue, style); + + stringValue = "-100"; + style = NumberStyles.AllowLeadingSign; + CallParseOperation(stringValue, style); + + stringValue = "100-"; + style = NumberStyles.AllowLeadingSign; + CallParseOperation(stringValue, style); + + stringValue = "100-"; + style = NumberStyles.AllowTrailingSign; + CallParseOperation(stringValue, style); + + stringValue = "$100"; + style = NumberStyles.AllowCurrencySymbol; + CallParseOperation(stringValue, style); + + style = NumberStyles.Integer; + CallParseOperation(stringValue, style); + + style = NumberStyles.AllowDecimalPoint; + CallParseOperation("100.0", style); + + stringValue = "1e02"; + style = NumberStyles.AllowExponent; + CallParseOperation(stringValue, style); + + stringValue = "(100)"; + style = NumberStyles.AllowParentheses; + CallParseOperation(stringValue, style); + } + + private static void CallParseOperation(string stringValue, + NumberStyles style) + { + sbyte number; + + if (stringValue == null) + Console.WriteLine("Cannot parse a null string..."); + + try + { + number = sbyte.Parse(stringValue, style); + Console.WriteLine($"SByte.Parse('{stringValue}', {style}) = {number}"); + } + catch (FormatException) + { + Console.WriteLine($"'{stringValue}' and {style} throw a FormatException"); + } + catch (OverflowException) + { + Console.WriteLine($"'{stringValue}' is outside the range of a signed byte"); + } + } } // The example displays the following information to the console: // ' 123 ' and None throw a FormatException diff --git a/snippets/csharp/System/SByte/Parse/parseex1.cs b/snippets/csharp/System/SByte/Parse/parseex1.cs index 7ea26bee91c..b06f1e0d1de 100644 --- a/snippets/csharp/System/SByte/Parse/parseex1.cs +++ b/snippets/csharp/System/SByte/Parse/parseex1.cs @@ -1,40 +1,40 @@ using System; -public class Example +public class SByteParseDefaultExample { - public static void Main() - { - // - // Define an array of numeric strings. - string[] values = { "-16", " -3", "+ 12", " +12 ", " 12 ", - "+120", "(103)", "192", "-160" }; - - // Parse each string and display the result. - foreach (string value in values) - { - try { - Console.WriteLine("Converted '{0}' to the SByte value {1}.", - value, SByte.Parse(value)); - } - catch (FormatException) { - Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.", - value); - } - catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of the SByte type.", - value); - } - } - // The example displays the following output: - // Converted '-16' to the SByte value -16. - // Converted ' -3' to the SByte value -3. - // '+ 12' cannot be parsed successfully by SByte type. - // Converted ' +12 ' to the SByte value 12. - // Converted ' 12 ' to the SByte value 12. - // Converted '+120' to the SByte value 120. - // '(103)' cannot be parsed successfully by SByte type. - // '192' is out of range of the SByte type. - // '-160' is out of range of the SByte type. - // - } + public static void Run() + { + // + // Define an array of numeric strings. + string[] values = ["-16", " -3", "+ 12", " +12 ", " 12 ", + "+120", "(103)", "192", "-160"]; + + // Parse each string and display the result. + foreach (string value in values) + { + try + { + Console.WriteLine($"Converted '{value}' to the SByte value {sbyte.Parse(value)}."); + } + catch (FormatException) + { + Console.WriteLine($"'{value}' cannot be parsed successfully by SByte type."); + } + catch (OverflowException) + { + Console.WriteLine($"'{value}' is out of range of the SByte type."); + } + } + // The example displays the following output: + // Converted '-16' to the SByte value -16. + // Converted ' -3' to the SByte value -3. + // '+ 12' cannot be parsed successfully by SByte type. + // Converted ' +12 ' to the SByte value 12. + // Converted ' 12 ' to the SByte value 12. + // Converted '+120' to the SByte value 120. + // '(103)' cannot be parsed successfully by SByte type. + // '192' is out of range of the SByte type. + // '-160' is out of range of the SByte type. + // + } } diff --git a/snippets/csharp/System/SByte/Parse/parseex2.cs b/snippets/csharp/System/SByte/Parse/parseex2.cs index 180b56a6661..133f250ba97 100644 --- a/snippets/csharp/System/SByte/Parse/parseex2.cs +++ b/snippets/csharp/System/SByte/Parse/parseex2.cs @@ -2,55 +2,60 @@ using System; using System.Globalization; -public class Example +public class SByteParseStylesExample { - public static void Main() - { - NumberStyles style; - sbyte number; + public static void Run() + { + NumberStyles style; + sbyte number; - // Parse value with no styles allowed. - string[] values1 = { " 121 ", "121", "-121" }; - style = NumberStyles.None; - Console.WriteLine("Styles: {0}", style.ToString()); - foreach (string value in values1) - { - try { - number = SByte.Parse(value, style); - Console.WriteLine(" Converted '{0}' to {1}.", value, number); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - } - Console.WriteLine(); - - // Parse value with trailing sign. - style = NumberStyles.Integer | NumberStyles.AllowTrailingSign; - string[] values2 = { " 103+", " 103 +", "+103", "(103)", " +103 " }; - Console.WriteLine("Styles: {0}", style.ToString()); - foreach (string value in values2) - { - try { - number = SByte.Parse(value, style); - Console.WriteLine(" Converted '{0}' to {1}.", value, number); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the SByte type.", value); - } - } - Console.WriteLine(); - } + // Parse value with no styles allowed. + string[] values1 = [" 121 ", "121", "-121"]; + style = NumberStyles.None; + Console.WriteLine($"Styles: {style}"); + foreach (string value in values1) + { + try + { + number = sbyte.Parse(value, style); + Console.WriteLine($" Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + } + Console.WriteLine(); + + // Parse value with trailing sign. + style = NumberStyles.Integer | NumberStyles.AllowTrailingSign; + string[] values2 = [" 103+", " 103 +", "+103", "(103)", " +103 "]; + Console.WriteLine($"Styles: {style}"); + foreach (string value in values2) + { + try + { + number = sbyte.Parse(value, style); + Console.WriteLine($" Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the SByte type."); + } + } + Console.WriteLine(); + } } // The example displays the following output: // Styles: None // Unable to parse ' 121 '. // Converted '121' to 121. // Unable to parse '-121'. -// +// // Styles: Integer, AllowTrailingSign // Converted ' 103+' to 103. // Converted ' 103 +' to 103. diff --git a/snippets/csharp/System/SByte/Parse/parseex3.cs b/snippets/csharp/System/SByte/Parse/parseex3.cs index bcf7c78017b..1111e07c903 100644 --- a/snippets/csharp/System/SByte/Parse/parseex3.cs +++ b/snippets/csharp/System/SByte/Parse/parseex3.cs @@ -2,34 +2,38 @@ using System; using System.Globalization; -public class Example +public class SByteParseProviderExample { - public static void Main() - { - NumberFormatInfo nf = new NumberFormatInfo(); - nf.NegativeSign = "~"; - - string[] values = { "-103", "+12", "~16", " 1", "~255" }; - IFormatProvider[] providers = { nf, CultureInfo.InvariantCulture }; - - foreach (IFormatProvider provider in providers) - { - Console.WriteLine("Conversions using {0}:", ((object) provider).GetType().Name); - foreach (string value in values) - { - try { - Console.WriteLine(" Converted '{0}' to {1}.", - value, SByte.Parse(value, provider)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the SByte type.", value); + public static void Run() + { + NumberFormatInfo nf = new() + { + NegativeSign = "~" + }; + + string[] values = ["-103", "+12", "~16", " 1", "~255"]; + IFormatProvider[] providers = [nf, CultureInfo.InvariantCulture]; + + foreach (IFormatProvider provider in providers) + { + Console.WriteLine($"Conversions using {((object)provider).GetType().Name}:"); + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {sbyte.Parse(value, provider)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the SByte type."); + } } - } - } - } + } + } } // The example displays the following output: // Conversions using NumberFormatInfo: diff --git a/snippets/csharp/System/SByte/ToString/Program.cs b/snippets/csharp/System/SByte/ToString/Program.cs new file mode 100644 index 00000000000..76bece4a57b --- /dev/null +++ b/snippets/csharp/System/SByte/ToString/Program.cs @@ -0,0 +1,4 @@ +SByteToStringDefaultExample.Run(); +SByteToStringProviderExample.Run(); +SByteToStringFormatExample.Run(); +SByteToStringCultureExample.Run(); diff --git a/snippets/csharp/System/SByte/ToString/Project.csproj b/snippets/csharp/System/SByte/ToString/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/SByte/ToString/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/SByte/ToString/tostring2.cs b/snippets/csharp/System/SByte/ToString/tostring2.cs index f42f7cb1e20..06d455317b5 100644 --- a/snippets/csharp/System/SByte/ToString/tostring2.cs +++ b/snippets/csharp/System/SByte/ToString/tostring2.cs @@ -1,20 +1,20 @@ // using System; -public class Example +public class SByteToStringDefaultExample { - public static void Main() - { - sbyte value = -123; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); // Displays -123 - // Display value using some standard format specifiers. - Console.WriteLine(value.ToString("G")); // Displays -123 - Console.WriteLine(value.ToString("C")); // Displays ($-123.00) - Console.WriteLine(value.ToString("D")); // Displays -123 - Console.WriteLine(value.ToString("F")); // Displays -123.00 - Console.WriteLine(value.ToString("N")); // Displays -123.00 - Console.WriteLine(value.ToString("X")); // Displays 85 - } + public static void Run() + { + sbyte value = -123; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); // Displays -123 + // Display value using some standard format specifiers. + Console.WriteLine(value.ToString("G")); // Displays -123 + Console.WriteLine(value.ToString("C")); // Displays ($-123.00) + Console.WriteLine(value.ToString("D")); // Displays -123 + Console.WriteLine(value.ToString("F")); // Displays -123.00 + Console.WriteLine(value.ToString("N")); // Displays -123.00 + Console.WriteLine(value.ToString("X")); // Displays 85 + } } // diff --git a/snippets/csharp/System/SByte/ToString/tostring3.cs b/snippets/csharp/System/SByte/ToString/tostring3.cs index cb22ccd11f6..7a815890f84 100644 --- a/snippets/csharp/System/SByte/ToString/tostring3.cs +++ b/snippets/csharp/System/SByte/ToString/tostring3.cs @@ -2,36 +2,38 @@ using System; using System.Globalization; -public class Example +public class SByteToStringProviderExample { - public static void Main() - { - // Define a custom NumberFormatInfo object with "~" as its negative sign. - NumberFormatInfo nfi = new NumberFormatInfo(); - nfi.NegativeSign = "~"; - - // Initialize an array of SByte values. - sbyte[] bytes = { -122, 17, 124 }; + public static void Run() + { + // Define a custom NumberFormatInfo object with "~" as its negative sign. + NumberFormatInfo nfi = new() + { + NegativeSign = "~" + }; - // Display the formatted result using the custom provider. - Console.WriteLine("Using the custom NumberFormatInfo object:"); - foreach (sbyte value in bytes) - Console.WriteLine(value.ToString(nfi)); + // Initialize an array of SByte values. + sbyte[] bytes = [-122, 17, 124]; - Console.WriteLine(); - - // Display the formatted result using the invariant culture. - Console.WriteLine("Using the invariant culture:"); - foreach (sbyte value in bytes) - Console.WriteLine(value.ToString(NumberFormatInfo.InvariantInfo)); - } + // Display the formatted result using the custom provider. + Console.WriteLine("Using the custom NumberFormatInfo object:"); + foreach (sbyte value in bytes) + Console.WriteLine(value.ToString(nfi)); + + Console.WriteLine(); + + // Display the formatted result using the invariant culture. + Console.WriteLine("Using the invariant culture:"); + foreach (sbyte value in bytes) + Console.WriteLine(value.ToString(NumberFormatInfo.InvariantInfo)); + } } // The example displays the following output: // Using the custom NumberFormatInfo object: // ~122 // 17 // 124 -// +// // Using the invariant culture: // -122 // 17 diff --git a/snippets/csharp/System/SByte/ToString/tostring4.cs b/snippets/csharp/System/SByte/ToString/tostring4.cs index a6306b99045..92791063275 100644 --- a/snippets/csharp/System/SByte/ToString/tostring4.cs +++ b/snippets/csharp/System/SByte/ToString/tostring4.cs @@ -1,23 +1,23 @@ // using System; -using System.Globalization; -public class Example + +public class SByteToStringFormatExample { - public static void Main() - { - sbyte[] values = { -124, 0, 118 }; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "00.0", "#.0", - "000;(0);**Zero**" }; - - foreach (sbyte value in values) - { - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - Console.WriteLine(); - } - } + public static void Run() + { + sbyte[] values = [-124, 0, 118]; + string[] specifiers = ["G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "00.0", "#.0", + "000;(0);**Zero**"]; + + foreach (sbyte value in values) + { + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G: -124 @@ -32,7 +32,7 @@ public static void Main() // 00.0: -124.0 // #.0: -124.0 // 000;(0);**Zero**: (124) -// +// // G: 0 // C: $0.00 // D3: 000 @@ -45,7 +45,7 @@ public static void Main() // 00.0: 00.0 // #.0: .0 // 000;(0);**Zero**: **Zero** -// +// // G: 118 // C: $118.00 // D3: 118 diff --git a/snippets/csharp/System/SByte/ToString/tostring5.cs b/snippets/csharp/System/SByte/ToString/tostring5.cs index 5f009ae9f53..cc55318e1ff 100644 --- a/snippets/csharp/System/SByte/ToString/tostring5.cs +++ b/snippets/csharp/System/SByte/ToString/tostring5.cs @@ -2,58 +2,55 @@ using System; using System.Globalization; -public class Example +public class SByteToStringCultureExample { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("fr-FR"), - CultureInfo.CreateSpecificCulture("es-ES") }; - sbyte positiveNumber = 119; - sbyte negativeNumber = -45; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 16} {3, 16}", - specifier, culture.Name, - positiveNumber.ToString(specifier, culture), - negativeNumber.ToString(specifier, culture)); - Console.WriteLine(); - } - } + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = [CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("fr-FR"), + CultureInfo.CreateSpecificCulture("es-ES")]; + sbyte positiveNumber = 119; + sbyte negativeNumber = -45; + string[] specifiers = ["G", "C", "D4", "E2", "F", "N", "P", "X2"]; + + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {positiveNumber.ToString(specifier, culture),16} {negativeNumber.ToString(specifier, culture),16}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 119 -45 // G format using fr-FR culture: 119 -45 // G format using es-ES culture: 119 -45 -// +// // C format using en-US culture: $119.00 ($45.00) // C format using fr-FR culture: 119,00 € -45,00 € // C format using es-ES culture: 119,00 € -45,00 € -// +// // D4 format using en-US culture: 0119 -0045 // D4 format using fr-FR culture: 0119 -0045 // D4 format using es-ES culture: 0119 -0045 -// +// // E2 format using en-US culture: 1.19E+002 -4.50E+001 // E2 format using fr-FR culture: 1,19E+002 -4,50E+001 // E2 format using es-ES culture: 1,19E+002 -4,50E+001 -// +// // F format using en-US culture: 119.00 -45.00 // F format using fr-FR culture: 119,00 -45,00 // F format using es-ES culture: 119,00 -45,00 -// +// // N format using en-US culture: 119.00 -45.00 // N format using fr-FR culture: 119,00 -45,00 // N format using es-ES culture: 119,00 -45,00 -// +// // P format using en-US culture: 11,900.00 % -4,500.00 % // P format using fr-FR culture: 11 900,00 % -4 500,00 % // P format using es-ES culture: 11.900,00 % -4.500,00 % -// +// // X2 format using en-US culture: 77 D3 // X2 format using fr-FR culture: 77 D3 // X2 format using es-ES culture: 77 D3 diff --git a/snippets/csharp/System/SByte/TryParse/TryParse1.cs b/snippets/csharp/System/SByte/TryParse/TryParse1.cs index 5b849932e1c..12bc0215ccd 100644 --- a/snippets/csharp/System/SByte/TryParse/TryParse1.cs +++ b/snippets/csharp/System/SByte/TryParse/TryParse1.cs @@ -2,31 +2,31 @@ public class ParseSByte { - public static void Main() - { - // - string[] numericStrings = {"-3.6", "12.8", "+16.7", " 3 ", "(17)", - "-17", "+12", "18-", "987", "1,024", " 127 "}; - sbyte number; - foreach (string numericString in numericStrings) - { - if (sbyte.TryParse(numericString, out number)) - Console.WriteLine("Converted '{0}' to {1}.", numericString, number); - else - Console.WriteLine("Cannot convert '{0}' to an SByte.", numericString); - } - // The example displays the following output to the console: - // Cannot convert '-3.6' to an SByte. - // Cannot convert '12.8' to an SByte. - // Cannot convert '+16.7' to an SByte. - // Converted ' 3 ' to 3. - // Cannot convert '(17)' to an SByte. - // Converted '-17' to -17. - // Converted '+12' to 12. - // Cannot convert '18-' to an SByte. - // Cannot convert '987' to an SByte. - // Cannot convert '1,024' to an SByte. - // Converted ' 127 ' to 127. - // - } + public static void Main() + { + // + string[] numericStrings = ["-3.6", "12.8", "+16.7", " 3 ", "(17)", + "-17", "+12", "18-", "987", "1,024", " 127 "]; + sbyte number; + foreach (string numericString in numericStrings) + { + if (sbyte.TryParse(numericString, out number)) + Console.WriteLine($"Converted '{numericString}' to {number}."); + else + Console.WriteLine($"Cannot convert '{numericString}' to an SByte."); + } + // The example displays the following output to the console: + // Cannot convert '-3.6' to an SByte. + // Cannot convert '12.8' to an SByte. + // Cannot convert '+16.7' to an SByte. + // Converted ' 3 ' to 3. + // Cannot convert '(17)' to an SByte. + // Converted '-17' to -17. + // Converted '+12' to 12. + // Cannot convert '18-' to an SByte. + // Cannot convert '987' to an SByte. + // Cannot convert '1,024' to an SByte. + // Converted ' 127 ' to 127. + // + } } diff --git a/snippets/csharp/System/SByte/TryParse/tryparse2.cs b/snippets/csharp/System/SByte/TryParse/tryparse2.cs index 7c7e7867421..a7c235d4a1a 100644 --- a/snippets/csharp/System/SByte/TryParse/tryparse2.cs +++ b/snippets/csharp/System/SByte/TryParse/tryparse2.cs @@ -4,54 +4,54 @@ public class Example { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "106"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-106"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "103.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "103.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Main() + { + string numericString; + NumberStyles styles; - numericString = "10E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "12E-01"; - CallTryParse(numericString, styles); - - numericString = "12E01"; - CallTryParse(numericString, styles); - - numericString = "C8"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - sbyte number; - bool result = SByte.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "106"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-106"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "103.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "103.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "12E-01"; + CallTryParse(numericString, styles); + + numericString = "12E01"; + CallTryParse(numericString, styles); + + numericString = "C8"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + sbyte number; + bool result = sbyte.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '106' to 106. diff --git a/snippets/csharp/System/Single/CompareTo/compareto2.cs b/snippets/csharp/System/Single/CompareTo/compareto2.cs index cdd6191ed77..1b6e27b4484 100644 --- a/snippets/csharp/System/Single/CompareTo/compareto2.cs +++ b/snippets/csharp/System/Single/CompareTo/compareto2.cs @@ -1,20 +1,20 @@ -// +// using System; public class Example2 { - public static void Main() - { - float value1 = 16.5457f; - float operand = 3.8899982f; - float value2 = value1 * operand / operand; - Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); - Console.WriteLine(); - Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); - } + public static void Main() + { + float value1 = 16.5457f; + float operand = 3.8899982f; + float value2 = value1 * operand / operand; + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); + Console.WriteLine(); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); + } } // The example displays the following output: // Comparing 16.5457 and 16.5457: -1 -// +// // Comparing 16.5457 and 16.545702: -1 // diff --git a/snippets/csharp/System/Single/CompareTo/compareto3.cs b/snippets/csharp/System/Single/CompareTo/compareto3.cs index 4d5b9b389fc..62892e15298 100644 --- a/snippets/csharp/System/Single/CompareTo/compareto3.cs +++ b/snippets/csharp/System/Single/CompareTo/compareto3.cs @@ -1,20 +1,20 @@ -// +// using System; public class Example { - public static void Main() - { - float value1 = 16.5457f; - float operand = 3.8899982f; - object value2 = value1 * operand / operand; - Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); - Console.WriteLine(); - Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); - } + public static void Main() + { + float value1 = 16.5457f; + float operand = 3.8899982f; + object value2 = value1 * operand / operand; + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); + Console.WriteLine(); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); + } } // The example displays the following output: // Comparing 16.5457 and 16.5457: -1 -// +// // Comparing 16.5457 and 16.545702: -1 // diff --git a/snippets/csharp/System/Single/CompareTo/singlesample.cs b/snippets/csharp/System/Single/CompareTo/singlesample.cs index 590776253ac..16cd7f9a717 100644 --- a/snippets/csharp/System/Single/CompareTo/singlesample.cs +++ b/snippets/csharp/System/Single/CompareTo/singlesample.cs @@ -2,18 +2,19 @@ namespace SingleSnippet { - class SingleSample { + class SingleSample + { public SingleSample() { - // - Single s = 4.55F; + // + float s = 4.55F; // - // - Console.WriteLine("A Single is of type {0}.", s.GetType().ToString()); + // + Console.WriteLine($"A Single is of type {s.GetType()}."); // - // + // bool done = false; string inp; do @@ -22,8 +23,8 @@ public SingleSample() inp = Console.ReadLine(); try { - s = Single.Parse(inp); - Console.WriteLine("You entered {0}.", s.ToString()); + s = float.Parse(inp); + Console.WriteLine($"You entered {s}."); done = true; } catch (FormatException) @@ -32,34 +33,34 @@ public SingleSample() } catch (Exception e) { - Console.WriteLine("An exception occurred while parsing your response: {0}", e.ToString()); + Console.WriteLine($"An exception occurred while parsing your response: {e}"); } } while (!done); // - // - if (s > Single.MaxValue) + // + if (s > float.MaxValue) { Console.WriteLine("Your number is larger than a Single."); } // - // - if (s < Single.MinValue) + // + if (s < float.MinValue) { Console.WriteLine("Your number is smaller than a Single."); } // - // - Console.WriteLine("Epsilon, or the permittivity of a vacuum, has value {0}", Single.Epsilon.ToString()); + // + Console.WriteLine($"Epsilon, or the permittivity of a vacuum, has value {float.Epsilon}"); // - // - Single zero = 0; + // + float zero = 0; // This condition will return false. - if ((0 / zero) == Single.NaN) + if ((0 / zero) == float.NaN) { Console.WriteLine("0 / 0 can be tested with Single.NaN."); } @@ -69,53 +70,53 @@ public SingleSample() } // - // + // // This will return true. - if (Single.IsNaN(0 / zero)) + if (float.IsNaN(0 / zero)) { Console.WriteLine("Single.IsNan() can determine whether a value is not-a-number."); } // - // + // // This will equal Infinity. - Console.WriteLine("10.0 minus NegativeInfinity equals {0}.", (10.0 - Single.NegativeInfinity).ToString()); + Console.WriteLine($"10.0 minus NegativeInfinity equals {10.0 - float.NegativeInfinity}."); // - // + // // This will equal Infinity. - Console.WriteLine("PositiveInfinity plus 10.0 equals {0}.", (Single.PositiveInfinity + 10.0).ToString()); + Console.WriteLine($"PositiveInfinity plus 10.0 equals {float.PositiveInfinity + 10.0}."); // - // + // // This will return "true". - Console.WriteLine("IsInfinity(3.0F / 0) == {0}.", Single.IsInfinity(3.0F / 0) ? "true" : "false"); + Console.WriteLine($"IsInfinity(3.0F / 0) == {(float.IsInfinity(3.0F / 0) ? "true" : "false")}."); // - // + // // This will return true. - Console.WriteLine("IsPositiveInfinity(4.0F / 0) == {0}.", Single.IsPositiveInfinity(4.0F / 0) ? "true" : "false"); + Console.WriteLine($"IsPositiveInfinity(4.0F / 0) == {(float.IsPositiveInfinity(4.0F / 0) ? "true" : "false")}."); // - // + // // This will return true. - Console.WriteLine("IsNegativeInfinity(-5.0F / 0) == {0}.", Single.IsNegativeInfinity(-5.0F / 0) ? "true" : "false"); + Console.WriteLine($"IsNegativeInfinity(-5.0F / 0) == {(float.IsNegativeInfinity(-5.0F / 0) ? "true" : "false")}."); // // - Single a; + float a; a = 500; - Object obj1; + object obj1; // - // + // // The variables point to the same objects. - Object obj2; + object obj2; obj1 = a; obj2 = obj1; - if (Single.ReferenceEquals(obj1, obj2)) + if (float.ReferenceEquals(obj1, obj2)) { Console.WriteLine("The variables point to the same Single object."); } @@ -125,28 +126,29 @@ public SingleSample() } // - // - obj1 = (Single)450; + // + obj1 = (float)450; if (a.CompareTo(obj1) < 0) { - Console.WriteLine("{0} is less than {1}.", a.ToString(), obj1.ToString()); + Console.WriteLine($"{a} is less than {obj1}."); } if (a.CompareTo(obj1) > 0) { - Console.WriteLine("{0} is greater than {1}.", a.ToString(), obj1.ToString()); + Console.WriteLine($"{a} is greater than {obj1}."); } if (a.CompareTo(obj1) == 0) { - Console.WriteLine("{0} equals {1}.", a.ToString(), obj1.ToString()); + Console.WriteLine($"{a} equals {obj1}."); } // - // - obj1 = (Single)500; - if (a.Equals(obj1)) { + // + obj1 = (float)500; + if (a.Equals(obj1)) + { Console.WriteLine("The value type and reference type values are equal."); } // @@ -156,8 +158,5 @@ public SingleSample() class EntryPoint { - static void Main(string[] args) - { - new SingleSnippet.SingleSample(); - } -} \ No newline at end of file + static void Main(string[] args) => new SingleSnippet.SingleSample(); +} diff --git a/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs b/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs index da27b7ae54c..af810b2453c 100644 --- a/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs +++ b/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs @@ -2,73 +2,73 @@ public class Class1 { - public static void Main() - { - CompareUsingEquals(); - Console.WriteLine(); - CompareApproximateValues(); - Console.WriteLine(); - CompareObjectsUsingEquals(); - Console.WriteLine(); - CompareApproximateObjectValues(); - Console.WriteLine(); - } + public static void Main() + { + CompareUsingEquals(); + Console.WriteLine(); + CompareApproximateValues(); + Console.WriteLine(); + CompareObjectsUsingEquals(); + Console.WriteLine(); + CompareApproximateObjectValues(); + Console.WriteLine(); + } - private static void CompareUsingEquals() - { - // - // Initialize two floats with apparently identical values - float float1 = .33333f; - float float2 = 1/3; - // Compare them for equality - Console.WriteLine(float1.Equals(float2)); // displays false - // - } - - private static void CompareApproximateValues() - { - // - // Initialize two floats with apparently identical values - float float1 = .33333f; - float float2 = (float) 1/3; - // Define the tolerance for variation in their values - float difference = Math.Abs(float1 * .0001f); + private static void CompareUsingEquals() + { + // + // Initialize two floats with apparently identical values + float float1 = .33333f; + float float2 = 1 / 3; + // Compare them for equality + Console.WriteLine(float1.Equals(float2)); // displays false + // + } - // Compare the values - // The output to the console indicates that the two values are equal - if (Math.Abs(float1 - float2) <= difference) - Console.WriteLine("float1 and float2 are equal."); - else - Console.WriteLine("float1 and float2 are unequal."); - // - } + private static void CompareApproximateValues() + { + // + // Initialize two floats with apparently identical values + float float1 = .33333f; + float float2 = (float)1 / 3; + // Define the tolerance for variation in their values + float difference = Math.Abs(float1 * .0001f); - private static void CompareObjectsUsingEquals() - { - // - // Initialize two floats with apparently identical values - float float1 = .33333f; - object float2 = 1/3; - // Compare them for equality - Console.WriteLine(float1.Equals(float2)); // displays false - // - } - - private static void CompareApproximateObjectValues() - { - // - // Initialize two floats with apparently identical values - float float1 = .33333f; - object float2 = (float) 1/3; - // Define the tolerance for variation in their values - float difference = Math.Abs(float1 * .0001f); + // Compare the values + // The output to the console indicates that the two values are equal + if (Math.Abs(float1 - float2) <= difference) + Console.WriteLine("float1 and float2 are equal."); + else + Console.WriteLine("float1 and float2 are unequal."); + // + } - // Compare the values - // The output to the console indicates that the two values are equal - if (Math.Abs(float1 - (float) float2) <= difference) - Console.WriteLine("float1 and float2 are equal."); - else - Console.WriteLine("float1 and float2 are unequal."); - // - } + private static void CompareObjectsUsingEquals() + { + // + // Initialize two floats with apparently identical values + float float1 = .33333f; + object float2 = 1 / 3; + // Compare them for equality + Console.WriteLine(float1.Equals(float2)); // displays false + // + } + + private static void CompareApproximateObjectValues() + { + // + // Initialize two floats with apparently identical values + float float1 = .33333f; + object float2 = (float)1 / 3; + // Define the tolerance for variation in their values + float difference = Math.Abs(float1 * .0001f); + + // Compare the values + // The output to the console indicates that the two values are equal + if (Math.Abs(float1 - (float)float2) <= difference) + Console.WriteLine("float1 and float2 are equal."); + else + Console.WriteLine("float1 and float2 are unequal."); + // + } } diff --git a/snippets/csharp/System/Single/Epsilon/epsilon.cs b/snippets/csharp/System/Single/Epsilon/epsilon.cs index 2bf16f5c802..a5581e319f2 100644 --- a/snippets/csharp/System/Single/Epsilon/epsilon.cs +++ b/snippets/csharp/System/Single/Epsilon/epsilon.cs @@ -1,25 +1,25 @@ -// +// using System; public class Example1 { - public static void Main() - { - float[] values = { 0f, Single.Epsilon, Single.Epsilon * .5f }; - - for (int ctr = 0; ctr <= values.Length - 2; ctr++) - { - for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) - { - Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); - } - Console.WriteLine(); - } - } + public static void Main() + { + float[] values = [0f, float.Epsilon, float.Epsilon * .5f]; + + for (int ctr = 0; ctr <= values.Length - 2; ctr++) + { + for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) + { + Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // 0 = 1.401298E-45: False // 0 = 0: True -// +// // 1.401298E-45 = 0: False // diff --git a/snippets/csharp/System/Single/Epsilon/epsilon1.cs b/snippets/csharp/System/Single/Epsilon/epsilon1.cs index 87664989eac..d15e3769807 100644 --- a/snippets/csharp/System/Single/Epsilon/epsilon1.cs +++ b/snippets/csharp/System/Single/Epsilon/epsilon1.cs @@ -3,48 +3,48 @@ public class Example2 { - public static void Main() - { - float[] values = { 0.0f, Single.Epsilon }; - foreach (var value in values) { - Console.WriteLine(GetComponentParts(value)); - Console.WriteLine(); - } - } + public static void Main() + { + float[] values = [0.0f, float.Epsilon]; + foreach (float value in values) + { + Console.WriteLine(GetComponentParts(value)); + Console.WriteLine(); + } + } - private static string GetComponentParts(float value) - { - string result = String.Format("{0:R}: ", value); - int indent = result.Length; + private static string GetComponentParts(float value) + { + string result = $"{value:R}: "; + int indent = result.Length; - // Convert the single to a 4-byte array. - byte[] bytes = BitConverter.GetBytes(value); - int formattedSingle = BitConverter.ToInt32(bytes, 0); - - // Get the sign bit (byte 3, bit 7). - result += String.Format("Sign: {0}\n", - (formattedSingle >> 31) != 0 ? "1 (-)" : "0 (+)"); + // Convert the single to a 4-byte array. + byte[] bytes = BitConverter.GetBytes(value); + int formattedSingle = BitConverter.ToInt32(bytes, 0); - // Get the exponent (byte 2 bit 7 to byte 3, bits 6) - int exponent = (formattedSingle >> 23) & 0x000000FF; - int adjustment = (exponent != 0) ? 127 : 126; - result += String.Format("{0}Exponent: 0x{1:X4} ({1})\n", new String(' ', indent), exponent - adjustment); + // Get the sign bit (byte 3, bit 7). + result += $"Sign: {((formattedSingle >> 31) != 0 ? "1 (-)" : "0 (+)")}\n"; - // Get the significand (bits 0-22) - long significand = exponent != 0 ? - ((formattedSingle & 0x007FFFFF) | 0x800000) : - (formattedSingle & 0x007FFFFF); - result += String.Format("{0}Mantissa: 0x{1:X13}\n", new String(' ', indent), significand); - return result; - } + // Get the exponent (byte 2 bit 7 to byte 3, bits 6) + int exponent = (formattedSingle >> 23) & 0x000000FF; + int adjustment = (exponent != 0) ? 127 : 126; + result += string.Format("{0}Exponent: 0x{1:X4} ({1})\n", new string(' ', indent), exponent - adjustment); + + // Get the significand (bits 0-22) + long significand = exponent != 0 ? + ((formattedSingle & 0x007FFFFF) | 0x800000) : + (formattedSingle & 0x007FFFFF); + result += $"{new string(' ', indent)}Mantissa: 0x{significand:X13}\n"; + return result; + } } // // The example displays the following output: // 0: Sign: 0 (+) // Exponent: 0xFFFFFF82 (-126) // Mantissa: 0x0000000000000 -// -// +// +// // 1.401298E-45: Sign: 0 (+) // Exponent: 0xFFFFFF82 (-126) // Mantissa: 0x0000000000001 -// +// diff --git a/snippets/csharp/System/Single/Equals/equalsabs1.cs b/snippets/csharp/System/Single/Equals/equalsabs1.cs index 6aa1d68c28e..67e08171bac 100644 --- a/snippets/csharp/System/Single/Equals/equalsabs1.cs +++ b/snippets/csharp/System/Single/Equals/equalsabs1.cs @@ -1,43 +1,43 @@ -// +// using System; public class Example { - public static void Main() - { - float value1 = .1f * 10f; - float value2 = 0f; - for (int ctr = 0; ctr < 10; ctr++) - value2 += .1f; - - Console.WriteLine($"{value1:R} = {value2:R}: {HasMinimalDifference(value1, value2, 1)}"); - } - - public static bool HasMinimalDifference(float value1, float value2, int units) - { - byte[] bytes = BitConverter.GetBytes(value1); - int iValue1 = BitConverter.ToInt32(bytes, 0); - - bytes = BitConverter.GetBytes(value2); - int iValue2 = BitConverter.ToInt32(bytes, 0); - - // If the signs are different, return false except for +0 and -0. - if ((iValue1 >> 31) != (iValue2 >> 31)) - { - if (value1 == value2) - return true; - - return false; - } + public static void Main() + { + float value1 = .1f * 10f; + float value2 = 0f; + for (int ctr = 0; ctr < 10; ctr++) + value2 += .1f; + + Console.WriteLine($"{value1:R} = {value2:R}: {HasMinimalDifference(value1, value2, 1)}"); + } + + public static bool HasMinimalDifference(float value1, float value2, int units) + { + byte[] bytes = BitConverter.GetBytes(value1); + int iValue1 = BitConverter.ToInt32(bytes, 0); + + bytes = BitConverter.GetBytes(value2); + int iValue2 = BitConverter.ToInt32(bytes, 0); - int diff = Math.Abs(iValue1 - iValue2); + // If the signs are different, return false except for +0 and -0. + if ((iValue1 >> 31) != (iValue2 >> 31)) + { + if (value1 == value2) + return true; - if (diff <= units) - return true; + return false; + } + + int diff = Math.Abs(iValue1 - iValue2); + + if (diff <= units) + return true; - return false; - } + return false; + } } // The example displays the following output: // 1 = 1.00000012: True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Single/Equals/equalsoverl.cs b/snippets/csharp/System/Single/Equals/equalsoverl.cs index 33dd94b5851..d16ba1fa0d2 100644 --- a/snippets/csharp/System/Single/Equals/equalsoverl.cs +++ b/snippets/csharp/System/Single/Equals/equalsoverl.cs @@ -3,58 +3,52 @@ public class Example2 { - static float value = 112; + static float value = 112; - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - short short1 = 112; - Console.WriteLine("value = short1: {0,16}", value.Equals(short1)); - TestObjectForEquality(short1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),16}"); + TestObjectForEquality(short1); - int int1 = 112; - Console.WriteLine("value = int1: {0,18}", value.Equals(int1)); - TestObjectForEquality(int1); + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),18}"); + TestObjectForEquality(int1); - long long1 = 112; - Console.WriteLine("value = long1: {0,17}", value.Equals(long1)); - TestObjectForEquality(long1); + long long1 = 112; + Console.WriteLine($"value = long1: {value.Equals(long1),17}"); + TestObjectForEquality(long1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,16}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),16}"); + TestObjectForEquality(sbyte1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - uint uint1 = 112; - Console.WriteLine("value = uint1: {0,18}", value.Equals(uint1)); - TestObjectForEquality(uint1); + uint uint1 = 112; + Console.WriteLine($"value = uint1: {value.Equals(uint1),18}"); + TestObjectForEquality(uint1); - ulong ulong1 = 112; - Console.WriteLine("value = ulong1: {0,17}", value.Equals(ulong1)); - TestObjectForEquality(ulong1); + ulong ulong1 = 112; + Console.WriteLine($"value = ulong1: {value.Equals(ulong1),17}"); + TestObjectForEquality(ulong1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/Single/MaxValue/maxvalueex.cs b/snippets/csharp/System/Single/MaxValue/maxvalueex.cs index e84e70b220d..aa87213e538 100644 --- a/snippets/csharp/System/Single/MaxValue/maxvalueex.cs +++ b/snippets/csharp/System/Single/MaxValue/maxvalueex.cs @@ -3,16 +3,14 @@ public class Example { - public static void Main() - { - float result1 = 1.867e38f + 2.385e38f; - Console.WriteLine("{0} (Positive Infinity: {1})", - result1, Single.IsPositiveInfinity(result1)); - - float result2 = 1.5935e25f * 7.948e20f; - Console.WriteLine("{0} (Positive Infinity: {1})", - result2, Single.IsPositiveInfinity(result2)); - } + public static void Main() + { + float result1 = 1.867e38f + 2.385e38f; + Console.WriteLine($"{result1} (Positive Infinity: {float.IsPositiveInfinity(result1)})"); + + float result2 = 1.5935e25f * 7.948e20f; + Console.WriteLine($"{result2} (Positive Infinity: {float.IsPositiveInfinity(result2)})"); + } } // The example displays the following output: // Infinity (Positive Infinity: True) diff --git a/snippets/csharp/System/Single/MinValue/minvalueex.cs b/snippets/csharp/System/Single/MinValue/minvalueex.cs index 953c4ebbf79..24b4151ac66 100644 --- a/snippets/csharp/System/Single/MinValue/minvalueex.cs +++ b/snippets/csharp/System/Single/MinValue/minvalueex.cs @@ -3,16 +3,14 @@ public class Example { - public static void Main() - { - float result1 = -8.997e37f + -2.985e38f; - Console.WriteLine("{0} (Negative Infinity: {1})", - result1, Single.IsNegativeInfinity(result1)); - - float result2 = -1.5935e25f * 7.948e32f; - Console.WriteLine("{0} (Negative Infinity: {1})", - result2, Single.IsNegativeInfinity(result2)); - } + public static void Main() + { + float result1 = -8.997e37f + -2.985e38f; + Console.WriteLine($"{result1} (Negative Infinity: {float.IsNegativeInfinity(result1)})"); + + float result2 = -1.5935e25f * 7.948e32f; + Console.WriteLine($"{result2} (Negative Infinity: {float.IsNegativeInfinity(result2)})"); + } } // The example displays the following output: // -Infinity (Negative Infinity: True) diff --git a/snippets/csharp/System/Single/NaN/Program.cs b/snippets/csharp/System/Single/NaN/Program.cs new file mode 100644 index 00000000000..67609d649bf --- /dev/null +++ b/snippets/csharp/System/Single/NaN/Program.cs @@ -0,0 +1,2 @@ +SingleNaNOperationsExample.Run(); +SingleNaNComparisonExample.Run(); diff --git a/snippets/csharp/System/Single/NaN/Project.csproj b/snippets/csharp/System/Single/NaN/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Single/NaN/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Single/NaN/nan1.cs b/snippets/csharp/System/Single/NaN/nan1.cs index c7af3af5178..d6abc4bf6d7 100644 --- a/snippets/csharp/System/Single/NaN/nan1.cs +++ b/snippets/csharp/System/Single/NaN/nan1.cs @@ -1,33 +1,32 @@ using System; -public class Example +public class SingleNaNOperationsExample { - public static void Main() - { - // - float zero = 0.0f; - Console.WriteLine("{0} / {1} = {2}", zero, zero, zero/zero); - // The example displays the following output: - // 0 / 0 = NaN - // + public static void Run() + { + // + float zero = 0.0f; + Console.WriteLine($"{zero} / {zero} = {zero / zero}"); + // The example displays the following output: + // 0 / 0 = NaN + // - // - float nan1 = Single.NaN; - - Console.WriteLine("{0} + {1} = {2}", 3, nan1, 3 + nan1); - Console.WriteLine("Abs({0}) = {1}", nan1, Math.Abs(nan1)); - // The example displays the following output: - // 3 + NaN = NaN - // Abs(NaN) = NaN - // - Console.WriteLine(); - - // - float result = Single.NaN; - Console.WriteLine("{0} = Single.NaN: {1}", - result, result == Single.NaN); - // The example displays the following output: - // NaN = Single.Nan: False - // - } + // + float nan1 = float.NaN; + + Console.WriteLine($"{3} + {nan1} = {3 + nan1}"); + Console.WriteLine($"Abs({nan1}) = {Math.Abs(nan1)}"); + // The example displays the following output: + // 3 + NaN = NaN + // Abs(NaN) = NaN + // + Console.WriteLine(); + + // + float result = float.NaN; + Console.WriteLine($"{result} = Single.NaN: {result == float.NaN}"); + // The example displays the following output: + // NaN = Single.Nan: False + // + } } diff --git a/snippets/csharp/System/Single/NaN/single.nan4.cs b/snippets/csharp/System/Single/NaN/single.nan4.cs index bf6ec01d851..ad96ed834b4 100644 --- a/snippets/csharp/System/Single/NaN/single.nan4.cs +++ b/snippets/csharp/System/Single/NaN/single.nan4.cs @@ -1,26 +1,26 @@ // using System; -public class Example +public class SingleNaNComparisonExample { - public static void Main() - { - Console.WriteLine("NaN == NaN: {0}", Single.NaN == Single.NaN); - Console.WriteLine("NaN != NaN: {0}", Single.NaN != Single.NaN); - Console.WriteLine("NaN.Equals(NaN): {0}", Single.NaN.Equals(Single.NaN)); - Console.WriteLine("! NaN.Equals(NaN): {0}", ! Single.NaN.Equals(Single.NaN)); - Console.WriteLine("IsNaN: {0}", Double.IsNaN(Double.NaN)); - - Console.WriteLine("\nNaN > NaN: {0}", Single.NaN > Single.NaN); - Console.WriteLine("NaN >= NaN: {0}", Single.NaN >= Single.NaN); - Console.WriteLine("NaN < NaN: {0}", Single.NaN < Single.NaN); - Console.WriteLine("NaN < 100.0: {0}", Single.NaN < 100.0f); - Console.WriteLine("NaN <= 100.0: {0}", Single.NaN <= 100.0f); - Console.WriteLine("NaN >= 100.0: {0}", Single.NaN > 100.0f); - Console.WriteLine("NaN.CompareTo(NaN): {0}", Single.NaN.CompareTo(Single.NaN)); - Console.WriteLine("NaN.CompareTo(100.0): {0}", Single.NaN.CompareTo(100.0f)); - Console.WriteLine("(100.0).CompareTo(Single.NaN): {0}", (100.0f).CompareTo(Single.NaN)); - } + public static void Run() + { + Console.WriteLine($"NaN == NaN: {float.NaN == float.NaN}"); + Console.WriteLine($"NaN != NaN: {float.NaN != float.NaN}"); + Console.WriteLine($"NaN.Equals(NaN): {float.NaN.Equals(float.NaN)}"); + Console.WriteLine($"! NaN.Equals(NaN): {!float.NaN.Equals(float.NaN)}"); + Console.WriteLine($"IsNaN: {double.IsNaN(double.NaN)}"); + + Console.WriteLine($"\nNaN > NaN: {float.NaN > float.NaN}"); + Console.WriteLine($"NaN >= NaN: {float.NaN >= float.NaN}"); + Console.WriteLine($"NaN < NaN: {float.NaN < float.NaN}"); + Console.WriteLine($"NaN < 100.0: {float.NaN < 100.0f}"); + Console.WriteLine($"NaN <= 100.0: {float.NaN <= 100.0f}"); + Console.WriteLine($"NaN > 100.0: {float.NaN > 100.0f}"); + Console.WriteLine($"NaN.CompareTo(NaN): {float.NaN.CompareTo(float.NaN)}"); + Console.WriteLine($"NaN.CompareTo(100.0): {float.NaN.CompareTo(100.0f)}"); + Console.WriteLine($"(100.0).CompareTo(Single.NaN): {(100.0f).CompareTo(float.NaN)}"); + } } // The example displays the following output: // NaN == NaN: False diff --git a/snippets/csharp/System/Single/Overview/comparison1.cs b/snippets/csharp/System/Single/Overview/comparison1.cs index 965c922e4f9..0d1eb7f0e2c 100644 --- a/snippets/csharp/System/Single/Overview/comparison1.cs +++ b/snippets/csharp/System/Single/Overview/comparison1.cs @@ -1,14 +1,14 @@ -// +// using System; public class Example { - public static void Main() - { - float value1 = .3333333f; - float value2 = 1.0f/3; - Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); - } + public static void Main() + { + float value1 = .3333333f; + float value2 = 1.0f / 3; + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); + } } // The example displays the following output: // 0.3333333 = 0.333333343: False diff --git a/snippets/csharp/System/Single/Overview/comparison2.cs b/snippets/csharp/System/Single/Overview/comparison2.cs index c18df56a7fa..400c11c3e1f 100644 --- a/snippets/csharp/System/Single/Overview/comparison2.cs +++ b/snippets/csharp/System/Single/Overview/comparison2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -13,7 +13,7 @@ public static void Main() // The example displays the following output on modern .NET: // 10.201438 = 10.201439: False - + // } } diff --git a/snippets/csharp/System/Single/Overview/comparison4.cs b/snippets/csharp/System/Single/Overview/comparison4.cs index ded666dc514..4ef3e6cd562 100644 --- a/snippets/csharp/System/Single/Overview/comparison4.cs +++ b/snippets/csharp/System/Single/Overview/comparison4.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example3 { @@ -29,9 +29,9 @@ static bool IsApproximatelyEqual(float value1, float value2, float epsilon) return true; // Handle NaN, Infinity. - if (Double.IsInfinity(value1) | Double.IsNaN(value1)) + if (double.IsInfinity(value1) | double.IsNaN(value1)) return value1.Equals(value2); - else if (Double.IsInfinity(value2) | Double.IsNaN(value2)) + else if (double.IsInfinity(value2) | double.IsNaN(value2)) return value1.Equals(value2); // Handle zero to avoid division by zero. diff --git a/snippets/csharp/System/Single/Overview/convert1.cs b/snippets/csharp/System/Single/Overview/convert1.cs index 8a5e0e75a97..c7995e864df 100644 --- a/snippets/csharp/System/Single/Overview/convert1.cs +++ b/snippets/csharp/System/Single/Overview/convert1.cs @@ -1,22 +1,22 @@ -// +// using System; public class Example4 { public static void Main() { - dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue, - Decimal.MaxValue, Double.MinValue, Double.MaxValue, - Int16.MinValue, Int16.MaxValue, Int32.MinValue, - Int32.MaxValue, Int64.MinValue, Int64.MaxValue, - SByte.MinValue, SByte.MaxValue, UInt16.MinValue, - UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue, - UInt64.MinValue, UInt64.MaxValue }; + dynamic[] values = [byte.MinValue, byte.MaxValue, decimal.MinValue, + decimal.MaxValue, double.MinValue, double.MaxValue, + short.MinValue, short.MaxValue, int.MinValue, + int.MaxValue, long.MinValue, long.MaxValue, + sbyte.MinValue, sbyte.MaxValue, ushort.MinValue, + ushort.MaxValue, uint.MinValue, uint.MaxValue, + ulong.MinValue, ulong.MaxValue]; float sngValue; foreach (var value in values) { - if (value.GetType() == typeof(Decimal) || - value.GetType() == typeof(Double)) + if (value.GetType() == typeof(decimal) || + value.GetType() == typeof(double)) sngValue = (float)value; else sngValue = value; diff --git a/snippets/csharp/System/Single/Overview/convert2.cs b/snippets/csharp/System/Single/Overview/convert2.cs index d9a17fb336c..812afb97838 100644 --- a/snippets/csharp/System/Single/Overview/convert2.cs +++ b/snippets/csharp/System/Single/Overview/convert2.cs @@ -1,21 +1,21 @@ -using System; +using System; public class Example5 { public static void Main() { // - float[] values = { Single.MinValue, -67890.1234f, -12345.6789f, - 12345.6789f, 67890.1234f, Single.MaxValue, - Single.NaN, Single.PositiveInfinity, - Single.NegativeInfinity }; + float[] values = [float.MinValue, -67890.1234f, -12345.6789f, + 12345.6789f, 67890.1234f, float.MaxValue, + float.NaN, float.PositiveInfinity, + float.NegativeInfinity]; checked { - foreach (var value in values) + foreach (float value in values) { try { - Int64 lValue = (long)value; + long lValue = (long)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"); } catch (OverflowException) @@ -24,7 +24,7 @@ public static void Main() } try { - UInt64 ulValue = (ulong)value; + ulong ulValue = (ulong)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"); } catch (OverflowException) @@ -33,7 +33,7 @@ public static void Main() } try { - Decimal dValue = (decimal)value; + decimal dValue = (decimal)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"); } catch (OverflowException) @@ -41,7 +41,7 @@ public static void Main() Console.WriteLine($"Unable to convert {value} to Decimal."); } - Double dblValue = value; + double dblValue = value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})"); Console.WriteLine(); } diff --git a/snippets/csharp/System/Single/Overview/exceptional2.cs b/snippets/csharp/System/Single/Overview/exceptional2.cs index 6c0cf45b151..b443cc4fe5c 100644 --- a/snippets/csharp/System/Single/Overview/exceptional2.cs +++ b/snippets/csharp/System/Single/Overview/exceptional2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example7 { @@ -8,14 +8,14 @@ public static void Main() float value1 = 3.065e35f; float value2 = 6.9375e32f; float result = value1 * value2; - Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}"); - Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}"); + Console.WriteLine($"PositiveInfinity: {float.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {float.IsNegativeInfinity(result)}"); Console.WriteLine(); value1 = -value1; result = value1 * value2; - Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}"); - Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}"); + Console.WriteLine($"PositiveInfinity: {float.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {float.IsNegativeInfinity(result)}"); // The example displays the following output: // PositiveInfinity: True diff --git a/snippets/csharp/System/Single/Overview/precisionlist1.cs b/snippets/csharp/System/Single/Overview/precisionlist1.cs index c42b4fc898f..02f1c908889 100644 --- a/snippets/csharp/System/Single/Overview/precisionlist1.cs +++ b/snippets/csharp/System/Single/Overview/precisionlist1.cs @@ -1,13 +1,13 @@ -using System; +using System; public class Example9 { public static void Main() { // - Double value1 = 1 / 3.0; - Single sValue2 = 1 / 3.0f; - Double value2 = (Double)sValue2; + double value1 = 1 / 3.0; + float sValue2 = 1 / 3.0f; + double value2 = (double)sValue2; Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); // The example displays the following output on .NET: diff --git a/snippets/csharp/System/Single/Overview/precisionlist3.cs b/snippets/csharp/System/Single/Overview/precisionlist3.cs index c8f2421707d..08338d033b4 100644 --- a/snippets/csharp/System/Single/Overview/precisionlist3.cs +++ b/snippets/csharp/System/Single/Overview/precisionlist3.cs @@ -5,10 +5,10 @@ public class PrecisionList3Example { public static void Main() { - Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f }; - Single result = 27.65f; - Single total = 0f; - foreach (var value in values) + float[] values = [10.01f, 2.88f, 2.88f, 2.88f, 9.0f]; + float result = 27.65f; + float total = 0f; + foreach (float value in values) total += value; if (total.Equals(result)) diff --git a/snippets/csharp/System/Single/Overview/representation1.cs b/snippets/csharp/System/Single/Overview/representation1.cs index 6ea38e68a79..0e4b8f14ea2 100644 --- a/snippets/csharp/System/Single/Overview/representation1.cs +++ b/snippets/csharp/System/Single/Overview/representation1.cs @@ -1,13 +1,13 @@ -// +// using System; public class Example12 { public static void Main() { - Single value = .2f; - Single result1 = value * 10f; - Single result2 = 0f; + float value = .2f; + float result1 = value * 10f; + float result2 = 0f; for (int ctr = 1; ctr <= 10; ctr++) result2 += value; diff --git a/snippets/csharp/System/Single/Overview/representation2.cs b/snippets/csharp/System/Single/Overview/representation2.cs index a3a072bdb3b..831f6bba562 100644 --- a/snippets/csharp/System/Single/Overview/representation2.cs +++ b/snippets/csharp/System/Single/Overview/representation2.cs @@ -5,8 +5,8 @@ public class Example13 { public static void Main() { - Single value = 123.456f; - Single additional = Single.Epsilon * 1e15f; + float value = 123.456f; + float additional = float.Epsilon * 1e15f; Console.WriteLine($"{value} + {additional} = {value + additional}"); } } diff --git a/snippets/csharp/System/Single/Parse/Program.cs b/snippets/csharp/System/Single/Parse/Program.cs new file mode 100644 index 00000000000..54c708cd959 --- /dev/null +++ b/snippets/csharp/System/Single/Parse/Program.cs @@ -0,0 +1,3 @@ +SingleParseDefaultExample.Run(); +ParseString.Run(); +SingleParseProviderExample.Run(); diff --git a/snippets/csharp/System/Single/Parse/Project.csproj b/snippets/csharp/System/Single/Parse/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Single/Parse/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Single/Parse/parse1.cs b/snippets/csharp/System/Single/Parse/parse1.cs index 94a4ae32ad5..57f3bdbc73e 100644 --- a/snippets/csharp/System/Single/Parse/parse1.cs +++ b/snippets/csharp/System/Single/Parse/parse1.cs @@ -1,28 +1,31 @@ // using System; -public class Example +public class SingleParseDefaultExample { - public static void Main() - { - string[] values = { "100", "(100)", "-123,456,789", "123.45e+6", - "+500", "5e2", "3.1416", "600.", "-.123", - "-Infinity", "-1E-16", Double.MaxValue.ToString(), - Single.MinValue.ToString(), String.Empty }; - foreach (string value in values) - { - try { - float number = Single.Parse(value); - Console.WriteLine("{0} -> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in a valid format.", value); - } - catch (OverflowException) { - Console.WriteLine("{0} is outside the range of a Single.", value); - } - } - } + public static void Run() + { + string[] values = ["100", "(100)", "-123,456,789", "123.45e+6", + "+500", "5e2", "3.1416", "600.", "-.123", + "-Infinity", "-1E-16", $"{double.MaxValue}", + $"{float.MinValue}", string.Empty]; + foreach (string value in values) + { + try + { + float number = float.Parse(value); + Console.WriteLine($"{value} -> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"'{value}' is not in a valid format."); + } + catch (OverflowException) + { + Console.WriteLine($"{value} is outside the range of a Single."); + } + } + } } // The example displays the following output: // 100 -> 100 diff --git a/snippets/csharp/System/Single/Parse/parse2.cs b/snippets/csharp/System/Single/Parse/parse2.cs index 9dd7be9bdf5..e06b0ce0fd3 100644 --- a/snippets/csharp/System/Single/Parse/parse2.cs +++ b/snippets/csharp/System/Single/Parse/parse2.cs @@ -5,66 +5,64 @@ public class ParseString { - public static void Main() - { - // Set current thread culture to en-US. - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - - string value; - NumberStyles styles; - - // Parse a string in exponential notation with only the AllowExponent flag. - value = "-1.063E-02"; - styles = NumberStyles.AllowExponent; - ShowNumericValue(value, styles); - - // Parse a string in exponential notation - // with the AllowExponent and Number flags. - styles = NumberStyles.AllowExponent | NumberStyles.Number; - ShowNumericValue(value, styles); + public static void Run() + { + // Set current thread culture to en-US. + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - // Parse a currency value with leading and trailing white space, and - // white space after the U.S. currency symbol. - value = " $ 6,164.3299 "; - styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; - ShowNumericValue(value, styles); - - // Parse negative value with thousands separator and decimal. - value = "(4,320.64)"; - styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | - NumberStyles.Float; - ShowNumericValue(value, styles); - - styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | - NumberStyles.Float | NumberStyles.AllowThousands; - ShowNumericValue(value, styles); - } + string value; + NumberStyles styles; - private static void ShowNumericValue(string value, NumberStyles styles) - { - Single number; - try - { - number = Single.Parse(value, styles); - Console.WriteLine("Converted '{0}' using {1} to {2}.", - value, styles.ToString(), number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}' with styles {1}.", - value, styles.ToString()); - } - Console.WriteLine(); - } + // Parse a string in exponential notation with only the AllowExponent flag. + value = "-1.063E-02"; + styles = NumberStyles.AllowExponent; + ShowNumericValue(value, styles); + + // Parse a string in exponential notation + // with the AllowExponent and Number flags. + styles = NumberStyles.AllowExponent | NumberStyles.Number; + ShowNumericValue(value, styles); + + // Parse a currency value with leading and trailing white space, and + // white space after the U.S. currency symbol. + value = " $ 6,164.3299 "; + styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; + ShowNumericValue(value, styles); + + // Parse negative value with thousands separator and decimal. + value = "(4,320.64)"; + styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | + NumberStyles.Float; + ShowNumericValue(value, styles); + + styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | + NumberStyles.Float | NumberStyles.AllowThousands; + ShowNumericValue(value, styles); + } + + private static void ShowNumericValue(string value, NumberStyles styles) + { + float number; + try + { + number = float.Parse(value, styles); + Console.WriteLine($"Converted '{value}' using {styles} to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}' with styles {styles}."); + } + Console.WriteLine(); + } } // The example displays the following output to the console: // Unable to parse '-1.063E-02' with styles AllowExponent. -// +// // Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063. -// +// // Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299. -// +// // Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float. -// -// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64. +// +// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64. // diff --git a/snippets/csharp/System/Single/Parse/parse3.cs b/snippets/csharp/System/Single/Parse/parse3.cs index 09b21dd9db9..dd33935f0c4 100644 --- a/snippets/csharp/System/Single/Parse/parse3.cs +++ b/snippets/csharp/System/Single/Parse/parse3.cs @@ -2,51 +2,52 @@ using System; using System.Globalization; -public class Example +public class SingleParseProviderExample { - public static void Main() + public static void Run() { - // Define an array of string values. - string[] values = { " 987.654E-2", " 987,654E-2", "(98765,43210)", - "9,876,543.210", "9.876.543,210", "98_76_54_32,19" }; - // Create a custom culture based on the invariant culture. - CultureInfo ci = new CultureInfo(""); - ci.NumberFormat.NumberGroupSizes = new int[] { 2 }; - ci.NumberFormat.NumberGroupSeparator = "_"; + // Define an array of string values. + string[] values = [" 987.654E-2", " 987,654E-2", "(98765,43210)", + "9,876,543.210", "9.876.543,210", "98_76_54_32,19"]; + // Create a custom culture based on the invariant culture. + CultureInfo ci = new(""); + ci.NumberFormat.NumberGroupSizes = [2]; + ci.NumberFormat.NumberGroupSeparator = "_"; - // Define an array of format providers. - CultureInfo[] providers = { new CultureInfo("en-US"), - new CultureInfo("nl-NL"), ci }; + // Define an array of format providers. + CultureInfo[] providers = [new CultureInfo("en-US"), + new CultureInfo("nl-NL"), ci]; - // Define an array of styles. - NumberStyles[] styles = { NumberStyles.Currency, NumberStyles.Float }; + // Define an array of styles. + NumberStyles[] styles = [NumberStyles.Currency, NumberStyles.Float]; - // Iterate the array of format providers. - foreach (CultureInfo provider in providers) - { - Console.WriteLine("Parsing using the {0} culture:", - provider.Name == String.Empty ? "Invariant" : provider.Name); - // Parse each element in the array of string values. - foreach (string value in values) - { - foreach (NumberStyles style in styles) + // Iterate the array of format providers. + foreach (CultureInfo provider in providers) + { + Console.WriteLine($"Parsing using the {(provider.Name == string.Empty ? "Invariant" : provider.Name)} culture:"); + // Parse each element in the array of string values. + foreach (string value in values) { - try { - float number = Single.Parse(value, style, provider); - Console.WriteLine(" {0} ({1}) -> {2}", - value, style, number); - } - catch (FormatException) { - Console.WriteLine(" '{0}' is invalid using {1}.", value, style); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of the range of a Single.", value); - } + foreach (NumberStyles style in styles) + { + try + { + float number = float.Parse(value, style, provider); + Console.WriteLine($" {value} ({style}) -> {number}"); + } + catch (FormatException) + { + Console.WriteLine($" '{value}' is invalid using {style}."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of the range of a Single."); + } + } } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output: // Parsing using the en-US culture: diff --git a/snippets/csharp/System/Single/ToString/ToString1.cs b/snippets/csharp/System/Single/ToString/ToString1.cs index 5ea413b49bd..b8091c3ee9a 100644 --- a/snippets/csharp/System/Single/ToString/ToString1.cs +++ b/snippets/csharp/System/Single/ToString/ToString1.cs @@ -3,209 +3,208 @@ public class Class1 { - public static void Main() - { - CallDefaultToString(); - Console.WriteLine("----------"); - CallToStringWithFormatProvider(); - Console.WriteLine("----------"); - CallToStringWithFormatString(); - Console.WriteLine("----------"); - CallToStringWithFormatStringAndProvider(); - } - - private static void CallDefaultToString() - { - // - float number; - - number = 1.6E20F; - // Displays 1.6E+20. - Console.WriteLine(number.ToString()); - - number = 1.6E2F; - // Displays 160. - Console.WriteLine(number.ToString()); - - number = -3.541F; - // Displays -3.541. - Console.WriteLine(number.ToString()); - - number = -1502345222199E-07F; - // Displays -150234.5222199. - Console.WriteLine(number.ToString()); - - number = -15023452221990199574E-09F; - // Displays -15023452221.9902. - Console.WriteLine(number.ToString()); - - number = .60344F; - // Displays 0.60344. - Console.WriteLine(number.ToString()); - - number = .000000001F; - // Displays 1E-09. - Console.WriteLine(number.ToString()); - // - } - - private static void CallToStringWithFormatProvider() - { - // - float value; - - value = -16325.62015F; - // Display value using the invariant culture. - Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); - // Display value using the en-GB culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); - // Display value using the de-DE culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); - - value = 16034.125E21F; - // Display value using the invariant culture. - Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); - // Display value using the en-GB culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); - // Display value using the de-DE culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); - // This example displays the following output to the console: - // -16325.62015 - // -16325.62015 - // -16325,62015 - // 1.6034125E+25 - // 1.6034125E+25 - // 1,6034125E+25 - // - } - - private static void CallToStringWithFormatString() - { - // - float[] numbers= { 1054.32179F, -195489100.8377F, 1.0437E21F, - -1.0573e-05F }; - string[] specifiers = { "C", "E", "e", "F", "G", "N", "P", - "R", "#,000.000", "0.###E-000", - "000,000,000,000.00###" }; - - foreach (float number in numbers) - { - Console.WriteLine("Formatting of {0}:", number); - foreach (string specifier in specifiers) - Console.WriteLine(" {0,5}: {1}", - specifier, number.ToString(specifier)); - - Console.WriteLine(); - } - // The example displays the following output to the console: - // Formatting of 1054.32179: - // C: $1,054.32 - // E: 1.054322E+003 - // e: 1.054322e+003 - // F: 1054.32 - // G: 1054.32179 - // N: 1,054.32 - // P: 105,432.18 % - // R: 1054.32179 - // #,000.000: 1,054.322 - // 0.###E-000: 1.054E003 - // 000,000,000,000.00###: 000,000,001,054.322 - // - // Formatting of -195489100.8377: - // C: ($195,489,100.84) - // E: -1.954891E+008 - // e: -1.954891e+008 - // F: -195489100.84 - // G: -195489100.8377 - // N: -195,489,100.84 - // P: -19,548,910,083.77 % - // R: -195489100.8377 - // #,000.000: -195,489,100.838 - // 0.###E-000: -1.955E008 - // 000,000,000,000.00###: -000,195,489,100.00 - // - // Formatting of 1.0437E+21: - // C: $1,043,700,000,000,000,000,000.00 - // E: 1.043700E+021 - // e: 1.043700e+021 - // F: 1043700000000000000000.00 - // G: 1.0437E+21 - // N: 1,043,700,000,000,000,000,000.00 - // P: 104,370,000,000,000,000,000,000.00 % - // R: 1.0437E+21 - // #,000.000: 1,043,700,000,000,000,000,000.000 - // 0.###E-000: 1.044E021 - // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00 - // - // Formatting of -1.0573E-05: - // C: $0.00 - // E: -1.057300E-005 - // e: -1.057300e-005 - // F: 0.00 - // G: -1.0573E-05 - // N: 0.00 - // P: 0.00 % - // R: -1.0573E-05 - // #,000.000: 000.000 - // 0.###E-000: -1.057E-005 - // 000,000,000,000.00###: -000,000,000,000.00001 - // - } - - private static void CallToStringWithFormatStringAndProvider() - { - // - float value = 16325.62901F; - string specifier; - CultureInfo culture; - - // Use standard numeric format specifiers. - specifier = "G"; - culture = CultureInfo.CreateSpecificCulture("eu-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,62901 - Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); - // Displays: 16325.62901 - - specifier = "C"; - culture = CultureInfo.CreateSpecificCulture("en-US"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: $16,325.63 - culture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: £16,325.63 - - specifier = "E04"; - culture = CultureInfo.CreateSpecificCulture("sv-SE"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1,6326E+004 - culture = CultureInfo.CreateSpecificCulture("en-NZ"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1.6326E+004 - - specifier = "F"; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,63 - culture = CultureInfo.CreateSpecificCulture("en-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325.63 - - specifier = "N"; - culture = CultureInfo.CreateSpecificCulture("es-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16.325,63 - culture = CultureInfo.CreateSpecificCulture("fr-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16 325,63 - - specifier = "P"; - culture = CultureInfo.InvariantCulture; - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.26 % - culture = CultureInfo.CreateSpecificCulture("ar-EG"); - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.256 % - // - } + public static void Main() + { + CallDefaultToString(); + Console.WriteLine("----------"); + CallToStringWithFormatProvider(); + Console.WriteLine("----------"); + CallToStringWithFormatString(); + Console.WriteLine("----------"); + CallToStringWithFormatStringAndProvider(); + } + + private static void CallDefaultToString() + { + // + float number; + + number = 1.6E20F; + // Displays 1.6E+20. + Console.WriteLine(number.ToString()); + + number = 1.6E2F; + // Displays 160. + Console.WriteLine(number.ToString()); + + number = -3.541F; + // Displays -3.541. + Console.WriteLine(number.ToString()); + + number = -1502345222199E-07F; + // Displays -150234.5222199. + Console.WriteLine(number.ToString()); + + number = -15023452221990199574E-09F; + // Displays -15023452221.9902. + Console.WriteLine(number.ToString()); + + number = .60344F; + // Displays 0.60344. + Console.WriteLine(number.ToString()); + + number = .000000001F; + // Displays 1E-09. + Console.WriteLine(number.ToString()); + // + } + + private static void CallToStringWithFormatProvider() + { + // + float value; + + value = -16325.62015F; + // Display value using the invariant culture. + Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); + // Display value using the en-GB culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); + // Display value using the de-DE culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); + + value = 16034.125E21F; + // Display value using the invariant culture. + Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); + // Display value using the en-GB culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); + // Display value using the de-DE culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); + // This example displays the following output to the console: + // -16325.62015 + // -16325.62015 + // -16325,62015 + // 1.6034125E+25 + // 1.6034125E+25 + // 1,6034125E+25 + // + } + + private static void CallToStringWithFormatString() + { + // + float[] numbers = [1054.32179F, -195489100.8377F, 1.0437E21F, + -1.0573e-05F]; + string[] specifiers = ["C", "E", "e", "F", "G", "N", "P", + "R", "#,000.000", "0.###E-000", + "000,000,000,000.00###"]; + + foreach (float number in numbers) + { + Console.WriteLine($"Formatting of {number}:"); + foreach (string specifier in specifiers) + Console.WriteLine($" {specifier,5}: {number.ToString(specifier)}"); + + Console.WriteLine(); + } + // The example displays the following output to the console: + // Formatting of 1054.32179: + // C: $1,054.32 + // E: 1.054322E+003 + // e: 1.054322e+003 + // F: 1054.32 + // G: 1054.32179 + // N: 1,054.32 + // P: 105,432.18 % + // R: 1054.32179 + // #,000.000: 1,054.322 + // 0.###E-000: 1.054E003 + // 000,000,000,000.00###: 000,000,001,054.322 + // + // Formatting of -195489100.8377: + // C: ($195,489,100.84) + // E: -1.954891E+008 + // e: -1.954891e+008 + // F: -195489100.84 + // G: -195489100.8377 + // N: -195,489,100.84 + // P: -19,548,910,083.77 % + // R: -195489100.8377 + // #,000.000: -195,489,100.838 + // 0.###E-000: -1.955E008 + // 000,000,000,000.00###: -000,195,489,100.00 + // + // Formatting of 1.0437E+21: + // C: $1,043,700,000,000,000,000,000.00 + // E: 1.043700E+021 + // e: 1.043700e+021 + // F: 1043700000000000000000.00 + // G: 1.0437E+21 + // N: 1,043,700,000,000,000,000,000.00 + // P: 104,370,000,000,000,000,000,000.00 % + // R: 1.0437E+21 + // #,000.000: 1,043,700,000,000,000,000,000.000 + // 0.###E-000: 1.044E021 + // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00 + // + // Formatting of -1.0573E-05: + // C: $0.00 + // E: -1.057300E-005 + // e: -1.057300e-005 + // F: 0.00 + // G: -1.0573E-05 + // N: 0.00 + // P: 0.00 % + // R: -1.0573E-05 + // #,000.000: 000.000 + // 0.###E-000: -1.057E-005 + // 000,000,000,000.00###: -000,000,000,000.00001 + // + } + + private static void CallToStringWithFormatStringAndProvider() + { + // + float value = 16325.62901F; + string specifier; + CultureInfo culture; + + // Use standard numeric format specifiers. + specifier = "G"; + culture = CultureInfo.CreateSpecificCulture("eu-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,62901 + Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); + // Displays: 16325.62901 + + specifier = "C"; + culture = CultureInfo.CreateSpecificCulture("en-US"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: $16,325.63 + culture = CultureInfo.CreateSpecificCulture("en-GB"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: £16,325.63 + + specifier = "E04"; + culture = CultureInfo.CreateSpecificCulture("sv-SE"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1,6326E+004 + culture = CultureInfo.CreateSpecificCulture("en-NZ"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1.6326E+004 + + specifier = "F"; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,63 + culture = CultureInfo.CreateSpecificCulture("en-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325.63 + + specifier = "N"; + culture = CultureInfo.CreateSpecificCulture("es-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16.325,63 + culture = CultureInfo.CreateSpecificCulture("fr-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16 325,63 + + specifier = "P"; + culture = CultureInfo.InvariantCulture; + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.26 % + culture = CultureInfo.CreateSpecificCulture("ar-EG"); + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.256 % + // + } } diff --git a/snippets/csharp/System/Single/ToString/ToString7.cs b/snippets/csharp/System/Single/ToString/ToString7.cs index bef287d882e..50919b4bab4 100644 --- a/snippets/csharp/System/Single/ToString/ToString7.cs +++ b/snippets/csharp/System/Single/ToString/ToString7.cs @@ -3,16 +3,16 @@ public class Example { - public static void Main() - { - Double number = 1764.3789; - - // Format as a currency value. - Console.WriteLine(number.ToString("C")); - - // Format as a numeric value with 3 decimal places. - Console.WriteLine(number.ToString("N3")); - } + public static void Main() + { + double number = 1764.3789; + + // Format as a currency value. + Console.WriteLine(number.ToString("C")); + + // Format as a numeric value with 3 decimal places. + Console.WriteLine(number.ToString("N3")); + } } // The example displays the following output: // $1,764.38 diff --git a/snippets/csharp/System/Single/TryParse/tryparse1.cs b/snippets/csharp/System/Single/TryParse/tryparse1.cs index a04439a3ead..ae03065cb59 100644 --- a/snippets/csharp/System/Single/TryParse/tryparse1.cs +++ b/snippets/csharp/System/Single/TryParse/tryparse1.cs @@ -2,100 +2,100 @@ public class Class1 { - public static void Main() - { - DefaultTryParse(); - Console.WriteLine("----------"); - TryParseWithConstraints(); - } + public static void Main() + { + DefaultTryParse(); + Console.WriteLine("----------"); + TryParseWithConstraints(); + } - private static void DefaultTryParse() - { - // - string value; - float number; + private static void DefaultTryParse() + { + // + string value; + float number; - // Parse a floating-point value with a thousands separator. - value = "1,643.57"; - if (Single.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a thousands separator. + value = "1,643.57"; + if (float.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a floating-point value with a currency symbol and a - // thousands separator. - value = "$1,643.57"; - if (Single.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a currency symbol and a + // thousands separator. + value = "$1,643.57"; + if (float.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse value in exponential notation. - value = "-1.643e6"; - if (Single.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse value in exponential notation. + value = "-1.643e6"; + if (float.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a negative integer value. - value = "-168934617882109132"; - if (Single.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); - // The example displays the following output: - // 1643.57 - // Unable to parse '$1,643.57'. - // -164300 - // -1.689346E+17 - // - } + // Parse a negative integer value. + value = "-168934617882109132"; + if (float.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); + // The example displays the following output: + // 1643.57 + // Unable to parse '$1,643.57'. + // -164300 + // -1.689346E+17 + // + } - private static void TryParseWithConstraints() - { - // - string value; - System.Globalization.NumberStyles style; - System.Globalization.CultureInfo culture; - float number; + private static void TryParseWithConstraints() + { + // + string value; + System.Globalization.NumberStyles style; + System.Globalization.CultureInfo culture; + float number; - // Parse currency value using en-GB culture. - value = "£1,097.63"; - style = System.Globalization.NumberStyles.Number | - System.Globalization.NumberStyles.AllowCurrencySymbol; - culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"); - if (Single.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); + // Parse currency value using en-GB culture. + value = "£1,097.63"; + style = System.Globalization.NumberStyles.Number | + System.Globalization.NumberStyles.AllowCurrencySymbol; + culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"); + if (float.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); - value = "1345,978"; - style = System.Globalization.NumberStyles.AllowDecimalPoint; - culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR"); - if (Single.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); + value = "1345,978"; + style = System.Globalization.NumberStyles.AllowDecimalPoint; + culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR"); + if (float.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); - value = "1.345,978"; - style = System.Globalization.NumberStyles.AllowDecimalPoint | - System.Globalization.NumberStyles.AllowThousands; - culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES"); - if (Single.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); + value = "1.345,978"; + style = System.Globalization.NumberStyles.AllowDecimalPoint | + System.Globalization.NumberStyles.AllowThousands; + culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES"); + if (float.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); - value = "1 345,978"; - if (Single.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // The example displays the following output: - // Converted '£1,097.63' to 1097.63. - // Converted '1345,978' to 1345.978. - // Converted '1.345,978' to 1345.978. - // Unable to convert '1 345,978'. - // - } + value = "1 345,978"; + if (float.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // The example displays the following output: + // Converted '£1,097.63' to 1097.63. + // Converted '1345,978' to 1345.978. + // Converted '1.345,978' to 1345.978. + // Unable to convert '1 345,978'. + // + } } diff --git a/snippets/csharp/System/Span.Enumerator/Program.cs b/snippets/csharp/System/Span.Enumerator/Program.cs index 02899297953..b6a091df094 100644 --- a/snippets/csharp/System/Span.Enumerator/Program.cs +++ b/snippets/csharp/System/Span.Enumerator/Program.cs @@ -10,9 +10,9 @@ static void Main() new Random(42).NextBytes(_array); Span span = _array; - Task.Run( () => ClearContents() ); + Task.Run(() => ClearContents()); - EnumerateSpan(span); + EnumerateSpan(span); } public static void ClearContents() @@ -20,7 +20,7 @@ public static void ClearContents() Task.Delay(20).Wait(); lock (_array) { - Array.Clear(_array, 0, _array.Length); + Array.Clear(_array, 0, _array.Length); } } @@ -38,4 +38,4 @@ public static void EnumerateSpan(Span span) // 23 // 186 // 0 -// 0 \ No newline at end of file +// 0 diff --git a/snippets/csharp/System/Span.Enumerator/Program2.cs b/snippets/csharp/System/Span.Enumerator/Program2.cs index d53b5c46324..c475bb77a87 100644 --- a/snippets/csharp/System/Span.Enumerator/Program2.cs +++ b/snippets/csharp/System/Span.Enumerator/Program2.cs @@ -10,7 +10,7 @@ static void Main() new Random(42).NextBytes(_array); Span span = _array; - Task.Run( () => ClearContents() ); + Task.Run(() => ClearContents()); EnumerateSpan(span); } @@ -20,7 +20,7 @@ public static void ClearContents() Task.Delay(20).Wait(); lock (_array) { - Array.Clear(_array, 0, _array.Length); + Array.Clear(_array, 0, _array.Length); } } diff --git a/snippets/csharp/System/Span/Overview/program.cs b/snippets/csharp/System/Span/Overview/program.cs index 51beba48d5e..4fff2f1868e 100644 --- a/snippets/csharp/System/Span/Overview/program.cs +++ b/snippets/csharp/System/Span/Overview/program.cs @@ -28,7 +28,7 @@ private static void CreateSpanFromArray() arraySpan[ctr] = data++; int arraySum = 0; - foreach (var value in array) + foreach (byte value in array) arraySum += value; Console.WriteLine($"The sum is {arraySum}"); @@ -44,14 +44,14 @@ private static void CreateSpanFromNativeMemory() Span nativeSpan; unsafe { - nativeSpan = new Span(native.ToPointer(), 100); + nativeSpan = new(native.ToPointer(), 100); } byte data = 0; for (int ctr = 0; ctr < nativeSpan.Length; ctr++) nativeSpan[ctr] = data++; int nativeSum = 0; - foreach (var value in nativeSpan) + foreach (byte value in nativeSpan) nativeSum += value; Console.WriteLine($"The sum is {nativeSum}"); @@ -70,7 +70,7 @@ private static void CreateSpanFromStack() stackSpan[ctr] = data++; int stackSum = 0; - foreach (var value in stackSpan) + foreach (byte value in stackSpan) stackSum += value; Console.WriteLine($"The sum is {stackSum}"); @@ -96,7 +96,7 @@ public static void WorkWithSpans() Span nativeSpan; unsafe { - nativeSpan = new Span(native.ToPointer(), 100); + nativeSpan = new(native.ToPointer(), 100); } InitializeSpan(nativeSpan); @@ -121,7 +121,7 @@ public static void InitializeSpan(Span span) public static int ComputeSum(Span span) { int sum = 0; - foreach (var value in span) + foreach (byte value in span) sum += value; return sum; diff --git a/snippets/csharp/System/Span/Slice/Program.cs b/snippets/csharp/System/Span/Slice/Program.cs index 4bd2e3d18d4..f959f0f9f26 100644 --- a/snippets/csharp/System/Span/Slice/Program.cs +++ b/snippets/csharp/System/Span/Slice/Program.cs @@ -1,12 +1,12 @@ using System; -var array = new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; +int[] array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; var slice = new Span(array, 2, 5); for (int ctr = 0; ctr < slice.Length; ctr++) slice[ctr] *= 2; // Examine the original array values. -foreach (var value in array) +foreach (int value in array) Console.Write($"{value} "); Console.WriteLine(); diff --git a/snippets/csharp/System/Span/Slice/Program2.cs b/snippets/csharp/System/Span/Slice/Program2.cs index 75bfaeff52a..704b362b732 100644 --- a/snippets/csharp/System/Span/Slice/Program2.cs +++ b/snippets/csharp/System/Span/Slice/Program2.cs @@ -5,7 +5,7 @@ class Program2 static void Run() { string contentLength = "Content-Length: 132"; - var length = GetContentLength(contentLength.ToCharArray()); + int length = GetContentLength(contentLength.ToCharArray()); Console.WriteLine($"Content length: {length}"); } diff --git a/snippets/csharp/System/StackOverflowException/Overview/example1a.cs b/snippets/csharp/System/StackOverflowException/Overview/example1a.cs index d71ade38be9..b39da408413 100644 --- a/snippets/csharp/System/StackOverflowException/Overview/example1a.cs +++ b/snippets/csharp/System/StackOverflowException/Overview/example1a.cs @@ -3,27 +3,27 @@ public class Example { - private const int MAX_RECURSIVE_CALLS = 1000; - static int ctr = 0; - - public static void Main() - { - Example ex = new Example(); - ex.Execute(); - Console.WriteLine("\nThe call counter: {0}", ctr); - } + private const int MAX_RECURSIVE_CALLS = 1000; + static int ctr = 0; - private void Execute() - { - ctr++; - if (ctr % 50 == 0) - Console.WriteLine("Call number {0} to the Execute method", ctr); - - if (ctr <= MAX_RECURSIVE_CALLS) - Execute(); - - ctr--; - } + public static void Main() + { + Example ex = new(); + ex.Execute(); + Console.WriteLine($"\nThe call counter: {ctr}"); + } + + private void Execute() + { + ctr++; + if (ctr % 50 == 0) + Console.WriteLine($"Call number {ctr} to the Execute method"); + + if (ctr <= MAX_RECURSIVE_CALLS) + Execute(); + + ctr--; + } } // The example displays the following output: // Call number 50 to the Execute method From 11b0a69b1a6b22da0c9c108f21c9e14d361e12c3 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 13 Aug 2026 14:12:21 -0700 Subject: [PATCH 2/9] Update code modernization skill (#12983) --- .github/skills/csharp-snippet-modernization/SKILL.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/skills/csharp-snippet-modernization/SKILL.md b/.github/skills/csharp-snippet-modernization/SKILL.md index 1e693a6f124..eeffbf9e23f 100644 --- a/.github/skills/csharp-snippet-modernization/SKILL.md +++ b/.github/skills/csharp-snippet-modernization/SKILL.md @@ -23,8 +23,8 @@ Apply these changes when they preserve behavior and sample clarity: - Use top-level statements where possible. - Use C# built-in aliases, such as `string`, `int`, and `bool`, instead of - framework type names. -- Use target-typed `new` when the target type is evident. + framework type names. Use `nint` and `nuint` for `IntPtr` and `UIntPtr`. +- Remove calls to `ToString()` when the result is used in a string context, unless the call is the subject of the snippet. - Use string interpolation instead of composite formatting, unless it makes the code harder to read or the composite-format overload is the subject of the snippet. For example, keep composite formatting when the arguments are complex: @@ -34,8 +34,8 @@ Apply these changes when they preserve behavior and sample clarity: timeZoneTime.DateTime); ``` - Use raw string literals (or interpolated raw string literals) for paragraph-style output. -- Use object and collection initializers when evaluation order and behavior - remain unchanged. +- Use target-typed `new` when the target type is evident. +- Use collection expressions to initialize collections and arrays wherever possible. - Convert eligible value-producing `switch` statements to switch expressions. - Use auto-implemented properties instead of defining a separate field. - Use expression-bodied members for simple single-expression members. If the line gets too long, for example, a method signature with a type parameter constraint, place the expression body on a new line: From 1962e74e8f15f4b2e36c12f7e97492d84f5b1f17 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 13 Aug 2026 16:10:57 -0700 Subject: [PATCH 3/9] Modernize C# snippets - Comparison{T}, System/L-O* (#12968) --- .../System/ComparisonT/Overview/Program.cs | 2 + .../ComparisonT/Overview/Project.csproj | 8 + .../ComparisonT/Overview/comparisont1.cs | 95 +++++----- .../System/ComparisonT/Overview/source.cs | 26 +-- snippets/csharp/System/LazyT/.ctor/Program.cs | 6 + .../csharp/System/LazyT/.ctor/Project.csproj | 8 + snippets/csharp/System/LazyT/.ctor/example.cs | 17 +- .../csharp/System/LazyT/.ctor/example1.cs | 13 +- .../csharp/System/LazyT/.ctor/example2.cs | 20 +- .../csharp/System/LazyT/.ctor/example3.cs | 19 +- .../csharp/System/LazyT/.ctor/example4.cs | 27 ++- .../csharp/System/LazyT/.ctor/example5.cs | 22 +-- .../csharp/System/LazyT/Overview/Program.cs | 2 + .../System/LazyT/Overview/Project.csproj | 8 + .../csharp/System/LazyT/Overview/example.cs | 17 +- .../csharp/System/LazyT/Overview/lambda.cs | 17 +- snippets/csharp/System/Math/Abs/Abs1.cs | 32 ++-- snippets/csharp/System/Math/Abs/Program.cs | 7 + .../csharp/System/Math/Abs/Project.csproj | 8 + snippets/csharp/System/Math/Abs/abs2.cs | 36 ++-- snippets/csharp/System/Math/Abs/abs3.cs | 47 ++--- snippets/csharp/System/Math/Abs/abs4.cs | 47 ++--- snippets/csharp/System/Math/Abs/abs5.cs | 47 ++--- snippets/csharp/System/Math/Abs/abs6.cs | 45 ++--- snippets/csharp/System/Math/Abs/abs7.cs | 36 ++-- snippets/csharp/System/Math/Atan/atan.cs | 58 +++--- snippets/csharp/System/Math/BigMul/bigmul.cs | 16 +- .../csharp/System/Math/Ceiling/Ceiling1.cs | 86 +++++---- snippets/csharp/System/Math/Cos/sincos.cs | 62 +++---- snippets/csharp/System/Math/Cosh/sinhcosh.cs | 38 ++-- snippets/csharp/System/Math/DivRem/Program.cs | 2 + .../csharp/System/Math/DivRem/Project.csproj | 8 + snippets/csharp/System/Math/DivRem/divrem1.cs | 37 ++-- snippets/csharp/System/Math/DivRem/divrem2.cs | 37 ++-- snippets/csharp/System/Math/E/efield.cs | 14 +- snippets/csharp/System/Math/Exp/exp.cs | 20 +- .../Math/IEEERemainder/ieeeremainder1.cs | 44 ++--- snippets/csharp/System/Math/Log10/log10.cs | 15 +- snippets/csharp/System/Math/LogMethod/log1.cs | 32 ++-- .../csharp/System/Math/LogMethod/loggen.cs | 18 +- snippets/csharp/System/Math/Max/max.cs | 22 +-- snippets/csharp/System/Math/Min/min.cs | 22 +-- .../csharp/System/Math/Overview/mathsample.cs | 120 ++++++------ snippets/csharp/System/Math/Pow/pow1.cs | 84 ++++----- snippets/csharp/System/Math/Round/Program.cs | 7 + .../csharp/System/Math/Round/Project.csproj | 8 + snippets/csharp/System/Math/Round/round2.cs | 30 +-- snippets/csharp/System/Math/Round/round3.cs | 14 +- snippets/csharp/System/Math/Round/round4.cs | 33 ++-- snippets/csharp/System/Math/Round/round5.cs | 32 ++-- .../csharp/System/Math/Round/rounddecimal1.cs | 32 ++-- snippets/csharp/System/Math/Round/source.cs | 18 +- snippets/csharp/System/Math/Round/source1.cs | 24 +-- snippets/csharp/System/Math/Sign/sign.cs | 18 +- snippets/csharp/System/Math/Sqrt/sqrt1.cs | 42 ++--- snippets/csharp/System/Math/Tanh/tanh.cs | 28 ++- .../csharp/System/Math/Truncate/Truncate1.cs | 42 ++--- .../Overview/MissingMethodException.cs | 18 +- .../Overview/delegatestring.cs | 171 +++++++++--------- .../Overview/program.cs | 30 +-- .../Overview/BadState1.cs | 6 +- .../Overview/TestProp1.cs | 11 +- .../Overview/TestProp2.cs | 11 +- .../NullReferenceException/Overview/Array1.cs | 5 +- .../NullReferenceException/Overview/Array2.cs | 6 +- .../NullReferenceException/Overview/Chain1.cs | 2 +- .../NullReferenceException/Overview/Chain2.cs | 2 +- .../Overview/example2.cs | 5 +- .../Overview/example3.cs | 9 +- .../Overview/nullreturn2.cs | 7 +- .../System/Nullable/GetUnderlyingType/gut.cs | 31 ++-- snippets/csharp/System/NullableT/Equals/eq.cs | 50 ++--- .../NullableT/GetValueOrDefault/gvod.cs | 90 +++++---- .../System/NullableT/HasValue/hasvalue2.cs | 45 ++--- .../csharp/System/NullableT/Overview/tarow.cs | 75 ++++---- .../csharp/System/NullableT/ToString/ts.cs | 32 ++-- .../System/NullableT/op_Explicit/explicit1.cs | 18 +- .../csharp/System/Object/Equals/equals2.cs | 39 ++-- .../csharp/System/Object/Equals/equals3.cs | 92 +++++----- .../csharp/System/Object/Equals/equals4.cs | 55 ++---- .../csharp/System/Object/Equals/equals_ref.cs | 38 ++-- .../System/Object/Equals/equals_static2.cs | 78 ++++---- .../System/Object/Equals/equals_val1.cs | 26 +-- .../System/Object/Equals/equals_val2.cs | 30 ++- .../System/Object/Equals/equalsoverride.cs | 49 +++-- .../csharp/System/Object/Equals/equalssb1.cs | 22 +-- .../System/Object/Finalize/finalize1.cs | 41 ++--- .../System/Object/Finalize/finalize_safe.cs | 8 +- .../System/Object/GetHashCode/direct1.cs | 55 +++--- .../System/Object/GetHashCode/shift1.cs | 31 ++-- .../csharp/System/Object/GetHashCode/xor1.cs | 31 ++-- .../csharp/System/Object/GetHashCode/xor2.cs | 25 ++- .../System/Object/GetType/GetTypeEx2.cs | 60 +++--- .../csharp/System/Object/GetType/Program.cs | 3 + .../System/Object/GetType/Project.csproj | 8 + .../csharp/System/Object/GetType/gettype.cs | 28 +-- .../csharp/System/Object/GetType/gettype1.cs | 30 ++- .../MemberwiseClone/memberwiseclone1.cs | 16 +- .../csharp/System/Object/Overview/ObjectX.cs | 29 +-- .../System/Object/ReferenceEquals/Program.cs | 3 + .../Object/ReferenceEquals/Project.csproj | 8 + .../Object/ReferenceEquals/referenceequals.cs | 35 ++-- .../ReferenceEquals/referenceequals4.cs | 24 +-- .../ReferenceEquals/referenceequalsa.cs | 42 ++--- .../csharp/System/Object/ToString/array1.cs | 24 +-- .../System/Object/ToString/customize1.cs | 43 +++-- .../System/Object/ToString/customize2.cs | 63 +++---- .../System/Object/ToString/tostring1.cs | 18 +- .../System/Object/ToString/tostring2.cs | 16 +- .../System/Object/ToString/tostring3.cs | 22 +-- .../Object/ToString/tostringoverload1.cs | 95 +++++----- .../Object/ToString/tostringoverload2.cs | 21 ++- .../Overview/dispose1.cs | 23 +-- .../Overview/objdispexc.cs | 28 +-- .../IsError/obsoleteattribute_message.cs | 72 ++++---- .../ObsoleteAttribute/Overview/Project.csproj | 8 + .../Overview/obsoleteattributeex1.cs | 65 +++---- .../Overview/snippets.5000.json | 10 + .../System/OperatingSystem/Clone/clone.cs | 32 ++-- .../OperatingSystem/Overview/osinfo1.cs | 24 +-- .../OperatingSystem/Platform/plat_ver.cs | 45 +++-- .../System/OperatingSystem/ServicePack/sp.cs | 8 +- .../OperatingSystem/ToString/ctor_tostr.cs | 40 ++-- .../OperatingSystem/VersionString/osvs.cs | 10 +- .../OutOfMemoryException/Overview/Program.cs | 4 + .../Overview/Project.csproj | 8 + .../OutOfMemoryException/Overview/data1.cs | 53 +++--- .../OutOfMemoryException/Overview/data2.cs | 71 ++++---- .../Overview/failfast1.cs | 47 ++--- .../Overview/sb_example1.cs | 26 +-- .../OverflowException/Overview/arithmetic1.cs | 117 ++++++------ xml/System/ObsoleteAttribute.xml | 11 +- 132 files changed, 2058 insertions(+), 2151 deletions(-) create mode 100644 snippets/csharp/System/ComparisonT/Overview/Program.cs create mode 100644 snippets/csharp/System/ComparisonT/Overview/Project.csproj create mode 100644 snippets/csharp/System/LazyT/.ctor/Program.cs create mode 100644 snippets/csharp/System/LazyT/.ctor/Project.csproj create mode 100644 snippets/csharp/System/LazyT/Overview/Program.cs create mode 100644 snippets/csharp/System/LazyT/Overview/Project.csproj create mode 100644 snippets/csharp/System/Math/Abs/Program.cs create mode 100644 snippets/csharp/System/Math/Abs/Project.csproj create mode 100644 snippets/csharp/System/Math/DivRem/Program.cs create mode 100644 snippets/csharp/System/Math/DivRem/Project.csproj create mode 100644 snippets/csharp/System/Math/Round/Program.cs create mode 100644 snippets/csharp/System/Math/Round/Project.csproj create mode 100644 snippets/csharp/System/Object/GetType/Program.cs create mode 100644 snippets/csharp/System/Object/GetType/Project.csproj create mode 100644 snippets/csharp/System/Object/ReferenceEquals/Program.cs create mode 100644 snippets/csharp/System/Object/ReferenceEquals/Project.csproj create mode 100644 snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj create mode 100644 snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json create mode 100644 snippets/csharp/System/OutOfMemoryException/Overview/Program.cs create mode 100644 snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj diff --git a/snippets/csharp/System/ComparisonT/Overview/Program.cs b/snippets/csharp/System/ComparisonT/Overview/Program.cs new file mode 100644 index 00000000000..fa4c677450d --- /dev/null +++ b/snippets/csharp/System/ComparisonT/Overview/Program.cs @@ -0,0 +1,2 @@ +ComparisonTOverviewExample1.Run(); +ComparisonTOverviewExample2.Run(); diff --git a/snippets/csharp/System/ComparisonT/Overview/Project.csproj b/snippets/csharp/System/ComparisonT/Overview/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/ComparisonT/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs b/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs index fbc3ab48f1e..1155811397d 100644 --- a/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs +++ b/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs @@ -3,75 +3,62 @@ public class CityInfo { - string cityName; - string countryName; - int pop2010; + string cityName; + string countryName; + int pop2010; - public CityInfo(string name, string country, int pop2010) - { - this.cityName = name; - this.countryName = country; - this.pop2010 = pop2010; - } + public CityInfo(string name, string country, int pop2010) + { + this.cityName = name; + this.countryName = country; + this.pop2010 = pop2010; + } - public string City - { get { return this.cityName; } } + public string City => this.cityName; - public string Country - { get { return this.countryName; } } + public string Country => this.countryName; - public int Population - { get { return this.pop2010; } } + public int Population => this.pop2010; - public static int CompareByName(CityInfo city1, CityInfo city2) - { - return String.Compare(city1.City, city2.City); - } + public static int CompareByName(CityInfo city1, CityInfo city2) => string.Compare(city1.City, city2.City); - public static int CompareByPopulation(CityInfo city1, CityInfo city2) - { - return city1.Population.CompareTo(city2.Population); - } + public static int CompareByPopulation(CityInfo city1, CityInfo city2) => city1.Population.CompareTo(city2.Population); - public static int CompareByNames(CityInfo city1, CityInfo city2) - { - return String.Compare(city1.Country + city1.City, city2.Country + city2.City); - } + public static int CompareByNames(CityInfo city1, CityInfo city2) => string.Compare(city1.Country + city1.City, city2.Country + city2.City); } -public class Example +public class ComparisonTOverviewExample1 { - public static void Main() - { - CityInfo NYC = new CityInfo("New York City", "United States of America", 8175133 ); - CityInfo Det = new CityInfo("Detroit", "United States of America", 713777); - CityInfo Paris = new CityInfo("Paris", "France", 2193031); - CityInfo[] cities = { NYC, Det, Paris }; - // Display ordered array. - DisplayArray(cities); + public static void Run() + { + CityInfo NYC = new("New York City", "United States of America", 8175133); + CityInfo Det = new("Detroit", "United States of America", 713777); + CityInfo Paris = new("Paris", "France", 2193031); + CityInfo[] cities = { NYC, Det, Paris }; + // Display ordered array. + DisplayArray(cities); - // Sort array by city name. - Array.Sort(cities, CityInfo.CompareByName); - DisplayArray(cities); + // Sort array by city name. + Array.Sort(cities, CityInfo.CompareByName); + DisplayArray(cities); - // Sort array by population. - Array.Sort(cities, CityInfo.CompareByPopulation); - DisplayArray(cities); + // Sort array by population. + Array.Sort(cities, CityInfo.CompareByPopulation); + DisplayArray(cities); - // Sort array by country + city name. - Array.Sort(cities, CityInfo.CompareByNames); - DisplayArray(cities); - } + // Sort array by country + city name. + Array.Sort(cities, CityInfo.CompareByNames); + DisplayArray(cities); + } - private static void DisplayArray(CityInfo[] cities) - { - Console.WriteLine("{0,-20} {1,-25} {2,10}", "City", "Country", "Population"); - foreach (var city in cities) - Console.WriteLine("{0,-20} {1,-25} {2,10:N0}", city.City, - city.Country, city.Population); + private static void DisplayArray(CityInfo[] cities) + { + Console.WriteLine($"{"City",-20} {"Country",-25} {"Population",10}"); + foreach (var city in cities) + Console.WriteLine($"{city.City,-20} {city.Country,-25} {city.Population,10:N0}"); - Console.WriteLine(); - } + Console.WriteLine(); + } } // The example displays the following output: // City Country Population diff --git a/snippets/csharp/System/ComparisonT/Overview/source.cs b/snippets/csharp/System/ComparisonT/Overview/source.cs index 4ffc0ed59bb..ded501522c8 100644 --- a/snippets/csharp/System/ComparisonT/Overview/source.cs +++ b/snippets/csharp/System/ComparisonT/Overview/source.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; -public class Example +public class ComparisonTOverviewExample2 { private static int CompareDinosByLength(string x, string y) { @@ -26,7 +26,7 @@ private static int CompareDinosByLength(string x, string y) // If x is not null... // if (y == null) - // ...and y is null, x is greater. + // ...and y is null, x is greater. { return 1; } @@ -55,15 +55,17 @@ private static int CompareDinosByLength(string x, string y) } } - public static void Main() + public static void Run() { - List dinosaurs = new List(); - dinosaurs.Add("Pachycephalosaurus"); - dinosaurs.Add("Amargasaurus"); - dinosaurs.Add(""); - dinosaurs.Add(null); - dinosaurs.Add("Mamenchisaurus"); - dinosaurs.Add("Deinonychus"); + List dinosaurs = new() + { + "Pachycephalosaurus", + "Amargasaurus", + "", + null, + "Mamenchisaurus", + "Deinonychus" + }; Display(dinosaurs); Console.WriteLine("\nSort with generic Comparison delegate:"); @@ -74,12 +76,12 @@ public static void Main() private static void Display(List list) { Console.WriteLine(); - foreach( string s in list ) + foreach (string s in list) { if (s == null) Console.WriteLine("(null)"); else - Console.WriteLine("\"{0}\"", s); + Console.WriteLine($"\"{s}\""); } } } diff --git a/snippets/csharp/System/LazyT/.ctor/Program.cs b/snippets/csharp/System/LazyT/.ctor/Program.cs new file mode 100644 index 00000000000..18d5981ecf8 --- /dev/null +++ b/snippets/csharp/System/LazyT/.ctor/Program.cs @@ -0,0 +1,6 @@ +LazyCtorExample1.Run(); +LazyCtorExample2.Run(); +LazyCtorExample3.Run(); +LazyCtorExample4.Run(); +LazyCtorExample5.Run(); +LazyCtorExample6.Run(); diff --git a/snippets/csharp/System/LazyT/.ctor/Project.csproj b/snippets/csharp/System/LazyT/.ctor/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/LazyT/.ctor/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/LazyT/.ctor/example.cs b/snippets/csharp/System/LazyT/.ctor/example.cs index 53baccaab31..910c9e28ba5 100644 --- a/snippets/csharp/System/LazyT/.ctor/example.cs +++ b/snippets/csharp/System/LazyT/.ctor/example.cs @@ -1,12 +1,13 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample1; -class Program +class LazyCtorExample1 { static Lazy lazyLargeObject = null; - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -25,7 +26,7 @@ static void Main() Console.ReadLine(); // Create and start 3 threads, passing the same blocking event to all of them. - ManualResetEvent startingGate = new ManualResetEvent(false); + ManualResetEvent startingGate = new(false); Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) }; foreach (Thread t in threads) { @@ -49,7 +50,7 @@ static void Main() static void ThreadProc(object state) { // Wait for the signal. - ManualResetEvent waitForStart = (ManualResetEvent) state; + ManualResetEvent waitForStart = (ManualResetEvent)state; waitForStart.WaitOne(); // @@ -62,7 +63,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", @@ -71,12 +72,12 @@ static void ThreadProc(object state) } } -class LargeObject +class LargeObjectCtorExample1 { int initBy = 0; - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; - public LargeObject() + public LargeObjectCtorExample1() { initBy = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("LargeObject was created on thread id {0}.", initBy); diff --git a/snippets/csharp/System/LazyT/.ctor/example1.cs b/snippets/csharp/System/LazyT/.ctor/example1.cs index d05e301ad74..d7938abc811 100644 --- a/snippets/csharp/System/LazyT/.ctor/example1.cs +++ b/snippets/csharp/System/LazyT/.ctor/example1.cs @@ -1,12 +1,13 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample2; -class Program +class LazyCtorExample2 { static Lazy lazyLargeObject = null; - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -34,13 +35,9 @@ static void Main() } } -class LargeObject +class LargeObjectCtorExample2 { - public LargeObject() - { - Console.WriteLine("LargeObject was created on thread id {0}.", - Thread.CurrentThread.ManagedThreadId); - } + public LargeObjectCtorExample2() => Console.WriteLine($"LargeObject was created on thread id {Thread.CurrentThread.ManagedThreadId}."); public long[] Data = new long[100000000]; } diff --git a/snippets/csharp/System/LazyT/.ctor/example2.cs b/snippets/csharp/System/LazyT/.ctor/example2.cs index 94f0bac084e..b2e3f48919e 100644 --- a/snippets/csharp/System/LazyT/.ctor/example2.cs +++ b/snippets/csharp/System/LazyT/.ctor/example2.cs @@ -1,19 +1,17 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample3; -class Program +class LazyCtorExample3 { static Lazy lazyLargeObject = null; // - static LargeObject InitLargeObject() - { - return new LargeObject(); - } + static LargeObject InitLargeObject() => new LargeObject(); // - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -58,7 +56,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", @@ -67,20 +65,20 @@ static void ThreadProc(object state) } catch (ApplicationException aex) { - Console.WriteLine("Exception: {0}", aex.Message); + Console.WriteLine($"Exception: {aex.Message}"); } // } } -class LargeObject +class LargeObjectCtorExample3 { int initBy = 0; - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; // static int instanceCount = 0; - public LargeObject() + public LargeObjectCtorExample3() { if (1 == Interlocked.Increment(ref instanceCount)) { diff --git a/snippets/csharp/System/LazyT/.ctor/example3.cs b/snippets/csharp/System/LazyT/.ctor/example3.cs index 634f125726b..2588d098243 100644 --- a/snippets/csharp/System/LazyT/.ctor/example3.cs +++ b/snippets/csharp/System/LazyT/.ctor/example3.cs @@ -1,19 +1,17 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample4; -class Program +class LazyCtorExample4 { static Lazy lazyLargeObject = null; // - static LargeObject InitLargeObject() - { - return new LargeObject(); - } + static LargeObject InitLargeObject() => new LargeObject(); // - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -40,7 +38,7 @@ static void Main() } catch (ApplicationException aex) { - Console.WriteLine("Exception: {0}", aex.Message); + Console.WriteLine($"Exception: {aex.Message}"); } } // @@ -50,11 +48,11 @@ static void Main() } } -class LargeObject +class LargeObjectCtorExample4 { // static bool pleaseThrow = true; - public LargeObject() + public LargeObjectCtorExample4() { if (pleaseThrow) { @@ -62,8 +60,7 @@ public LargeObject() throw new ApplicationException("Throw only ONCE."); } - Console.WriteLine("LargeObject was created on thread id {0}.", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"LargeObject was created on thread id {Thread.CurrentThread.ManagedThreadId}."); } // public long[] Data = new long[100000000]; diff --git a/snippets/csharp/System/LazyT/.ctor/example4.cs b/snippets/csharp/System/LazyT/.ctor/example4.cs index 768f57b38ea..6c97044e88e 100644 --- a/snippets/csharp/System/LazyT/.ctor/example4.cs +++ b/snippets/csharp/System/LazyT/.ctor/example4.cs @@ -1,8 +1,9 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample5; -class Program +class LazyCtorExample5 { static Lazy lazyLargeObject = null; @@ -14,14 +15,13 @@ static LargeObject InitLargeObject() if (1 == Interlocked.Increment(ref instanceCount)) { throw new ApplicationException( - String.Format("Lazy initialization function failed on thread {0}.", - Thread.CurrentThread.ManagedThreadId)); + $"Lazy initialization function failed on thread {Thread.CurrentThread.ManagedThreadId}."); } return new LargeObject(Thread.CurrentThread.ManagedThreadId); } // - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -31,7 +31,7 @@ static void Main() // // Create and start 3 threads, passing the same blocking event to all of them. - ManualResetEvent startingGate = new ManualResetEvent(false); + ManualResetEvent startingGate = new(false); Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) }; foreach (Thread t in threads) { @@ -64,7 +64,7 @@ static void Main() static void ThreadProc(object state) { // Wait for the signal. - ManualResetEvent waitForStart = (ManualResetEvent) state; + ManualResetEvent waitForStart = (ManualResetEvent)state; waitForStart.WaitOne(); // @@ -79,7 +79,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("LargeObject was initialized by thread {0}; last used by thread {1}.", @@ -88,28 +88,25 @@ static void ThreadProc(object state) } catch (ApplicationException ex) { - Console.WriteLine("ApplicationException: {0}", ex.Message); + Console.WriteLine($"ApplicationException: {ex.Message}"); } // } } -class LargeObject +class LargeObjectCtorExample5 { int initBy = -1; - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; // - public LargeObject(int initializedBy) + public LargeObjectCtorExample5(int initializedBy) { initBy = initializedBy; Console.WriteLine("Constructor: Instance initializing on thread {0}", initBy); } - ~LargeObject() - { - Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy); - } + ~LargeObjectCtorExample5() => Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy); // public long[] Data = new long[100000000]; diff --git a/snippets/csharp/System/LazyT/.ctor/example5.cs b/snippets/csharp/System/LazyT/.ctor/example5.cs index 8e3403efd25..b6335414466 100644 --- a/snippets/csharp/System/LazyT/.ctor/example5.cs +++ b/snippets/csharp/System/LazyT/.ctor/example5.cs @@ -1,12 +1,13 @@ // using System; using System.Threading; +using LargeObject = LargeObjectCtorExample6; -class Program +class LazyCtorExample6 { static Lazy lazyLargeObject = null; - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -15,7 +16,7 @@ static void Main() // // Create and start 3 threads, passing the same blocking event to all of them. - ManualResetEvent startingGate = new ManualResetEvent(false); + ManualResetEvent startingGate = new(false); Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) }; foreach (Thread t in threads) { @@ -49,7 +50,7 @@ static void Main() static void ThreadProc(object state) { // Wait for the signal. - ManualResetEvent waitForStart = (ManualResetEvent) state; + ManualResetEvent waitForStart = (ManualResetEvent)state; waitForStart.WaitOne(); // @@ -63,7 +64,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("LargeObject was initialized by thread {0}; last used by thread {1}.", @@ -72,22 +73,19 @@ static void ThreadProc(object state) } } -class LargeObject +class LargeObjectCtorExample6 { int initBy = -1; - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; // - public LargeObject() + public LargeObjectCtorExample6() { initBy = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Constructor: Instance initializing on thread {0}", initBy); } - ~LargeObject() - { - Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy); - } + ~LargeObjectCtorExample6() => Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy); // public long[] Data = new long[100000000]; diff --git a/snippets/csharp/System/LazyT/Overview/Program.cs b/snippets/csharp/System/LazyT/Overview/Program.cs new file mode 100644 index 00000000000..22896b8011d --- /dev/null +++ b/snippets/csharp/System/LazyT/Overview/Program.cs @@ -0,0 +1,2 @@ +LazyOverviewExample1.Run(); +LazyOverviewExample2.Run(); diff --git a/snippets/csharp/System/LazyT/Overview/Project.csproj b/snippets/csharp/System/LazyT/Overview/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/LazyT/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/LazyT/Overview/example.cs b/snippets/csharp/System/LazyT/Overview/example.cs index a5be10f8635..c61c673e31a 100644 --- a/snippets/csharp/System/LazyT/Overview/example.cs +++ b/snippets/csharp/System/LazyT/Overview/example.cs @@ -1,21 +1,22 @@ // using System; using System.Threading; +using LargeObject = LargeObjectOverviewExample1; -class Program +class LazyOverviewExample1 { static Lazy lazyLargeObject = null; // static LargeObject InitLargeObject() { - LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId); + LargeObject large = new(Thread.CurrentThread.ManagedThreadId); // Perform additional initialization here. return large; } // - static void Main() + public static void Run() { // The lazy initializer is created here. LargeObject is not created until the // ThreadProc method executes. @@ -38,7 +39,7 @@ static void Main() Thread[] threads = new Thread[3]; for (int i = 0; i < 3; i++) { - threads[i] = new Thread(ThreadProc); + threads[i] = new(ThreadProc); threads[i].Start(); } @@ -60,7 +61,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", @@ -70,13 +71,13 @@ static void ThreadProc(object state) } } -class LargeObject +class LargeObjectOverviewExample1 { - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; // int initBy = 0; - public LargeObject(int initializedBy) + public LargeObjectOverviewExample1(int initializedBy) { initBy = initializedBy; Console.WriteLine("LargeObject was created on thread id {0}.", initBy); diff --git a/snippets/csharp/System/LazyT/Overview/lambda.cs b/snippets/csharp/System/LazyT/Overview/lambda.cs index 2067f9837bd..e9939c4b39a 100644 --- a/snippets/csharp/System/LazyT/Overview/lambda.cs +++ b/snippets/csharp/System/LazyT/Overview/lambda.cs @@ -1,16 +1,17 @@ using System; using System.Threading; +using LargeObject = LargeObjectOverviewExample2; -class Program +class LazyOverviewExample2 { static Lazy lazyLargeObject = null; - static void Main() + public static void Run() { // lazyLargeObject = new Lazy(() => { - LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId); + LargeObject large = new(Thread.CurrentThread.ManagedThreadId); // Perform additional initialization here. return large; }); @@ -25,7 +26,7 @@ static void Main() Thread[] threads = new Thread[3]; for (int i = 0; i < 3; i++) { - threads[i] = new Thread(ThreadProc); + threads[i] = new(ThreadProc); threads[i].Start(); } @@ -46,7 +47,7 @@ static void ThreadProc(object state) // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the // object after creation. You must lock the object before accessing it, // unless the type is thread safe. (LargeObject is not thread safe.) - lock(large) + lock (large) { large.Data[0] = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", @@ -55,12 +56,12 @@ static void ThreadProc(object state) } } -class LargeObject +class LargeObjectOverviewExample2 { - public int InitializedBy { get { return initBy; } } + public int InitializedBy => initBy; int initBy = 0; - public LargeObject(int initializedBy) + public LargeObjectOverviewExample2(int initializedBy) { initBy = initializedBy; Console.WriteLine("LargeObject was created on thread id {0}.", initBy); diff --git a/snippets/csharp/System/Math/Abs/Abs1.cs b/snippets/csharp/System/Math/Abs/Abs1.cs index a8a3403f890..91ebdcecb62 100644 --- a/snippets/csharp/System/Math/Abs/Abs1.cs +++ b/snippets/csharp/System/Math/Abs/Abs1.cs @@ -1,21 +1,21 @@ using System; -public class Example +public class MathAbsExample1 { - public static void Main() - { - // - decimal[] decimals = { Decimal.MaxValue, 12.45M, 0M, -19.69M, - Decimal.MinValue }; - foreach (decimal value in decimals) - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + public static void Run() + { + // + decimal[] decimals = { decimal.MaxValue, 12.45M, 0M, -19.69M, + decimal.MinValue }; + foreach (decimal value in decimals) + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - // The example displays the following output: - // Abs(79228162514264337593543950335) = 79228162514264337593543950335 - // Abs(12.45) = 12.45 - // Abs(0) = 0 - // Abs(-19.69) = 19.69 - // Abs(-79228162514264337593543950335) = 79228162514264337593543950335 - // - } + // The example displays the following output: + // Abs(79228162514264337593543950335) = 79228162514264337593543950335 + // Abs(12.45) = 12.45 + // Abs(0) = 0 + // Abs(-19.69) = 19.69 + // Abs(-79228162514264337593543950335) = 79228162514264337593543950335 + // + } } diff --git a/snippets/csharp/System/Math/Abs/Program.cs b/snippets/csharp/System/Math/Abs/Program.cs new file mode 100644 index 00000000000..98ae5302805 --- /dev/null +++ b/snippets/csharp/System/Math/Abs/Program.cs @@ -0,0 +1,7 @@ +MathAbsExample1.Run(); +MathAbsExample2.Run(); +MathAbsExample3.Run(); +MathAbsExample4.Run(); +MathAbsExample5.Run(); +MathAbsExample6.Run(); +MathAbsExample7.Run(); diff --git a/snippets/csharp/System/Math/Abs/Project.csproj b/snippets/csharp/System/Math/Abs/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/Math/Abs/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/Math/Abs/abs2.cs b/snippets/csharp/System/Math/Abs/abs2.cs index 5c5bca5462a..bd0869db31e 100644 --- a/snippets/csharp/System/Math/Abs/abs2.cs +++ b/snippets/csharp/System/Math/Abs/abs2.cs @@ -1,23 +1,23 @@ using System; -public class Example +public class MathAbsExample2 { - public static void Main() - { - // - double[] doubles = { Double.MaxValue, 16.354e-17, 15.098123, 0, - -19.069713, -15.058e18, Double.MinValue }; - foreach (double value in doubles) - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + public static void Run() + { + // + double[] doubles = { double.MaxValue, 16.354e-17, 15.098123, 0, + -19.069713, -15.058e18, double.MinValue }; + foreach (double value in doubles) + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - // The example displays the following output: - // Abs(1.79769313486232E+308) = 1.79769313486232E+308 - // Abs(1.6354E-16) = 1.6354E-16 - // Abs(15.098123) = 15.098123 - // Abs(0) = 0 - // Abs(-19.069713) = 19.069713 - // Abs(-1.5058E+19) = 1.5058E+19 - // Abs(-1.79769313486232E+308) = 1.79769313486232E+308 - // - } + // The example displays the following output: + // Abs(1.79769313486232E+308) = 1.79769313486232E+308 + // Abs(1.6354E-16) = 1.6354E-16 + // Abs(15.098123) = 15.098123 + // Abs(0) = 0 + // Abs(-19.069713) = 19.069713 + // Abs(-1.5058E+19) = 1.5058E+19 + // Abs(-1.79769313486232E+308) = 1.79769313486232E+308 + // + } } diff --git a/snippets/csharp/System/Math/Abs/abs3.cs b/snippets/csharp/System/Math/Abs/abs3.cs index b37c617cd7a..28275eb681c 100644 --- a/snippets/csharp/System/Math/Abs/abs3.cs +++ b/snippets/csharp/System/Math/Abs/abs3.cs @@ -1,28 +1,29 @@ using System; -public class Example +public class MathAbsExample3 { - public static void Main() - { - // - short[] values = { Int16.MaxValue, 10328, 0, -1476, Int16.MinValue }; - foreach (short value in values) - { - try { - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - } - catch (OverflowException) { - Console.WriteLine("Unable to calculate the absolute value of {0}.", - value); - } - } + public static void Run() + { + // + short[] values = { short.MaxValue, 10328, 0, -1476, short.MinValue }; + foreach (short value in values) + { + try + { + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + } + catch (OverflowException) + { + Console.WriteLine($"Unable to calculate the absolute value of {value}."); + } + } - // The example displays the following output: - // Abs(32767) = 32767 - // Abs(10328) = 10328 - // Abs(0) = 0 - // Abs(-1476) = 1476 - // Unable to calculate the absolute value of -32768. - // - } + // The example displays the following output: + // Abs(32767) = 32767 + // Abs(10328) = 10328 + // Abs(0) = 0 + // Abs(-1476) = 1476 + // Unable to calculate the absolute value of -32768. + // + } } diff --git a/snippets/csharp/System/Math/Abs/abs4.cs b/snippets/csharp/System/Math/Abs/abs4.cs index dea56d9505d..e3138e4b8ae 100644 --- a/snippets/csharp/System/Math/Abs/abs4.cs +++ b/snippets/csharp/System/Math/Abs/abs4.cs @@ -1,28 +1,29 @@ using System; -public class Example +public class MathAbsExample4 { - public static void Main() - { - // - int[] values = { Int32.MaxValue, 16921, 0, -804128, Int32.MinValue }; - foreach (int value in values) - { - try { - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - } - catch (OverflowException) { - Console.WriteLine("Unable to calculate the absolute value of {0}.", - value); - } - } + public static void Run() + { + // + int[] values = { int.MaxValue, 16921, 0, -804128, int.MinValue }; + foreach (int value in values) + { + try + { + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + } + catch (OverflowException) + { + Console.WriteLine($"Unable to calculate the absolute value of {value}."); + } + } - // The example displays the following output: - // Abs(2147483647) = 2147483647 - // Abs(16921) = 16921 - // Abs(0) = 0 - // Abs(-804128) = 804128 - // Unable to calculate the absolute value of -2147483648. - // - } + // The example displays the following output: + // Abs(2147483647) = 2147483647 + // Abs(16921) = 16921 + // Abs(0) = 0 + // Abs(-804128) = 804128 + // Unable to calculate the absolute value of -2147483648. + // + } } diff --git a/snippets/csharp/System/Math/Abs/abs5.cs b/snippets/csharp/System/Math/Abs/abs5.cs index 99dd0159d3a..410a8ef34b6 100644 --- a/snippets/csharp/System/Math/Abs/abs5.cs +++ b/snippets/csharp/System/Math/Abs/abs5.cs @@ -1,28 +1,29 @@ using System; -public class Example +public class MathAbsExample5 { - public static void Main() - { - // - long[] values = { Int64.MaxValue, 109013, 0, -6871982, Int64.MinValue }; - foreach (long value in values) - { - try { - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - } - catch (OverflowException) { - Console.WriteLine("Unable to calculate the absolute value of {0}.", - value); - } - } + public static void Run() + { + // + long[] values = { long.MaxValue, 109013, 0, -6871982, long.MinValue }; + foreach (long value in values) + { + try + { + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + } + catch (OverflowException) + { + Console.WriteLine($"Unable to calculate the absolute value of {value}."); + } + } - // The example displays the following output: - // Abs(9223372036854775807) = 9223372036854775807 - // Abs(109013) = 109013 - // Abs(0) = 0 - // Abs(-6871982) = 6871982 - // Unable to calculate the absolute value of -9223372036854775808. - // - } + // The example displays the following output: + // Abs(9223372036854775807) = 9223372036854775807 + // Abs(109013) = 109013 + // Abs(0) = 0 + // Abs(-6871982) = 6871982 + // Unable to calculate the absolute value of -9223372036854775808. + // + } } diff --git a/snippets/csharp/System/Math/Abs/abs6.cs b/snippets/csharp/System/Math/Abs/abs6.cs index ab5cf586f80..b617e930716 100644 --- a/snippets/csharp/System/Math/Abs/abs6.cs +++ b/snippets/csharp/System/Math/Abs/abs6.cs @@ -1,28 +1,29 @@ using System; -public class Example +public class MathAbsExample6 { - public static void Main() + public static void Run() { - // - sbyte[] values = { SByte.MaxValue, 98, 0, -32, SByte.MinValue }; - foreach (sbyte value in values) - { - try { - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - } - catch (OverflowException) { - Console.WriteLine("Unable to calculate the absolute value of {0}.", - value); - } - } + // + sbyte[] values = { sbyte.MaxValue, 98, 0, -32, sbyte.MinValue }; + foreach (sbyte value in values) + { + try + { + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + } + catch (OverflowException) + { + Console.WriteLine($"Unable to calculate the absolute value of {value}."); + } + } - // The example displays the following output: - // Abs(127) = 127 - // Abs(98) = 98 - // Abs(0) = 0 - // Abs(-32) = 32 - // Unable to calculate the absolute value of -128. - // - } + // The example displays the following output: + // Abs(127) = 127 + // Abs(98) = 98 + // Abs(0) = 0 + // Abs(-32) = 32 + // Unable to calculate the absolute value of -128. + // + } } diff --git a/snippets/csharp/System/Math/Abs/abs7.cs b/snippets/csharp/System/Math/Abs/abs7.cs index 7ea386cde58..b2d0c1b70b4 100644 --- a/snippets/csharp/System/Math/Abs/abs7.cs +++ b/snippets/csharp/System/Math/Abs/abs7.cs @@ -1,23 +1,23 @@ using System; -public class Example +public class MathAbsExample7 { - public static void Main() - { - // - float[] values= { Single.MaxValue, 16.354e-12F, 15.098123F, 0F, - -19.069713F, -15.058e17F, Single.MinValue }; - foreach (float value in values) - Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); + public static void Run() + { + // + float[] values = { float.MaxValue, 16.354e-12F, 15.098123F, 0F, + -19.069713F, -15.058e17F, float.MinValue }; + foreach (float value in values) + Console.WriteLine($"Abs({value}) = {Math.Abs(value)}"); - // The example displays the following output: - // Abs(3.402823E+38) = 3.402823E+38 - // Abs(1.6354E-11) = 1.6354E-11 - // Abs(15.09812) = 15.09812 - // Abs(0) = 0 - // Abs(-19.06971) = 19.06971 - // Abs(-1.5058E+18) = 1.5058E+18 - // Abs(-3.402823E+38) = 3.402823E+38 - // - } + // The example displays the following output: + // Abs(3.402823E+38) = 3.402823E+38 + // Abs(1.6354E-11) = 1.6354E-11 + // Abs(15.09812) = 15.09812 + // Abs(0) = 0 + // Abs(-19.06971) = 19.06971 + // Abs(-1.5058E+18) = 1.5058E+18 + // Abs(-3.402823E+38) = 3.402823E+38 + // + } } diff --git a/snippets/csharp/System/Math/Atan/atan.cs b/snippets/csharp/System/Math/Atan/atan.cs index 0880e906d89..b50dacd3be6 100644 --- a/snippets/csharp/System/Math/Atan/atan.cs +++ b/snippets/csharp/System/Math/Atan/atan.cs @@ -8,34 +8,34 @@ class Sample { public static void Main() { - double x = 1.0; - double y = 2.0; - double angle; - double radians; - double result; - -// Calculate the tangent of 30 degrees. - angle = 30; - radians = angle * (Math.PI/180); - result = Math.Tan(radians); - Console.WriteLine("The tangent of 30 degrees is {0}.", result); - -// Calculate the arctangent of the previous tangent. - radians = Math.Atan(result); - angle = radians * (180/Math.PI); - Console.WriteLine("The previous tangent is equivalent to {0} degrees.", angle); - -// Calculate the arctangent of an angle. - String line1 = "{0}The arctangent of the angle formed by the x-axis and "; - String line2 = "a vector to point ({0},{1}) is {2}, "; - String line3 = "which is equivalent to {0} degrees."; - - radians = Math.Atan2(y, x); - angle = radians * (180/Math.PI); - - Console.WriteLine(line1, Environment.NewLine); - Console.WriteLine(line2, x, y, radians); - Console.WriteLine(line3, angle); + double x = 1.0; + double y = 2.0; + double angle; + double radians; + double result; + + // Calculate the tangent of 30 degrees. + angle = 30; + radians = angle * (Math.PI / 180); + result = Math.Tan(radians); + Console.WriteLine($"The tangent of 30 degrees is {result}."); + + // Calculate the arctangent of the previous tangent. + radians = Math.Atan(result); + angle = radians * (180 / Math.PI); + Console.WriteLine($"The previous tangent is equivalent to {angle} degrees."); + + // Calculate the arctangent of an angle. + string line1 = "{0}The arctangent of the angle formed by the x-axis and "; + string line2 = "a vector to point ({0},{1}) is {2}, "; + string line3 = "which is equivalent to {0} degrees."; + + radians = Math.Atan2(y, x); + angle = radians * (180 / Math.PI); + + Console.WriteLine(line1, Environment.NewLine); + Console.WriteLine(line2, x, y, radians); + Console.WriteLine(line3, angle); } } /* @@ -48,4 +48,4 @@ The arctangent of the angle formed by the x-axis and a vector to point (1,2) is 1.10714871779409, which is equivalent to 63.434948822922 degrees. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Math/BigMul/bigmul.cs b/snippets/csharp/System/Math/BigMul/bigmul.cs index 22b26ca9855..77bfae833d3 100644 --- a/snippets/csharp/System/Math/BigMul/bigmul.cs +++ b/snippets/csharp/System/Math/BigMul/bigmul.cs @@ -6,13 +6,13 @@ class Sample { public static void Main() { - int int1 = Int32.MaxValue; - int int2 = Int32.MaxValue; - long longResult; -// - longResult = Math.BigMul(int1, int2); - Console.WriteLine("Calculate the product of two Int32 values:"); - Console.WriteLine("{0} * {1} = {2}", int1, int2, longResult); + int int1 = int.MaxValue; + int int2 = int.MaxValue; + long longResult; + // + longResult = Math.BigMul(int1, int2); + Console.WriteLine("Calculate the product of two Int32 values:"); + Console.WriteLine($"{int1} * {int2} = {longResult}"); } } /* @@ -20,4 +20,4 @@ public static void Main() Calculate the product of two Int32 values: 2147483647 * 2147483647 = 4611686014132420609 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Math/Ceiling/Ceiling1.cs b/snippets/csharp/System/Math/Ceiling/Ceiling1.cs index 0a49c4ecf24..e86a94c6527 100644 --- a/snippets/csharp/System/Math/Ceiling/Ceiling1.cs +++ b/snippets/csharp/System/Math/Ceiling/Ceiling1.cs @@ -2,50 +2,48 @@ public class Class1 { - public static void Main() - { - CeilingWithDecimal(); - Console.WriteLine(); - CeilingWithDouble(); - } + public static void Main() + { + CeilingWithDecimal(); + Console.WriteLine(); + CeilingWithDouble(); + } - private static void CeilingWithDecimal() - { - // - decimal[] values = {7.03m, 7.64m, 0.12m, -0.12m, -7.1m, -7.6m}; - Console.WriteLine(" Value Ceiling Floor\n"); - foreach (decimal value in values) - Console.WriteLine("{0,7} {1,16} {2,14}", - value, Math.Ceiling(value), Math.Floor(value)); - // The example displays the following output to the console: - // Value Ceiling Floor - // - // 7.03 8 7 - // 7.64 8 7 - // 0.12 1 0 - // -0.12 0 -1 - // -7.1 -7 -8 - // -7.6 -7 -8 - // - } + private static void CeilingWithDecimal() + { + // + decimal[] values = { 7.03m, 7.64m, 0.12m, -0.12m, -7.1m, -7.6m }; + Console.WriteLine(" Value Ceiling Floor\n"); + foreach (decimal value in values) + Console.WriteLine($"{value,7} {Math.Ceiling(value),16} {Math.Floor(value),14}"); + // The example displays the following output to the console: + // Value Ceiling Floor + // + // 7.03 8 7 + // 7.64 8 7 + // 0.12 1 0 + // -0.12 0 -1 + // -7.1 -7 -8 + // -7.6 -7 -8 + // + } - private static void CeilingWithDouble() - { - // - double[] values = {7.03, 7.64, 0.12, -0.12, -7.1, -7.6}; - Console.WriteLine(" Value Ceiling Floor\n"); - foreach (double value in values) - Console.WriteLine("{0,7} {1,16} {2,14}", - value, Math.Ceiling(value), Math.Floor(value)); - // The example displays the following output to the console: - // Value Ceiling Floor - // - // 7.03 8 7 - // 7.64 8 7 - // 0.12 1 0 - // -0.12 0 -1 - // -7.1 -7 -8 - // -7.6 -7 -8 - // - } + private static void CeilingWithDouble() + { + // + double[] values = { 7.03, 7.64, 0.12, -0.12, -7.1, -7.6 }; + Console.WriteLine(" Value Ceiling Floor\n"); + foreach (double value in values) + Console.WriteLine($"{value,7} {Math.Ceiling(value),16} {Math.Floor(value),14}"); + // The example displays the following output to the console: + // Value Ceiling Floor + // + // 7.03 8 7 + // 7.64 8 7 + // 0.12 1 0 + // -0.12 0 -1 + // -7.1 -7 -8 + // -7.6 -7 -8 + // + } } diff --git a/snippets/csharp/System/Math/Cos/sincos.cs b/snippets/csharp/System/Math/Cos/sincos.cs index 6fdf596ae5c..3253a3b016f 100644 --- a/snippets/csharp/System/Math/Cos/sincos.cs +++ b/snippets/csharp/System/Math/Cos/sincos.cs @@ -10,14 +10,14 @@ public static void Main() Console.WriteLine( "This example of trigonometric " + "Math.Sin( double ), Math.Cos( double ), and Math.SinCos( double )\n" + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Convert selected values for X to radians \n" + - "and evaluate these trigonometric identities:" ); - Console.WriteLine( " sin^2(X) + cos^2(X) == 1\n" + - " sin(2 * X) == 2 * sin(X) * cos(X)" ); - Console.WriteLine( " cos(2 * X) == cos^2(X) - sin^2(X)" ); - Console.WriteLine( " cos(2 * X) == cos^2(X) - sin^2(X)" ); + "and evaluate these trigonometric identities:"); + Console.WriteLine(" sin^2(X) + cos^2(X) == 1\n" + + " sin(2 * X) == 2 * sin(X) * cos(X)"); + Console.WriteLine(" cos(2 * X) == cos^2(X) - sin^2(X)"); + Console.WriteLine(" cos(2 * X) == cos^2(X) - sin^2(X)"); UseSineCosine(15.0); UseSineCosine(30.0); @@ -25,16 +25,16 @@ public static void Main() Console.WriteLine( "\nConvert selected values for X and Y to radians \n" + - "and evaluate these trigonometric identities:" ); - Console.WriteLine( " sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y)" ); - Console.WriteLine( " cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y)" ); + "and evaluate these trigonometric identities:"); + Console.WriteLine(" sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y)"); + Console.WriteLine(" cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y)"); UseTwoAngles(15.0, 30.0); UseTwoAngles(30.0, 45.0); Console.WriteLine( "\nWhen you have calls to sin(X) and cos(X) they \n" + - "can be replaced with a single call to sincos(x):" ); + "can be replaced with a single call to sincos(x):"); UseCombinedSineCosine(15.0); UseCombinedSineCosine(30.0); @@ -48,21 +48,15 @@ static void UseCombinedSineCosine(double degrees) (double sinAngle, double cosAngle) = Math.SinCos(angle); // Evaluate sin^2(X) + cos^2(X) == 1. - Console.WriteLine( - "\n Math.SinCos({0} deg) == ({1:E16}, {2:E16})", - degrees, sinAngle, cosAngle); - Console.WriteLine( - "(double sin, double cos) = Math.SinCos({0} deg)", - degrees ); - Console.WriteLine( - "sin^2 + cos^2 == {0:E16}", - sinAngle * sinAngle + cosAngle * cosAngle ); + Console.WriteLine($"\n Math.SinCos({degrees} deg) == ({sinAngle:E16}, {cosAngle:E16})"); + Console.WriteLine($"(double sin, double cos) = Math.SinCos({degrees} deg)"); + Console.WriteLine($"sin^2 + cos^2 == {sinAngle * sinAngle + cosAngle * cosAngle:E16}"); } // Evaluate trigonometric identities with a given angle. static void UseSineCosine(double degrees) { - double angle = Math.PI * degrees / 180.0; + double angle = Math.PI * degrees / 180.0; double sinAngle = Math.Sin(angle); double cosAngle = Math.Cos(angle); @@ -70,33 +64,29 @@ static void UseSineCosine(double degrees) Console.WriteLine( "\n Math.Sin({0} deg) == {1:E16}\n" + " Math.Cos({0} deg) == {2:E16}", - degrees, Math.Sin(angle), Math.Cos(angle) ); + degrees, Math.Sin(angle), Math.Cos(angle)); Console.WriteLine( "(Math.Sin({0} deg))^2 + (Math.Cos({0} deg))^2 == {1:E16}", - degrees, sinAngle * sinAngle + cosAngle * cosAngle ); + degrees, sinAngle * sinAngle + cosAngle * cosAngle); // Evaluate sin(2 * X) == 2 * sin(X) * cos(X). - Console.WriteLine( - " Math.Sin({0} deg) == {1:E16}", - 2.0 * degrees, Math.Sin(2.0 * angle) ); + Console.WriteLine($" Math.Sin({2.0 * degrees} deg) == {Math.Sin(2.0 * angle):E16}"); Console.WriteLine( " 2 * Math.Sin({0} deg) * Math.Cos({0} deg) == {1:E16}", - degrees, 2.0 * sinAngle * cosAngle ); + degrees, 2.0 * sinAngle * cosAngle); // Evaluate cos(2 * X) == cos^2(X) - sin^2(X). - Console.WriteLine( - " Math.Cos({0} deg) == {1:E16}", - 2.0 * degrees, Math.Cos(2.0 * angle) ); + Console.WriteLine($" Math.Cos({2.0 * degrees} deg) == {Math.Cos(2.0 * angle):E16}"); Console.WriteLine( "(Math.Cos({0} deg))^2 - (Math.Sin({0} deg))^2 == {1:E16}", - degrees, cosAngle * cosAngle - sinAngle * sinAngle ); + degrees, cosAngle * cosAngle - sinAngle * sinAngle); } // Evaluate trigonometric identities that are functions of two angles. static void UseTwoAngles(double degreesX, double degreesY) { - double angleX = Math.PI * degreesX / 180.0; - double angleY = Math.PI * degreesY / 180.0; + double angleX = Math.PI * degreesX / 180.0; + double angleY = Math.PI * degreesY / 180.0; // Evaluate sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y). Console.WriteLine( @@ -104,9 +94,7 @@ static void UseTwoAngles(double degreesX, double degreesY) " Math.Cos({0} deg) * Math.Sin({1} deg) == {2:E16}", degreesX, degreesY, Math.Sin(angleX) * Math.Cos(angleY) + Math.Cos(angleX) * Math.Sin(angleY)); - Console.WriteLine( - " Math.Sin({0} deg) == {1:E16}", - degreesX + degreesY, Math.Sin(angleX + angleY)); + Console.WriteLine($" Math.Sin({degreesX + degreesY} deg) == {Math.Sin(angleX + angleY):E16}"); // Evaluate cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y). Console.WriteLine( @@ -114,9 +102,7 @@ static void UseTwoAngles(double degreesX, double degreesY) " Math.Sin({0} deg) * Math.Sin({1} deg) == {2:E16}", degreesX, degreesY, Math.Cos(angleX) * Math.Cos(angleY) - Math.Sin(angleX) * Math.Sin(angleY)); - Console.WriteLine( - " Math.Cos({0} deg) == {1:E16}", - degreesX + degreesY, Math.Cos(angleX + angleY)); + Console.WriteLine($" Math.Cos({degreesX + degreesY} deg) == {Math.Cos(angleX + angleY):E16}"); } } diff --git a/snippets/csharp/System/Math/Cosh/sinhcosh.cs b/snippets/csharp/System/Math/Cosh/sinhcosh.cs index 8649d0dcebb..d05396059d1 100644 --- a/snippets/csharp/System/Math/Cosh/sinhcosh.cs +++ b/snippets/csharp/System/Math/Cosh/sinhcosh.cs @@ -10,14 +10,14 @@ public static void Main() Console.WriteLine( "This example of hyperbolic Math.Sinh( double ) " + "and Math.Cosh( double )\n" + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Evaluate these hyperbolic identities " + - "with selected values for X:" ); + "with selected values for X:"); Console.WriteLine( " cosh^2(X) - sinh^2(X) == 1\n" + - " sinh(2 * X) == 2 * sinh(X) * cosh(X)" ); - Console.WriteLine( " cosh(2 * X) == cosh^2(X) + sinh^2(X)" ); + " sinh(2 * X) == 2 * sinh(X) * cosh(X)"); + Console.WriteLine(" cosh(2 * X) == cosh^2(X) + sinh^2(X)"); UseSinhCosh(0.1); UseSinhCosh(1.2); @@ -25,11 +25,11 @@ public static void Main() Console.WriteLine( "\nEvaluate these hyperbolic identities " + - "with selected values for X and Y:" ); + "with selected values for X and Y:"); Console.WriteLine( - " sinh(X + Y) == sinh(X) * cosh(Y) + cosh(X) * sinh(Y)" ); + " sinh(X + Y) == sinh(X) * cosh(Y) + cosh(X) * sinh(Y)"); Console.WriteLine( - " cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y)" ); + " cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y)"); UseTwoArgs(0.1, 1.2); UseTwoArgs(1.2, 4.9); @@ -45,26 +45,22 @@ static void UseSinhCosh(double arg) Console.WriteLine( "\n Math.Sinh({0}) == {1:E16}\n" + " Math.Cosh({0}) == {2:E16}", - arg, Math.Sinh(arg), Math.Cosh(arg) ); + arg, Math.Sinh(arg), Math.Cosh(arg)); Console.WriteLine( "(Math.Cosh({0}))^2 - (Math.Sinh({0}))^2 == {1:E16}", - arg, coshArg * coshArg - sinhArg * sinhArg ); + arg, coshArg * coshArg - sinhArg * sinhArg); // Evaluate sinh(2 * X) == 2 * sinh(X) * cosh(X). - Console.WriteLine( - " Math.Sinh({0}) == {1:E16}", - 2.0 * arg, Math.Sinh(2.0 * arg) ); + Console.WriteLine($" Math.Sinh({2.0 * arg}) == {Math.Sinh(2.0 * arg):E16}"); Console.WriteLine( " 2 * Math.Sinh({0}) * Math.Cosh({0}) == {1:E16}", - arg, 2.0 * sinhArg * coshArg ); + arg, 2.0 * sinhArg * coshArg); // Evaluate cosh(2 * X) == cosh^2(X) + sinh^2(X). - Console.WriteLine( - " Math.Cosh({0}) == {1:E16}", - 2.0 * arg, Math.Cosh(2.0 * arg) ); + Console.WriteLine($" Math.Cosh({2.0 * arg}) == {Math.Cosh(2.0 * arg):E16}"); Console.WriteLine( "(Math.Cosh({0}))^2 + (Math.Sinh({0}))^2 == {1:E16}", - arg, coshArg * coshArg + sinhArg * sinhArg ); + arg, coshArg * coshArg + sinhArg * sinhArg); } // Evaluate hyperbolic identities that are functions of two arguments. @@ -76,9 +72,7 @@ static void UseTwoArgs(double argX, double argY) " Math.Cosh({0}) * Math.Sinh({1}) == {2:E16}", argX, argY, Math.Sinh(argX) * Math.Cosh(argY) + Math.Cosh(argX) * Math.Sinh(argY)); - Console.WriteLine( - " Math.Sinh({0}) == {1:E16}", - argX + argY, Math.Sinh(argX + argY)); + Console.WriteLine($" Math.Sinh({argX + argY}) == {Math.Sinh(argX + argY):E16}"); // Evaluate cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y). Console.WriteLine( @@ -86,9 +80,7 @@ static void UseTwoArgs(double argX, double argY) " Math.Sinh({0}) * Math.Sinh({1}) == {2:E16}", argX, argY, Math.Cosh(argX) * Math.Cosh(argY) + Math.Sinh(argX) * Math.Sinh(argY)); - Console.WriteLine( - " Math.Cosh({0}) == {1:E16}", - argX + argY, Math.Cosh(argX + argY)); + Console.WriteLine($" Math.Cosh({argX + argY}) == {Math.Cosh(argX + argY):E16}"); } } diff --git a/snippets/csharp/System/Math/DivRem/Program.cs b/snippets/csharp/System/Math/DivRem/Program.cs new file mode 100644 index 00000000000..ee5f6f7ff64 --- /dev/null +++ b/snippets/csharp/System/Math/DivRem/Program.cs @@ -0,0 +1,2 @@ +MathDivRemExample1.Run(); +MathDivRemExample2.Run(); diff --git a/snippets/csharp/System/Math/DivRem/Project.csproj b/snippets/csharp/System/Math/DivRem/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/Math/DivRem/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/Math/DivRem/divrem1.cs b/snippets/csharp/System/Math/DivRem/divrem1.cs index 43a2253f196..7a19186de57 100644 --- a/snippets/csharp/System/Math/DivRem/divrem1.cs +++ b/snippets/csharp/System/Math/DivRem/divrem1.cs @@ -1,27 +1,26 @@ // using System; -public class Example +public class MathDivRemExample1 { - public static void Main() - { - // Define several positive and negative dividends. - int[] dividends = { Int32.MaxValue, 13952, 0, -14032, - Int32.MinValue }; - // Define one positive and one negative divisor. - int[] divisors = { 2000, -2000 }; + public static void Run() + { + // Define several positive and negative dividends. + int[] dividends = { int.MaxValue, 13952, 0, -14032, + int.MinValue }; + // Define one positive and one negative divisor. + int[] divisors = { 2000, -2000 }; - foreach (int divisor in divisors) - { - foreach (int dividend in dividends) - { - int remainder; - int quotient = Math.DivRem(dividend, divisor, out remainder); - Console.WriteLine(@"{0:N0} \ {1:N0} = {2:N0}, remainder {3:N0}", - dividend, divisor, quotient, remainder); - } - } - } + foreach (int divisor in divisors) + { + foreach (int dividend in dividends) + { + int remainder; + int quotient = Math.DivRem(dividend, divisor, out remainder); + Console.WriteLine($"{dividend:N0} \\ {divisor:N0} = {quotient:N0}, remainder {remainder:N0}"); + } + } + } } // The example displays the following output: // 2,147,483,647 \ 2,000 = 1,073,741, remainder 1,647 diff --git a/snippets/csharp/System/Math/DivRem/divrem2.cs b/snippets/csharp/System/Math/DivRem/divrem2.cs index 9fddf00056d..80c7dde90c2 100644 --- a/snippets/csharp/System/Math/DivRem/divrem2.cs +++ b/snippets/csharp/System/Math/DivRem/divrem2.cs @@ -1,27 +1,26 @@ // using System; -public class Example +public class MathDivRemExample2 { - public static void Main() - { - // Define several positive and negative dividends. - long[] dividends = { Int64.MaxValue, 13952, 0, -14032, - Int64.MinValue }; - // Define one positive and one negative divisor. - long[] divisors = { 2000, -2000 }; + public static void Run() + { + // Define several positive and negative dividends. + long[] dividends = { long.MaxValue, 13952, 0, -14032, + long.MinValue }; + // Define one positive and one negative divisor. + long[] divisors = { 2000, -2000 }; - foreach (long divisor in divisors) - { - foreach (long dividend in dividends) - { - long remainder; - long quotient = Math.DivRem(dividend, divisor, out remainder); - Console.WriteLine(@"{0:N0} \ {1:N0} = {2:N0}, remainder {3:N0}", - dividend, divisor, quotient, remainder); - } - } - } + foreach (long divisor in divisors) + { + foreach (long dividend in dividends) + { + long remainder; + long quotient = Math.DivRem(dividend, divisor, out remainder); + Console.WriteLine($"{dividend:N0} \\ {divisor:N0} = {quotient:N0}, remainder {remainder:N0}"); + } + } + } } // The example displays the following output: // 9,223,372,036,854,775,807 \ 2,000 = 4,611,686,018,427,387, remainder 1,807 diff --git a/snippets/csharp/System/Math/E/efield.cs b/snippets/csharp/System/Math/E/efield.cs index 73050c9fe3d..82eb0c73319 100644 --- a/snippets/csharp/System/Math/E/efield.cs +++ b/snippets/csharp/System/Math/E/efield.cs @@ -9,13 +9,13 @@ public static void Main() Console.WriteLine( "This example of Math.E == {0:E16}\n" + "generates the following output.\n", - Math.E ); + Math.E); Console.WriteLine( - "Define the power series PS(n) = Sum(k->0,n)[1/k!]" ); - Console.WriteLine( " (limit n->infinity)PS(n) == e" ); + "Define the power series PS(n) = Sum(k->0,n)[1/k!]"); + Console.WriteLine(" (limit n->infinity)PS(n) == e"); Console.WriteLine( "Display PS(n) and Math.E - PS(n), " + - "and stop when delta < 1.0E-15\n" ); + "and stop when delta < 1.0E-15\n"); CalcPowerSeries(); } @@ -28,17 +28,17 @@ static void CalcPowerSeries() // Stop iterating when the series converges, // and prevent a runaway process. - for( int n = 0; n < 999 && Math.Abs( Math.E - PS ) > 1.0E-15; n++ ) + for (int n = 0; n < 999 && Math.Abs(Math.E - PS) > 1.0E-15; n++) { // Calculate a running factorial. - if( n > 0 ) + if (n > 0) factorial *= (double)n; // Calculate and display the power series. PS += 1.0 / factorial; Console.WriteLine( "PS({0:D2}) == {1:E16}, Math.E - PS({0:D2}) == {2:E16}", - n, PS, Math.E - PS ); + n, PS, Math.E - PS); } } } diff --git a/snippets/csharp/System/Math/Exp/exp.cs b/snippets/csharp/System/Math/Exp/exp.cs index d6d9d593d39..fae76c02a1c 100644 --- a/snippets/csharp/System/Math/Exp/exp.cs +++ b/snippets/csharp/System/Math/Exp/exp.cs @@ -8,10 +8,10 @@ public static void Main() { Console.WriteLine( "This example of Math.Exp( double ) " + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Evaluate [e ^ ln(X) == ln(e ^ X) == X] " + - "with selected values for X:" ); + "with selected values for X:"); UseLnExp(0.1); UseLnExp(1.2); @@ -20,10 +20,10 @@ public static void Main() Console.WriteLine( "\nEvaluate these identities with " + - "selected values for X and Y:" ); - Console.WriteLine( " (e ^ X) * (e ^ Y) == e ^ (X + Y)" ); - Console.WriteLine( " (e ^ X) ^ Y == e ^ (X * Y)" ); - Console.WriteLine( " X ^ Y == e ^ (Y * ln(X))" ); + "selected values for X and Y:"); + Console.WriteLine(" (e ^ X) * (e ^ Y) == e ^ (X + Y)"); + Console.WriteLine(" (e ^ X) ^ Y == e ^ (X * Y)"); + Console.WriteLine(" X ^ Y == e ^ (Y * ln(X))"); UseTwoArgs(0.1, 1.2); UseTwoArgs(1.2, 4.9); @@ -37,7 +37,7 @@ static void UseLnExp(double arg) Console.WriteLine( "\n Math.Exp(Math.Log({0})) == {1:E16}\n" + " Math.Log(Math.Exp({0})) == {2:E16}", - arg, Math.Exp(Math.Log(arg)), Math.Log(Math.Exp(arg)) ); + arg, Math.Exp(Math.Log(arg)), Math.Log(Math.Exp(arg))); } // Evaluate exponential identities that are functions of two arguments. @@ -48,21 +48,21 @@ static void UseTwoArgs(double argX, double argY) "\nMath.Exp({0}) * Math.Exp({1}) == {2:E16}" + "\n Math.Exp({0} + {1}) == {3:E16}", argX, argY, Math.Exp(argX) * Math.Exp(argY), - Math.Exp(argX + argY) ); + Math.Exp(argX + argY)); // Evaluate (e ^ X) ^ Y == e ^ (X * Y). Console.WriteLine( " Math.Pow(Math.Exp({0}), {1}) == {2:E16}" + "\n Math.Exp({0} * {1}) == {3:E16}", argX, argY, Math.Pow(Math.Exp(argX), argY), - Math.Exp(argX * argY) ); + Math.Exp(argX * argY)); // Evaluate X ^ Y == e ^ (Y * ln(X)). Console.WriteLine( " Math.Pow({0}, {1}) == {2:E16}" + "\nMath.Exp({1} * Math.Log({0})) == {3:E16}", argX, argY, Math.Pow(argX, argY), - Math.Exp(argY * Math.Log(argX)) ); + Math.Exp(argY * Math.Log(argX))); } } diff --git a/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs b/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs index 9374237b135..8752e9cd3b0 100644 --- a/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs +++ b/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs @@ -3,29 +3,29 @@ public class Example { - public static void Main() - { - Console.WriteLine($"{"IEEERemainder",35} {"Remainder operator",20}"); - ShowRemainders(3, 2); - ShowRemainders(4, 2); - ShowRemainders(10, 3); - ShowRemainders(11, 3); - ShowRemainders(27, 4); - ShowRemainders(28, 5); - ShowRemainders(17.8, 4); - ShowRemainders(17.8, 4.1); - ShowRemainders(-16.3, 4.1); - ShowRemainders(17.8, -4.1); - ShowRemainders(-17.8, -4.1); - } + public static void Main() + { + Console.WriteLine($"{"IEEERemainder",35} {"Remainder operator",20}"); + ShowRemainders(3, 2); + ShowRemainders(4, 2); + ShowRemainders(10, 3); + ShowRemainders(11, 3); + ShowRemainders(27, 4); + ShowRemainders(28, 5); + ShowRemainders(17.8, 4); + ShowRemainders(17.8, 4.1); + ShowRemainders(-16.3, 4.1); + ShowRemainders(17.8, -4.1); + ShowRemainders(-17.8, -4.1); + } - private static void ShowRemainders(double number1, double number2) - { - var formula = $"{number1} / {number2} = "; - var ieeeRemainder = Math.IEEERemainder(number1, number2); - var remainder = number1 % number2; - Console.WriteLine($"{formula,-16} {ieeeRemainder,18} {remainder,20}"); - } + private static void ShowRemainders(double number1, double number2) + { + string formula = $"{number1} / {number2} = "; + double ieeeRemainder = Math.IEEERemainder(number1, number2); + double remainder = number1 % number2; + Console.WriteLine($"{formula,-16} {ieeeRemainder,18} {remainder,20}"); + } } // The example displays the following output: // diff --git a/snippets/csharp/System/Math/Log10/log10.cs b/snippets/csharp/System/Math/Log10/log10.cs index dbad2eab0c4..e9729e5f344 100644 --- a/snippets/csharp/System/Math/Log10/log10.cs +++ b/snippets/csharp/System/Math/Log10/log10.cs @@ -3,15 +3,14 @@ public class Example { - public static void Main() - { - double[] numbers = {-1, 0, .105, .5, .798, 1, 4, 6.9, 10, 50, - 100, 500, 1000, Double.MaxValue}; + public static void Main() + { + double[] numbers = {-1, 0, .105, .5, .798, 1, 4, 6.9, 10, 50, + 100, 500, 1000, double.MaxValue}; - foreach (double number in numbers) - Console.WriteLine("The base 10 log of {0} is {1}.", - number, Math.Log10(number)); - } + foreach (double number in numbers) + Console.WriteLine($"The base 10 log of {number} is {Math.Log10(number)}."); + } } // The example dislays the following output: // The base 10 log of -1 is NaN. diff --git a/snippets/csharp/System/Math/LogMethod/log1.cs b/snippets/csharp/System/Math/LogMethod/log1.cs index 410533c711a..1900a3f40f3 100644 --- a/snippets/csharp/System/Math/LogMethod/log1.cs +++ b/snippets/csharp/System/Math/LogMethod/log1.cs @@ -2,26 +2,24 @@ using System; public class Example { - public static void Main() - { - Console.WriteLine(" Evaluate this identity with selected values for X:"); - Console.WriteLine(" ln(x) = 1 / log[X](B)"); - Console.WriteLine(); + public static void Main() + { + Console.WriteLine(" Evaluate this identity with selected values for X:"); + Console.WriteLine(" ln(x) = 1 / log[X](B)"); + Console.WriteLine(); - double[] XArgs = { 1.2, 4.9, 9.9, 0.1 }; + double[] XArgs = { 1.2, 4.9, 9.9, 0.1 }; - foreach (double argX in XArgs) - { - // Find natural log of argX. - Console.WriteLine(" Math.Log({0}) = {1:E16}", - argX, Math.Log(argX)); + foreach (double argX in XArgs) + { + // Find natural log of argX. + Console.WriteLine($" Math.Log({argX}) = {Math.Log(argX):E16}"); - // Evaluate 1 / log[X](e). - Console.WriteLine(" 1.0 / Math.Log(e, {0}) = {1:E16}", - argX, 1.0 / Math.Log(Math.E, argX)); - Console.WriteLine(); - } - } + // Evaluate 1 / log[X](e). + Console.WriteLine($" 1.0 / Math.Log(e, {argX}) = {1.0 / Math.Log(Math.E, argX):E16}"); + Console.WriteLine(); + } + } } // This example displays the following output: // Evaluate this identity with selected values for X: diff --git a/snippets/csharp/System/Math/LogMethod/loggen.cs b/snippets/csharp/System/Math/LogMethod/loggen.cs index bf1a7f94139..97f703e8f66 100644 --- a/snippets/csharp/System/Math/LogMethod/loggen.cs +++ b/snippets/csharp/System/Math/LogMethod/loggen.cs @@ -9,13 +9,13 @@ public static void Main() Console.WriteLine( "This example of Math.Log( double ) and " + "Math.Log( double, double )\n" + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Evaluate these identities with " + - "selected values for X and B (base):" ); - Console.WriteLine( " log(B)[X] == 1 / log(X)[B]" ); - Console.WriteLine( " log(B)[X] == ln[X] / ln[B]" ); - Console.WriteLine( " log(B)[X] == log(B)[e] * ln[X]" ); + "selected values for X and B (base):"); + Console.WriteLine(" log(B)[X] == 1 / log(X)[B]"); + Console.WriteLine(" log(B)[X] == ln[X] / ln[B]"); + Console.WriteLine(" log(B)[X] == log(B)[e] * ln[X]"); UseBaseAndArg(0.1, 1.2); UseBaseAndArg(1.2, 4.9); @@ -31,17 +31,15 @@ static void UseBaseAndArg(double argB, double argX) "\n Math.Log({1}, {0}) == {2:E16}" + "\n 1.0 / Math.Log({0}, {1}) == {3:E16}", argB, argX, Math.Log(argX, argB), - 1.0 / Math.Log(argB, argX) ); + 1.0 / Math.Log(argB, argX)); // Evaluate log(B)[X] == ln[X] / ln[B]. Console.WriteLine( " Math.Log({1}) / Math.Log({0}) == {2:E16}", - argB, argX, Math.Log(argX) / Math.Log(argB) ); + argB, argX, Math.Log(argX) / Math.Log(argB)); // Evaluate log(B)[X] == log(B)[e] * ln[X]. - Console.WriteLine( - "Math.Log(Math.E, {0}) * Math.Log({1}) == {2:E16}", - argB, argX, Math.Log(Math.E, argB) * Math.Log(argX) ); + Console.WriteLine($"Math.Log(Math.E, {argB}) * Math.Log({argX}) == {Math.Log(Math.E, argB) * Math.Log(argX):E16}"); } } diff --git a/snippets/csharp/System/Math/Max/max.cs b/snippets/csharp/System/Math/Max/max.cs index f499bab3433..6512795cf44 100644 --- a/snippets/csharp/System/Math/Max/max.cs +++ b/snippets/csharp/System/Math/Max/max.cs @@ -8,19 +8,19 @@ public static void Main() // string str = "{0}: The greater of {1,3} and {2,3} is {3}."; - byte xByte1 = 1, xByte2 = 51; - short xShort1 = -2, xShort2 = 52; - int xInt1 = -3, xInt2 = 53; - long xLong1 = -4, xLong2 = 54; - float xSingle1 = 5.0f, xSingle2 = 55.0f; - double xDouble1 = 6.0, xDouble2 = 56.0; - Decimal xDecimal1 = 7m, xDecimal2 = 57m; + byte xByte1 = 1, xByte2 = 51; + short xShort1 = -2, xShort2 = 52; + int xInt1 = -3, xInt2 = 53; + long xLong1 = -4, xLong2 = 54; + float xSingle1 = 5.0f, xSingle2 = 55.0f; + double xDouble1 = 6.0, xDouble2 = 56.0; + decimal xDecimal1 = 7m, xDecimal2 = 57m; // The following types are not CLS-compliant. - sbyte xSbyte1 = 101, xSbyte2 = 111; - ushort xUshort1 = 102, xUshort2 = 112; - uint xUint1 = 103, xUint2 = 113; - ulong xUlong1 = 104, xUlong2 = 114; + sbyte xSbyte1 = 101, xSbyte2 = 111; + ushort xUshort1 = 102, xUshort2 = 112; + uint xUint1 = 103, xUint2 = 113; + ulong xUlong1 = 104, xUlong2 = 114; Console.WriteLine("Display the greater of two values:\n"); Console.WriteLine(str, "Byte ", xByte1, xByte2, Math.Max(xByte1, xByte2)); diff --git a/snippets/csharp/System/Math/Min/min.cs b/snippets/csharp/System/Math/Min/min.cs index 9c790bb9a2c..223041e316a 100644 --- a/snippets/csharp/System/Math/Min/min.cs +++ b/snippets/csharp/System/Math/Min/min.cs @@ -8,19 +8,19 @@ public static void Main() // string str = "{0}: The lesser of {1,3} and {2,3} is {3}."; - byte xByte1 = 1, xByte2 = 51; - short xShort1 = -2, xShort2 = 52; - int xInt1 = -3, xInt2 = 53; - long xLong1 = -4, xLong2 = 54; - float xSingle1 = 5.0f, xSingle2 = 55.0f; - double xDouble1 = 6.0, xDouble2 = 56.0; - Decimal xDecimal1 = 7m, xDecimal2 = 57m; + byte xByte1 = 1, xByte2 = 51; + short xShort1 = -2, xShort2 = 52; + int xInt1 = -3, xInt2 = 53; + long xLong1 = -4, xLong2 = 54; + float xSingle1 = 5.0f, xSingle2 = 55.0f; + double xDouble1 = 6.0, xDouble2 = 56.0; + decimal xDecimal1 = 7m, xDecimal2 = 57m; // The following types are not CLS-compliant. - sbyte xSbyte1 = 101, xSbyte2 = 111; - ushort xUshort1 = 102, xUshort2 = 112; - uint xUint1 = 103, xUint2 = 113; - ulong xUlong1 = 104, xUlong2 = 114; + sbyte xSbyte1 = 101, xSbyte2 = 111; + ushort xUshort1 = 102, xUshort2 = 112; + uint xUint1 = 103, xUint2 = 113; + ulong xUlong1 = 104, xUlong2 = 114; Console.WriteLine("Display the lesser of two values:\n"); Console.WriteLine(str, "Byte ", xByte1, xByte2, Math.Min(xByte1, xByte2)); diff --git a/snippets/csharp/System/Math/Overview/mathsample.cs b/snippets/csharp/System/Math/Overview/mathsample.cs index b8fdb53179e..f9f3a108d7b 100644 --- a/snippets/csharp/System/Math/Overview/mathsample.cs +++ b/snippets/csharp/System/Math/Overview/mathsample.cs @@ -6,77 +6,71 @@ namespace MathClassCS { - class MathTrapezoidSample - { - private double m_longBase; - private double m_shortBase; - private double m_leftLeg; - private double m_rightLeg; + class MathTrapezoidSample + { + private double m_longBase; + private double m_shortBase; + private double m_leftLeg; + private double m_rightLeg; - public MathTrapezoidSample(double longbase, double shortbase, double leftLeg, double rightLeg) - { - m_longBase = Math.Abs(longbase); - m_shortBase = Math.Abs(shortbase); - m_leftLeg = Math.Abs(leftLeg); - m_rightLeg = Math.Abs(rightLeg); - } + public MathTrapezoidSample(double longbase, double shortbase, double leftLeg, double rightLeg) + { + m_longBase = Math.Abs(longbase); + m_shortBase = Math.Abs(shortbase); + m_leftLeg = Math.Abs(leftLeg); + m_rightLeg = Math.Abs(rightLeg); + } - private double GetRightSmallBase() - { - return (Math.Pow(m_rightLeg,2.0) - Math.Pow(m_leftLeg,2.0) + Math.Pow(m_longBase,2.0) + Math.Pow(m_shortBase,2.0) - 2* m_shortBase * m_longBase)/ (2*(m_longBase - m_shortBase)); - } + private double GetRightSmallBase() => (Math.Pow(m_rightLeg, 2.0) - Math.Pow(m_leftLeg, 2.0) + Math.Pow(m_longBase, 2.0) + Math.Pow(m_shortBase, 2.0) - 2 * m_shortBase * m_longBase) / (2 * (m_longBase - m_shortBase)); - public double GetHeight() - { - double x = GetRightSmallBase(); - return Math.Sqrt(Math.Pow(m_rightLeg,2.0) - Math.Pow(x,2.0)); - } + public double GetHeight() + { + double x = GetRightSmallBase(); + return Math.Sqrt(Math.Pow(m_rightLeg, 2.0) - Math.Pow(x, 2.0)); + } - public double GetSquare() - { - return GetHeight() * m_longBase / 2.0; - } + public double GetSquare() => GetHeight() * m_longBase / 2.0; - public double GetLeftBaseRadianAngle() - { - double sinX = GetHeight()/m_leftLeg; - return Math.Round(Math.Asin(sinX),2); - } + public double GetLeftBaseRadianAngle() + { + double sinX = GetHeight() / m_leftLeg; + return Math.Round(Math.Asin(sinX), 2); + } - public double GetRightBaseRadianAngle() - { - double x = GetRightSmallBase(); - double cosX = (Math.Pow(m_rightLeg,2.0) + Math.Pow(x,2.0) - Math.Pow(GetHeight(),2.0))/(2*x*m_rightLeg); - return Math.Round(Math.Acos(cosX),2); - } + public double GetRightBaseRadianAngle() + { + double x = GetRightSmallBase(); + double cosX = (Math.Pow(m_rightLeg, 2.0) + Math.Pow(x, 2.0) - Math.Pow(GetHeight(), 2.0)) / (2 * x * m_rightLeg); + return Math.Round(Math.Acos(cosX), 2); + } - public double GetLeftBaseDegreeAngle() - { - double x = GetLeftBaseRadianAngle() * 180/ Math.PI; - return Math.Round(x,2); - } + public double GetLeftBaseDegreeAngle() + { + double x = GetLeftBaseRadianAngle() * 180 / Math.PI; + return Math.Round(x, 2); + } - public double GetRightBaseDegreeAngle() - { - double x = GetRightBaseRadianAngle() * 180/ Math.PI; - return Math.Round(x,2); - } + public double GetRightBaseDegreeAngle() + { + double x = GetRightBaseRadianAngle() * 180 / Math.PI; + return Math.Round(x, 2); + } - static void Main(string[] args) - { - MathTrapezoidSample trpz = new MathTrapezoidSample(20.0, 10.0, 8.0, 6.0); - Console.WriteLine("The trapezoid's bases are 20.0 and 10.0, the trapezoid's legs are 8.0 and 6.0"); - double h = trpz.GetHeight(); - Console.WriteLine("Trapezoid height is: " + h.ToString()); - double dxR = trpz.GetLeftBaseRadianAngle(); - Console.WriteLine("Trapezoid left base angle is: " + dxR.ToString() + " Radians"); - double dyR = trpz.GetRightBaseRadianAngle(); - Console.WriteLine("Trapezoid right base angle is: " + dyR.ToString() + " Radians"); - double dxD = trpz.GetLeftBaseDegreeAngle(); - Console.WriteLine("Trapezoid left base angle is: " + dxD.ToString() + " Degrees"); - double dyD = trpz.GetRightBaseDegreeAngle(); - Console.WriteLine("Trapezoid right base angle is: " + dyD.ToString() + " Degrees"); - } - } + static void Main(string[] args) + { + MathTrapezoidSample trpz = new(20.0, 10.0, 8.0, 6.0); + Console.WriteLine("The trapezoid's bases are 20.0 and 10.0, the trapezoid's legs are 8.0 and 6.0"); + double h = trpz.GetHeight(); + Console.WriteLine("Trapezoid height is: " + h.ToString()); + double dxR = trpz.GetLeftBaseRadianAngle(); + Console.WriteLine("Trapezoid left base angle is: " + dxR.ToString() + " Radians"); + double dyR = trpz.GetRightBaseRadianAngle(); + Console.WriteLine("Trapezoid right base angle is: " + dyR.ToString() + " Radians"); + double dxD = trpz.GetLeftBaseDegreeAngle(); + Console.WriteLine("Trapezoid left base angle is: " + dxD.ToString() + " Degrees"); + double dyD = trpz.GetRightBaseDegreeAngle(); + Console.WriteLine("Trapezoid right base angle is: " + dyD.ToString() + " Degrees"); + } + } } // diff --git a/snippets/csharp/System/Math/Pow/pow1.cs b/snippets/csharp/System/Math/Pow/pow1.cs index 06b94f68ca9..b6adceaac81 100644 --- a/snippets/csharp/System/Math/Pow/pow1.cs +++ b/snippets/csharp/System/Math/Pow/pow1.cs @@ -2,47 +2,47 @@ public class Example { - public static void Main() - { - // - int value = 2; - for (int power = 0; power <= 32; power++) - Console.WriteLine($"{value}^{power} = {(long)Math.Pow(value, power):N0} (0x{(long)Math.Pow(value, power):X})"); + public static void Main() + { + // + int value = 2; + for (int power = 0; power <= 32; power++) + Console.WriteLine($"{value}^{power} = {(long)Math.Pow(value, power):N0} (0x{(long)Math.Pow(value, power):X})"); - // The example displays the following output: - // 2^0 = 1 (0x1) - // 2^1 = 2 (0x2) - // 2^2 = 4 (0x4) - // 2^3 = 8 (0x8) - // 2^4 = 16 (0x10) - // 2^5 = 32 (0x20) - // 2^6 = 64 (0x40) - // 2^7 = 128 (0x80) - // 2^8 = 256 (0x100) - // 2^9 = 512 (0x200) - // 2^10 = 1,024 (0x400) - // 2^11 = 2,048 (0x800) - // 2^12 = 4,096 (0x1000) - // 2^13 = 8,192 (0x2000) - // 2^14 = 16,384 (0x4000) - // 2^15 = 32,768 (0x8000) - // 2^16 = 65,536 (0x10000) - // 2^17 = 131,072 (0x20000) - // 2^18 = 262,144 (0x40000) - // 2^19 = 524,288 (0x80000) - // 2^20 = 1,048,576 (0x100000) - // 2^21 = 2,097,152 (0x200000) - // 2^22 = 4,194,304 (0x400000) - // 2^23 = 8,388,608 (0x800000) - // 2^24 = 16,777,216 (0x1000000) - // 2^25 = 33,554,432 (0x2000000) - // 2^26 = 67,108,864 (0x4000000) - // 2^27 = 134,217,728 (0x8000000) - // 2^28 = 268,435,456 (0x10000000) - // 2^29 = 536,870,912 (0x20000000) - // 2^30 = 1,073,741,824 (0x40000000) - // 2^31 = 2,147,483,648 (0x80000000) - // 2^32 = 4,294,967,296 (0x100000000) - // - } + // The example displays the following output: + // 2^0 = 1 (0x1) + // 2^1 = 2 (0x2) + // 2^2 = 4 (0x4) + // 2^3 = 8 (0x8) + // 2^4 = 16 (0x10) + // 2^5 = 32 (0x20) + // 2^6 = 64 (0x40) + // 2^7 = 128 (0x80) + // 2^8 = 256 (0x100) + // 2^9 = 512 (0x200) + // 2^10 = 1,024 (0x400) + // 2^11 = 2,048 (0x800) + // 2^12 = 4,096 (0x1000) + // 2^13 = 8,192 (0x2000) + // 2^14 = 16,384 (0x4000) + // 2^15 = 32,768 (0x8000) + // 2^16 = 65,536 (0x10000) + // 2^17 = 131,072 (0x20000) + // 2^18 = 262,144 (0x40000) + // 2^19 = 524,288 (0x80000) + // 2^20 = 1,048,576 (0x100000) + // 2^21 = 2,097,152 (0x200000) + // 2^22 = 4,194,304 (0x400000) + // 2^23 = 8,388,608 (0x800000) + // 2^24 = 16,777,216 (0x1000000) + // 2^25 = 33,554,432 (0x2000000) + // 2^26 = 67,108,864 (0x4000000) + // 2^27 = 134,217,728 (0x8000000) + // 2^28 = 268,435,456 (0x10000000) + // 2^29 = 536,870,912 (0x20000000) + // 2^30 = 1,073,741,824 (0x40000000) + // 2^31 = 2,147,483,648 (0x80000000) + // 2^32 = 4,294,967,296 (0x100000000) + // + } } diff --git a/snippets/csharp/System/Math/Round/Program.cs b/snippets/csharp/System/Math/Round/Program.cs new file mode 100644 index 00000000000..bb05111e8d3 --- /dev/null +++ b/snippets/csharp/System/Math/Round/Program.cs @@ -0,0 +1,7 @@ +MathRoundExample1.Run(); +MathRoundExample2.Run(); +MathRoundExample3.Run(); +MathRoundExample4.Run(); +MathRoundExample5.Run(); +MathRoundExample6.Run(); +Sample.Run(); diff --git a/snippets/csharp/System/Math/Round/Project.csproj b/snippets/csharp/System/Math/Round/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/Math/Round/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/Math/Round/round2.cs b/snippets/csharp/System/Math/Round/round2.cs index 85f36ef2f3b..b456d432f7b 100644 --- a/snippets/csharp/System/Math/Round/round2.cs +++ b/snippets/csharp/System/Math/Round/round2.cs @@ -1,25 +1,25 @@ // using System; -public class Example +public class MathRoundExample1 { - public static void Main() - { - double value = 11.1; - for (int ctr = 0; ctr <= 5; ctr++) - value = RoundValueAndAdd(value); + public static void Run() + { + double value = 11.1; + for (int ctr = 0; ctr <= 5; ctr++) + value = RoundValueAndAdd(value); - Console.WriteLine(); + Console.WriteLine(); - value = 11.5; - RoundValueAndAdd(value); - } + value = 11.5; + RoundValueAndAdd(value); + } - private static double RoundValueAndAdd(double value) - { - Console.WriteLine("{0} --> {1}", value, Math.Round(value)); - return value + .1; - } + private static double RoundValueAndAdd(double value) + { + Console.WriteLine($"{value} --> {Math.Round(value)}"); + return value + .1; + } } // The example displays the following output: // 11.1 --> 11 diff --git a/snippets/csharp/System/Math/Round/round3.cs b/snippets/csharp/System/Math/Round/round3.cs index 448e7829e61..50545a0fbbe 100644 --- a/snippets/csharp/System/Math/Round/round3.cs +++ b/snippets/csharp/System/Math/Round/round3.cs @@ -1,14 +1,14 @@ // using System; -public class Example +public class MathRoundExample2 { - public static void Main() - { - double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }; - foreach (double value in values) - Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2)); - } + public static void Run() + { + double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }; + foreach (double value in values) + Console.WriteLine($"{value} --> {Math.Round(value, 2)}"); + } } // The example displays the following output: // 2.125 --> 2.12 diff --git a/snippets/csharp/System/Math/Round/round4.cs b/snippets/csharp/System/Math/Round/round4.cs index 4644d380347..7c4443f8b86 100644 --- a/snippets/csharp/System/Math/Round/round4.cs +++ b/snippets/csharp/System/Math/Round/round4.cs @@ -1,22 +1,21 @@ using System; -public class Example +public class MathRoundExample3 { - public static void Main() - { - // - double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }; - foreach (double value in values) - Console.WriteLine("{0} --> {1}", value, - Math.Round(value, 2, MidpointRounding.AwayFromZero)); + public static void Run() + { + // + double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }; + foreach (double value in values) + Console.WriteLine($"{value} --> {Math.Round(value, 2, MidpointRounding.AwayFromZero)}"); - // The example displays the following output: - // 2.125 --> 2.13 - // 2.135 --> 2.13 - // 2.145 --> 2.15 - // 3.125 --> 3.13 - // 3.135 --> 3.14 - // 3.145 --> 3.15 - // - } + // The example displays the following output: + // 2.125 --> 2.13 + // 2.135 --> 2.13 + // 2.145 --> 2.15 + // 3.125 --> 3.13 + // 3.135 --> 3.14 + // 3.145 --> 3.15 + // + } } diff --git a/snippets/csharp/System/Math/Round/round5.cs b/snippets/csharp/System/Math/Round/round5.cs index c75ab9b2c20..bbccada8586 100644 --- a/snippets/csharp/System/Math/Round/round5.cs +++ b/snippets/csharp/System/Math/Round/round5.cs @@ -1,26 +1,26 @@ // using System; -public class Example +public class MathRoundExample4 { - public static void Main() - { - double value = 11.1; - for (int ctr = 0; ctr <= 5; ctr++) - value = RoundValueAndAdd(value); + public static void Run() + { + double value = 11.1; + for (int ctr = 0; ctr <= 5; ctr++) + value = RoundValueAndAdd(value); - Console.WriteLine(); + Console.WriteLine(); - value = 11.5; - RoundValueAndAdd(value); - } + value = 11.5; + RoundValueAndAdd(value); + } - private static double RoundValueAndAdd(double value) - { - Console.WriteLine("{0} --> {1}", value, Math.Round(value, - MidpointRounding.AwayFromZero)); - return value + .1; - } + private static double RoundValueAndAdd(double value) + { + Console.WriteLine($"{value} --> {Math.Round(value, + MidpointRounding.AwayFromZero)}"); + return value + .1; + } } // The example displays the following output: // 11.1 --> 11 diff --git a/snippets/csharp/System/Math/Round/rounddecimal1.cs b/snippets/csharp/System/Math/Round/rounddecimal1.cs index bc9ad15c373..7f4059f166a 100644 --- a/snippets/csharp/System/Math/Round/rounddecimal1.cs +++ b/snippets/csharp/System/Math/Round/rounddecimal1.cs @@ -1,20 +1,20 @@ using System; -class Example +class MathRoundExample5 { - static void Main() - { - // - for (decimal value = 4.2m; value <= 4.8m; value+=.1m ) - Console.WriteLine("{0} --> {1}", value, Math.Round(value)); - // The example displays the following output: - // 4.2 --> 4 - // 4.3 --> 4 - // 4.4 --> 4 - // 4.5 --> 4 - // 4.6 --> 5 - // 4.7 --> 5 - // 4.8 --> 5 - // - } + public static void Run() + { + // + for (decimal value = 4.2m; value <= 4.8m; value += .1m) + Console.WriteLine($"{value} --> {Math.Round(value)}"); + // The example displays the following output: + // 4.2 --> 4 + // 4.3 --> 4 + // 4.4 --> 4 + // 4.5 --> 4 + // 4.6 --> 5 + // 4.7 --> 5 + // 4.8 --> 5 + // + } } diff --git a/snippets/csharp/System/Math/Round/source.cs b/snippets/csharp/System/Math/Round/source.cs index 5b7e92dc26c..b4ce79acb8a 100644 --- a/snippets/csharp/System/Math/Round/source.cs +++ b/snippets/csharp/System/Math/Round/source.cs @@ -1,15 +1,15 @@ using System; -class Program +class MathRoundExample6 { - static void Main() + public static void Run() { -// - Console.WriteLine("Classic Math.Round in CSharp"); - Console.WriteLine(Math.Round(4.4)); // 4 - Console.WriteLine(Math.Round(4.5)); // 4 - Console.WriteLine(Math.Round(4.6)); // 5 - Console.WriteLine(Math.Round(5.5)); // 6 -// + // + Console.WriteLine("Classic Math.Round in CSharp"); + Console.WriteLine(Math.Round(4.4)); // 4 + Console.WriteLine(Math.Round(4.5)); // 4 + Console.WriteLine(Math.Round(4.6)); // 5 + Console.WriteLine(Math.Round(5.5)); // 6 + // } } diff --git a/snippets/csharp/System/Math/Round/source1.cs b/snippets/csharp/System/Math/Round/source1.cs index 24dc3206c31..01ae6d4c79c 100644 --- a/snippets/csharp/System/Math/Round/source1.cs +++ b/snippets/csharp/System/Math/Round/source1.cs @@ -1,15 +1,17 @@ using System; -public class Sample { - static void Main() { - // - Math.Round(3.44, 1); //Returns 3.4. - Math.Round(3.45, 1); //Returns 3.4. - Math.Round(3.46, 1); //Returns 3.5. +public class Sample +{ + public static void Run() + { + // + Math.Round(3.44, 1); //Returns 3.4. + Math.Round(3.45, 1); //Returns 3.4. + Math.Round(3.46, 1); //Returns 3.5. - Math.Round(4.34, 1); // Returns 4.3 - Math.Round(4.35, 1); // Returns 4.4 - Math.Round(4.36, 1); // Returns 4.4 - // - } + Math.Round(4.34, 1); // Returns 4.3 + Math.Round(4.35, 1); // Returns 4.4 + Math.Round(4.36, 1); // Returns 4.4 + // + } }; diff --git a/snippets/csharp/System/Math/Sign/sign.cs b/snippets/csharp/System/Math/Sign/sign.cs index 6445b40198f..9238a4d9e53 100644 --- a/snippets/csharp/System/Math/Sign/sign.cs +++ b/snippets/csharp/System/Math/Sign/sign.cs @@ -8,17 +8,17 @@ public static void Main() { string str = "{0}: {1,3} is {2} zero."; string nl = Environment.NewLine; - byte xByte1 = 0; - short xShort1 = -2; - int xInt1 = -3; - long xLong1 = -4; - float xSingle1 = 0.0f; - double xDouble1 = 6.0; - Decimal xDecimal1 = -7m; - nint xIntPtr1 = 8; + byte xByte1 = 0; + short xShort1 = -2; + int xInt1 = -3; + long xLong1 = -4; + float xSingle1 = 0.0f; + double xDouble1 = 6.0; + decimal xDecimal1 = -7m; + nint xIntPtr1 = 8; // The following type is not CLS-compliant. - sbyte xSbyte1 = -101; + sbyte xSbyte1 = -101; Console.WriteLine($"{nl}Test the sign of the following types of values:"); Console.WriteLine(str, "Byte ", xByte1, Test(Math.Sign(xByte1))); diff --git a/snippets/csharp/System/Math/Sqrt/sqrt1.cs b/snippets/csharp/System/Math/Sqrt/sqrt1.cs index 9f0ee019044..ac12b1d9aea 100644 --- a/snippets/csharp/System/Math/Sqrt/sqrt1.cs +++ b/snippets/csharp/System/Math/Sqrt/sqrt1.cs @@ -2,34 +2,32 @@ public class Example { - public static void Main() - { - // - // Create an array containing the area of some squares. - Tuple[] areas = - { Tuple.Create("Sitka, Alaska", 2870.3), + public static void Main() + { + // + // Create an array containing the area of some squares. + Tuple[] areas = + { Tuple.Create("Sitka, Alaska", 2870.3), Tuple.Create("New York City", 302.6), Tuple.Create("Los Angeles", 468.7), Tuple.Create("Detroit", 138.8), Tuple.Create("Chicago", 227.1), Tuple.Create("San Diego", 325.2) }; - Console.WriteLine("{0,-18} {1,14:N1} {2,30}\n", "City", "Area (mi.)", - "Equivalent to a square with:"); + Console.WriteLine($"{"City",-18} {"Area (mi.)",14:N1} {"Equivalent to a square with:",30}\n"); - foreach (var area in areas) - Console.WriteLine("{0,-18} {1,14:N1} {2,14:N2} miles per side", - area.Item1, area.Item2, Math.Round(Math.Sqrt(area.Item2), 2)); + foreach (var area in areas) + Console.WriteLine($"{area.Item1,-18} {area.Item2,14:N1} {Math.Round(Math.Sqrt(area.Item2), 2),14:N2} miles per side"); - // The example displays the following output: - // City Area (mi.) Equivalent to a square with: - // - // Sitka, Alaska 2,870.3 53.58 miles per side - // New York City 302.6 17.40 miles per side - // Los Angeles 468.7 21.65 miles per side - // Detroit 138.8 11.78 miles per side - // Chicago 227.1 15.07 miles per side - // San Diego 325.2 18.03 miles per side - // - } + // The example displays the following output: + // City Area (mi.) Equivalent to a square with: + // + // Sitka, Alaska 2,870.3 53.58 miles per side + // New York City 302.6 17.40 miles per side + // Los Angeles 468.7 21.65 miles per side + // Detroit 138.8 11.78 miles per side + // Chicago 227.1 15.07 miles per side + // San Diego 325.2 18.03 miles per side + // + } } diff --git a/snippets/csharp/System/Math/Tanh/tanh.cs b/snippets/csharp/System/Math/Tanh/tanh.cs index 2287df55413..650de427e13 100644 --- a/snippets/csharp/System/Math/Tanh/tanh.cs +++ b/snippets/csharp/System/Math/Tanh/tanh.cs @@ -8,13 +8,13 @@ public static void Main() { Console.WriteLine( "This example of hyperbolic Math.Tanh( double )\n" + - "generates the following output." ); + "generates the following output."); Console.WriteLine( "\nEvaluate these hyperbolic identities " + - "with selected values for X:" ); - Console.WriteLine( " tanh(X) == sinh(X) / cosh(X)" ); + "with selected values for X:"); + Console.WriteLine(" tanh(X) == sinh(X) / cosh(X)"); Console.WriteLine( - " tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X))" ); + " tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X))"); UseTanh(0.1); UseTanh(1.2); @@ -23,7 +23,7 @@ public static void Main() Console.WriteLine( "\nEvaluate [tanh(X + Y) == (tanh(X) + tanh(Y)) " + "/ (1 + tanh(X) * tanh(Y))]" + - "\nwith selected values for X and Y:" ); + "\nwith selected values for X and Y:"); UseTwoArgs(0.1, 1.2); UseTwoArgs(1.2, 4.9); @@ -38,18 +38,14 @@ static void UseTanh(double arg) Console.WriteLine( "\n Math.Tanh({0}) == {1:E16}\n" + " Math.Sinh({0}) / Math.Cosh({0}) == {2:E16}", - arg, tanhArg, (Math.Sinh(arg) / Math.Cosh(arg)) ); + arg, tanhArg, (Math.Sinh(arg) / Math.Cosh(arg))); // Evaluate tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X)). Console.WriteLine( " 2 * Math.Tanh({0}) /", - arg, 2.0 * tanhArg ); - Console.WriteLine( - " (1 + (Math.Tanh({0}))^2) == {1:E16}", - arg, 2.0 * tanhArg / (1.0 + tanhArg * tanhArg ) ); - Console.WriteLine( - " Math.Tanh({0}) == {1:E16}", - 2.0 * arg, Math.Tanh(2.0 * arg) ); + arg, 2.0 * tanhArg); + Console.WriteLine($" (1 + (Math.Tanh({arg}))^2) == {2.0 * tanhArg / (1.0 + tanhArg * tanhArg):E16}"); + Console.WriteLine($" Math.Tanh({2.0 * arg}) == {Math.Tanh(2.0 * arg):E16}"); } // Evaluate a hyperbolic identity that is a function of two arguments. @@ -60,10 +56,8 @@ static void UseTwoArgs(double argX, double argY) "\n (Math.Tanh({0}) + Math.Tanh({1})) /\n" + "(1 + Math.Tanh({0}) * Math.Tanh({1})) == {2:E16}", argX, argY, (Math.Tanh(argX) + Math.Tanh(argY)) / - (1.0 + Math.Tanh(argX) * Math.Tanh(argY)) ); - Console.WriteLine( - " Math.Tanh({0}) == {1:E16}", - argX + argY, Math.Tanh(argX + argY)); + (1.0 + Math.Tanh(argX) * Math.Tanh(argY))); + Console.WriteLine($" Math.Tanh({argX + argY}) == {Math.Tanh(argX + argY):E16}"); } } diff --git a/snippets/csharp/System/Math/Truncate/Truncate1.cs b/snippets/csharp/System/Math/Truncate/Truncate1.cs index ccd81138362..53645bcee23 100644 --- a/snippets/csharp/System/Math/Truncate/Truncate1.cs +++ b/snippets/csharp/System/Math/Truncate/Truncate1.cs @@ -2,30 +2,30 @@ public class Class1 { - public static void Main() - { - // - double floatNumber; + public static void Main() + { + // + double floatNumber; - floatNumber = 32.7865; - // Displays 32 - Console.WriteLine(Math.Truncate(floatNumber)); + floatNumber = 32.7865; + // Displays 32 + Console.WriteLine(Math.Truncate(floatNumber)); - floatNumber = -32.9012; - // Displays -32 - Console.WriteLine(Math.Truncate(floatNumber)); - // + floatNumber = -32.9012; + // Displays -32 + Console.WriteLine(Math.Truncate(floatNumber)); + // - // - decimal decimalNumber; + // + decimal decimalNumber; - decimalNumber = 32.7865m; - // Displays 32 - Console.WriteLine(Math.Truncate(decimalNumber)); + decimalNumber = 32.7865m; + // Displays 32 + Console.WriteLine(Math.Truncate(decimalNumber)); - decimalNumber = -32.9012m; - // Displays -32 - Console.WriteLine(Math.Truncate(decimalNumber)); - // - } + decimalNumber = -32.9012m; + // Displays -32 + Console.WriteLine(Math.Truncate(decimalNumber)); + // + } } diff --git a/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs b/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs index 13c515ba601..ee088e3f376 100644 --- a/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs +++ b/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs @@ -22,7 +22,7 @@ public static void Main() catch (MissingMethodException e) { // Show the user that the DoSomething method cannot be called. - Console.WriteLine("Unable to call the DoSomething method: {0}", e.Message); + Console.WriteLine($"Unable to call the DoSomething method: {e.Message}"); } // @@ -33,12 +33,12 @@ public static void Main() // However, because the App class does not define this field, // a MissingFieldException is thrown. typeof(App).InvokeMember("AField", BindingFlags.Static | BindingFlags.SetField, - null, null, new Object[] { 5 }); + null, null, new object[] { 5 }); } catch (MissingFieldException e) { - // Show the user that the AField field cannot be accessed. - Console.WriteLine("Unable to access the AField field: {0}", e.Message); + // Show the user that the AField field cannot be accessed. + Console.WriteLine($"Unable to access the AField field: {e.Message}"); } // @@ -53,10 +53,10 @@ public static void Main() } catch (MissingMemberException e) { - // Notice that this code is catching MissingMemberException which is the - // base class of MissingMethodException and MissingFieldException. - // Show the user that the AnotherField field cannot be accessed. - Console.WriteLine("Unable to access the AnotherField field: {0}", e.Message); + // Notice that this code is catching MissingMemberException which is the + // base class of MissingMethodException and MissingFieldException. + // Show the user that the AnotherField field cannot be accessed. + Console.WriteLine($"Unable to access the AnotherField field: {e.Message}"); } // } @@ -66,4 +66,4 @@ public static void Main() // Unable to call the DoSomething method: Method 'App.DoSomething' not found. // Unable to access the AField field: Field 'App.AField' not found. // Unable to access the AnotherField field: Field 'App.AnotherField' not found. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs b/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs index 0ca29355b27..1fa902ccf3a 100644 --- a/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs +++ b/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs @@ -4,103 +4,100 @@ class StringContainer { - // Define a delegate to handle string display. - public delegate void CheckAndDisplayDelegate(string str); - - // A generic list object that holds the strings. - private List container = new List(); - - // A method that adds strings to the collection. - public void AddString(string str) - { - container.Add(str); - } - - // Iterate through the strings and invoke the method(s) that the delegate points to. - public void DisplayAllQualified(CheckAndDisplayDelegate displayDelegate) - { - foreach (var str in container) { - displayDelegate(str); - } - } - } + // Define a delegate to handle string display. + public delegate void CheckAndDisplayDelegate(string str); + + // A generic list object that holds the strings. + private List container = new(); + + // A method that adds strings to the collection. + public void AddString(string str) => container.Add(str); + + // Iterate through the strings and invoke the method(s) that the delegate points to. + public void DisplayAllQualified(CheckAndDisplayDelegate displayDelegate) + { + foreach (string str in container) + { + displayDelegate(str); + } + } +} // This class defines some methods to display strings. class StringExtensions { - // Display a string if it starts with a consonant. - public static void ConStart(string str) - { - if (!(str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u')) - Console.WriteLine(str); - } - - // Display a string if it starts with a vowel. - public static void VowelStart(string str) - { - if ((str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u')) - Console.WriteLine(str); - } + // Display a string if it starts with a consonant. + public static void ConStart(string str) + { + if (!(str[0] == 'a' || str[0] == 'e' || str[0] == 'i' || str[0] == 'o' || str[0] == 'u')) + Console.WriteLine(str); + } + + // Display a string if it starts with a vowel. + public static void VowelStart(string str) + { + if ((str[0] == 'a' || str[0] == 'e' || str[0] == 'i' || str[0] == 'o' || str[0] == 'u')) + Console.WriteLine(str); + } } // Demonstrate the use of delegates, including the Remove and // Combine methods to create and modify delegate combinations. class Test { - static public void Main() - { - // Declare the StringContainer class and add some strings - StringContainer container = new StringContainer(); - container.AddString("This"); - container.AddString("is"); - container.AddString("a"); - container.AddString("multicast"); - container.AddString("delegate"); - container.AddString("example"); - - // Create two delegates individually using different methods. - StringContainer.CheckAndDisplayDelegate conStart = StringExtensions.ConStart; - StringContainer.CheckAndDisplayDelegate vowelStart = StringExtensions.VowelStart; - - // Get the list of all delegates assigned to this MulticastDelegate instance. - Delegate[] delegateList = conStart.GetInvocationList(); - Console.WriteLine("conStart contains {0} delegate(s).", delegateList.Length); - delegateList = vowelStart.GetInvocationList(); - Console.WriteLine("vowelStart contains {0} delegate(s).\n", delegateList.Length); - - // Determine whether the delegates are System.Multicast delegates. - if (conStart is System.MulticastDelegate && vowelStart is System.MulticastDelegate) - Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n"); - - // Execute the two delegates. - Console.WriteLine("Executing the conStart delegate:"); - container.DisplayAllQualified(conStart); - Console.WriteLine(); - Console.WriteLine("Executing the vowelStart delegate:"); - container.DisplayAllQualified(vowelStart); - Console.WriteLine(); - - // Create a new MulticastDelegate and call Combine to add two delegates. - StringContainer.CheckAndDisplayDelegate multipleDelegates = - (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(conStart, vowelStart); - - // How many delegates does multipleDelegates contain? - delegateList = multipleDelegates.GetInvocationList(); - Console.WriteLine("\nmultipleDelegates contains {0} delegates.\n", - delegateList.Length); - - // Pass this multicast delegate to DisplayAllQualified. - Console.WriteLine("Executing the multipleDelegate delegate."); - container.DisplayAllQualified(multipleDelegates); - - // Call remove and combine to change the contained delegates. - multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Remove(multipleDelegates, vowelStart); - multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(multipleDelegates, conStart); - - // Pass multipleDelegates to DisplayAllQualified again. - Console.WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:"); - container.DisplayAllQualified(multipleDelegates); - } + static public void Main() + { + // Declare the StringContainer class and add some strings + StringContainer container = new(); + container.AddString("This"); + container.AddString("is"); + container.AddString("a"); + container.AddString("multicast"); + container.AddString("delegate"); + container.AddString("example"); + + // Create two delegates individually using different methods. + StringContainer.CheckAndDisplayDelegate conStart = StringExtensions.ConStart; + StringContainer.CheckAndDisplayDelegate vowelStart = StringExtensions.VowelStart; + + // Get the list of all delegates assigned to this MulticastDelegate instance. + Delegate[] delegateList = conStart.GetInvocationList(); + Console.WriteLine($"conStart contains {delegateList.Length} delegate(s)."); + delegateList = vowelStart.GetInvocationList(); + Console.WriteLine($"vowelStart contains {delegateList.Length} delegate(s).\n"); + + // Determine whether the delegates are System.Multicast delegates. + if (conStart is System.MulticastDelegate && vowelStart is System.MulticastDelegate) + Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n"); + + // Execute the two delegates. + Console.WriteLine("Executing the conStart delegate:"); + container.DisplayAllQualified(conStart); + Console.WriteLine(); + Console.WriteLine("Executing the vowelStart delegate:"); + container.DisplayAllQualified(vowelStart); + Console.WriteLine(); + + // Create a new MulticastDelegate and call Combine to add two delegates. + StringContainer.CheckAndDisplayDelegate multipleDelegates = + (StringContainer.CheckAndDisplayDelegate)Delegate.Combine(conStart, vowelStart); + + // How many delegates does multipleDelegates contain? + delegateList = multipleDelegates.GetInvocationList(); + Console.WriteLine($"\nmultipleDelegates contains {delegateList.Length} delegates.\n"); + + // Pass this multicast delegate to DisplayAllQualified. + Console.WriteLine("Executing the multipleDelegate delegate."); + container.DisplayAllQualified(multipleDelegates); + + // Call remove and combine to change the contained delegates. + multipleDelegates = (StringContainer.CheckAndDisplayDelegate)Delegate.Remove(multipleDelegates, vowelStart); + multipleDelegates = (StringContainer.CheckAndDisplayDelegate)Delegate.Combine(multipleDelegates, conStart); + + // Pass multipleDelegates to DisplayAllQualified again. + Console.WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:"); + container.DisplayAllQualified(multipleDelegates); + } } // The example displays the following output: // conStart contains 1 delegate(s). diff --git a/snippets/csharp/System/NotImplementedException/Overview/program.cs b/snippets/csharp/System/NotImplementedException/Overview/program.cs index 301fca07fae..941b6c8435b 100644 --- a/snippets/csharp/System/NotImplementedException/Overview/program.cs +++ b/snippets/csharp/System/NotImplementedException/Overview/program.cs @@ -2,23 +2,23 @@ class Program { -// -static void Main(string[] args) -{ - try + // + static void Main(string[] args) { - FutureFeature(); + try + { + FutureFeature(); + } + catch (NotImplementedException notImp) + { + Console.WriteLine(notImp.Message); + } } - catch (NotImplementedException notImp) + + static void FutureFeature() { - Console.WriteLine(notImp.Message); + // Not developed yet. + throw new NotImplementedException(); } -} - -static void FutureFeature() -{ - // Not developed yet. - throw new NotImplementedException(); -} -// + // } diff --git a/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs b/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs index 323cea83410..de52310127b 100644 --- a/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs +++ b/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs @@ -9,10 +9,10 @@ public class Example public static async Task Main() { Encoding enc = Encoding.Unicode; - String value = "This is a string to persist."; - Byte[] bytes = enc.GetBytes(value); + string value = "This is a string to persist."; + byte[] bytes = enc.GetBytes(value); - FileStream fs = new FileStream(@".\TestFile.dat", + FileStream fs = new(@".\TestFile.dat", FileMode.Open, FileAccess.Read); Task t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length); diff --git a/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs b/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs index 7eaf7c84e92..abc9ae52b90 100644 --- a/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs +++ b/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs @@ -7,12 +7,11 @@ public class TestPropEx1 { public static async Task Main() { - String name = @".\TestFile.dat"; + string name = @".\TestFile.dat"; var fs = new FileStream(name, FileMode.Create, FileAccess.Write); - Console.WriteLine("Filename: {0}, Encoding: {1}", - name, await FileUtilities1.GetEncodingType(fs)); + Console.WriteLine($"Filename: {name}, Encoding: {await FileUtilities1.GetEncodingType(fs)}"); } } @@ -23,7 +22,7 @@ public enum EncodingType public async static Task GetEncodingType(FileStream fs) { - Byte[] bytes = new Byte[4]; + byte[] bytes = new byte[4]; int bytesRead = await fs.ReadAsync(bytes, 0, 4); if (bytesRead < 2) return EncodingType.None; @@ -33,12 +32,12 @@ public async static Task GetEncodingType(FileStream fs) if (bytesRead == 4) { - var value = BitConverter.ToUInt32(bytes, 0); + uint value = BitConverter.ToUInt32(bytes, 0); if (value == 0x0000FEFF | value == 0xFEFF0000) return EncodingType.Utf32; } - var value16 = BitConverter.ToUInt16(bytes, 0); + ushort value16 = BitConverter.ToUInt16(bytes, 0); if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) return EncodingType.Utf16; diff --git a/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs b/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs index 795a01183ae..a10c1987c38 100644 --- a/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs +++ b/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs @@ -6,12 +6,11 @@ public class TestPropEx2 { public static async Task Main() { - String name = @".\TestFile.dat"; + string name = @".\TestFile.dat"; var fs = new FileStream(name, FileMode.Create, FileAccess.Write); - Console.WriteLine("Filename: {0}, Encoding: {1}", - name, await FileUtilities.GetEncodingType(fs)); + Console.WriteLine($"Filename: {name}, Encoding: {await FileUtilities.GetEncodingType(fs)}"); } } @@ -26,7 +25,7 @@ public static async Task GetEncodingType(FileStream fs) if (!fs.CanRead) return EncodingType.Unknown; - Byte[] bytes = new Byte[4]; + byte[] bytes = new byte[4]; int bytesRead = await fs.ReadAsync(bytes, 0, 4); if (bytesRead < 2) return EncodingType.None; @@ -36,12 +35,12 @@ public static async Task GetEncodingType(FileStream fs) if (bytesRead == 4) { - var value = BitConverter.ToUInt32(bytes, 0); + uint value = BitConverter.ToUInt32(bytes, 0); if (value == 0x0000FEFF | value == 0xFEFF0000) return EncodingType.Utf32; } - var value16 = BitConverter.ToUInt16(bytes, 0); + ushort value16 = BitConverter.ToUInt16(bytes, 0); if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) return EncodingType.Utf16; diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs index 599029a2be9..bf12d6305a3 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs @@ -5,10 +5,9 @@ public class Array1Example public static void Main() { // - string[] values = [ "one", null, "two" ]; + string[] values = ["one", null, "two"]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) - Console.Write("{0}{1}", values[ctr].Trim(), - ctr == values.GetUpperBound(0) ? "" : ", "); + Console.Write($"{values[ctr].Trim()}{(ctr == values.GetUpperBound(0) ? "" : ", ")}"); Console.WriteLine(); // The example displays the following output: diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs index 756e52f450b..4cdb6435cb9 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs @@ -5,11 +5,9 @@ public class Array2Example public static void Main() { // - string[] values = [ "one", null, "two" ]; + string[] values = ["one", null, "two"]; for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++) - Console.Write("{0}{1}", - values[ctr] != null ? values[ctr].Trim() : "", - ctr == values.GetUpperBound(0) ? "" : ", "); + Console.Write($"{(values[ctr] != null ? values[ctr].Trim() : "")}{(ctr == values.GetUpperBound(0) ? "" : ", ")}"); Console.WriteLine(); // The example displays the following output: diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs index 31f69e53c3e..2756d22fbf4 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs @@ -23,7 +23,7 @@ public class Pages public Page CurrentPage { - get { return _page[_ctr]; } + get => _page[_ctr]; set { // Move all the page objects down to accommodate the new one. diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs index 2034ef1efb6..8987d0d9a28 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs @@ -30,7 +30,7 @@ public class Pages public Page CurrentPage { - get { return _page[_ctr]; } + get => _page[_ctr]; set { // Move all the page objects down to accommodate the new one. diff --git a/snippets/csharp/System/NullReferenceException/Overview/example2.cs b/snippets/csharp/System/NullReferenceException/Overview/example2.cs index 41dfb78ede0..71ab56fe89a 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example2.cs @@ -17,10 +17,7 @@ private static void PopulateNames(List names) names.Add(arrName); } - private static List GetData() - { - return null; - } + private static List GetData() => null; } // The example displays output like the following: diff --git a/snippets/csharp/System/NullReferenceException/Overview/example3.cs b/snippets/csharp/System/NullReferenceException/Overview/example3.cs index 2ce0700f112..412cfa96068 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/example3.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/example3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Collections; @@ -12,15 +12,12 @@ public static void Main() _ = GetList(listType); } - private static Type GetListType() - { - return typeof(List); - } + private static Type GetListType() => typeof(List); private static IList GetList(Type type) { var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor - var value = 1; + int value = 1; emptyList.Add(value); return emptyList; } diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs index 2c6dd285739..2036797ecce 100644 --- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs +++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs @@ -44,15 +44,12 @@ public static Person[] AddRange(params string[] firstNames) { Person[] p = new Person[firstNames.Length]; for (int ctr = 0; ctr < firstNames.Length; ctr++) - p[ctr] = new Person(firstNames[ctr]); + p[ctr] = new(firstNames[ctr]); return p; } - public Person(string firstName) - { - FirstName = firstName; - } + public Person(string firstName) => FirstName = firstName; public string FirstName; } diff --git a/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs b/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs index dc86f85c3bd..8e163b67ee9 100644 --- a/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs +++ b/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs @@ -7,33 +7,30 @@ class Sample { -// Declare a type named Example. -// The MyMethod member of Example returns a Nullable of Int32. + // Declare a type named Example. + // The MyMethod member of Example returns a Nullable of Int32. public class Example { - public int? MyMethod() - { - return 0; - } + public int? MyMethod() => 0; } -/* - Use reflection to obtain a Type object for the Example type. - Use the Type object to obtain a MethodInfo object for the MyMethod method. - Use the MethodInfo object to obtain the type of the return value of - MyMethod, which is Nullable of Int32. - Use the GetUnderlyingType method to obtain the type argument of the - return value type, which is Int32. -*/ + /* + Use reflection to obtain a Type object for the Example type. + Use the Type object to obtain a MethodInfo object for the MyMethod method. + Use the MethodInfo object to obtain the type of the return value of + MyMethod, which is Nullable of Int32. + Use the GetUnderlyingType method to obtain the type argument of the + return value type, which is Int32. + */ public static void Main() { Type t = typeof(Example); MethodInfo mi = t.GetMethod("MyMethod"); Type retval = mi.ReturnType; - Console.WriteLine("Return value type ... {0}", retval); + Console.WriteLine($"Return value type ... {retval}"); Type answer = Nullable.GetUnderlyingType(retval); - Console.WriteLine("Underlying type ..... {0}", answer); + Console.WriteLine($"Underlying type ..... {answer}"); } } /* @@ -43,4 +40,4 @@ Return value type ... System.Nullable`1[System.Int32] Underlying type ..... System.Int32 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/Equals/eq.cs b/snippets/csharp/System/NullableT/Equals/eq.cs index ebd405f2f38..a86abbad545 100644 --- a/snippets/csharp/System/NullableT/Equals/eq.cs +++ b/snippets/csharp/System/NullableT/Equals/eq.cs @@ -8,30 +8,30 @@ class Sample { public static void Main() { - int? nullInt1 = 100; - int? nullInt2 = 200; - object myObj; - -// Determine if two nullable of System.Int32 values are equal. -// The nullable objects have different values. - Console.Write("1) nullInt1 and nullInt2 "); - if (nullInt1.Equals(nullInt2)) - Console.Write("are"); - else - Console.Write("are not"); - Console.WriteLine(" equal."); - -// Determine if a nullable of System.Int32 and an object -// are equal. The object contains the boxed value of the -// nullable object. - - myObj = (object)nullInt1; - Console.Write("2) nullInt1 and myObj "); - if (nullInt1.Equals(myObj)) - Console.Write("are"); - else - Console.Write("are not"); - Console.WriteLine(" equal."); + int? nullInt1 = 100; + int? nullInt2 = 200; + object myObj; + + // Determine if two nullable of System.Int32 values are equal. + // The nullable objects have different values. + Console.Write("1) nullInt1 and nullInt2 "); + if (nullInt1.Equals(nullInt2)) + Console.Write("are"); + else + Console.Write("are not"); + Console.WriteLine(" equal."); + + // Determine if a nullable of System.Int32 and an object + // are equal. The object contains the boxed value of the + // nullable object. + + myObj = (object)nullInt1; + Console.Write("2) nullInt1 and myObj "); + if (nullInt1.Equals(myObj)) + Console.Write("are"); + else + Console.Write("are not"); + Console.WriteLine(" equal."); } } @@ -42,4 +42,4 @@ public static void Main() 2) nullInt1 and myObj are equal. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs b/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs index 3169bdada67..2fd73c2cee6 100644 --- a/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs +++ b/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs @@ -8,67 +8,63 @@ class Sample { public static void Main() { - float? mySingle = 12.34f; - float? yourSingle = -1.0f; + float? mySingle = 12.34f; + float? yourSingle = -1.0f; - Console.WriteLine("*** Display a value or the default value ***\n"); -// Display the values of mySingle and yourSingle. + Console.WriteLine("*** Display a value or the default value ***\n"); + // Display the values of mySingle and yourSingle. - Display("A1", mySingle, yourSingle); + Display("A1", mySingle, yourSingle); -// Assign the value of mySingle to yourSingle, then display the values -// of mySingle and yourSingle. The yourSingle variable is assigned the -// value 12.34 because mySingle has a value. + // Assign the value of mySingle to yourSingle, then display the values + // of mySingle and yourSingle. The yourSingle variable is assigned the + // value 12.34 because mySingle has a value. - yourSingle = mySingle.GetValueOrDefault(); - Display("A2", mySingle, yourSingle); + yourSingle = mySingle.GetValueOrDefault(); + Display("A2", mySingle, yourSingle); -// Assign null (Nothing in Visual Basic) to mySingle, which means no value is -// defined for mySingle. Then assign the value of mySingle to yourSingle and -// display the values of both variables. The default value of all binary zeroes -// is assigned to yourSingle because mySingle has no value. + // Assign null (Nothing in Visual Basic) to mySingle, which means no value is + // defined for mySingle. Then assign the value of mySingle to yourSingle and + // display the values of both variables. The default value of all binary zeroes + // is assigned to yourSingle because mySingle has no value. - mySingle = null; - yourSingle = mySingle.GetValueOrDefault(); - Display("A3", mySingle, yourSingle); + mySingle = null; + yourSingle = mySingle.GetValueOrDefault(); + Display("A3", mySingle, yourSingle); -// Reassign the original values of mySingle and yourSingle. - mySingle = 12.34f; - yourSingle = -1.0f; + // Reassign the original values of mySingle and yourSingle. + mySingle = 12.34f; + yourSingle = -1.0f; - Console.Write("\n*** Display a value or the "); - Console.WriteLine("specified default value ***\n"); + Console.Write("\n*** Display a value or the "); + Console.WriteLine("specified default value ***\n"); -// Display the values of mySingle and yourSingle. - Display("B1", mySingle, yourSingle); + // Display the values of mySingle and yourSingle. + Display("B1", mySingle, yourSingle); -// Assign the value of mySingle to yourSingle, then display the values -// of mySingle and yourSingle. The yourSingle variable is assigned the -// value 12.34 because mySingle has a value. + // Assign the value of mySingle to yourSingle, then display the values + // of mySingle and yourSingle. The yourSingle variable is assigned the + // value 12.34 because mySingle has a value. - yourSingle = mySingle.GetValueOrDefault(-222.22f); - Display("B2", mySingle, yourSingle); + yourSingle = mySingle.GetValueOrDefault(-222.22f); + Display("B2", mySingle, yourSingle); -// Assign null (Nothing in Visual Basic) to mySingle, which means no value is -// defined for mySingle. Then assign the value of mySingle to yourSingle and -// display the values of both variables. The specified default value of -333.33 -// is assigned to yourSingle because mySingle has no value. + // Assign null (Nothing in Visual Basic) to mySingle, which means no value is + // defined for mySingle. Then assign the value of mySingle to yourSingle and + // display the values of both variables. The specified default value of -333.33 + // is assigned to yourSingle because mySingle has no value. - mySingle = null; - yourSingle = mySingle.GetValueOrDefault(-333.33f); - Display("B3", mySingle, yourSingle); + mySingle = null; + yourSingle = mySingle.GetValueOrDefault(-333.33f); + Display("B3", mySingle, yourSingle); } -// Display the values of two nullable of System.Single structures. -// The Console.WriteLine method automatically calls the ToString methods of -// each input argument to display its values. If no value is defined for a -// nullable type, the ToString method for that argument returns the empty -// string (""). - public static void Display(string title, float? dspMySingle, float? dspYourSingle) - { - Console.WriteLine("{0}) mySingle = [{1}], yourSingle = [{2}]", - title, dspMySingle, dspYourSingle); - } + // Display the values of two nullable of System.Single structures. + // The Console.WriteLine method automatically calls the ToString methods of + // each input argument to display its values. If no value is defined for a + // nullable type, the ToString method for that argument returns the empty + // string (""). + public static void Display(string title, float? dspMySingle, float? dspYourSingle) => Console.WriteLine($"{title}) mySingle = [{dspMySingle}], yourSingle = [{dspYourSingle}]"); } /* @@ -85,4 +81,4 @@ public static void Display(string title, float? dspMySingle, float? dspYourSingl B3) mySingle = [], yourSingle = [-333.33] */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs b/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs index a0d19fb3abe..07d18f393b6 100644 --- a/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs +++ b/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs @@ -3,27 +3,30 @@ public class Example { - public static void Main() - { - Nullable n1 = new Nullable(10); - Nullable n2 = null; - Nullable n3 = new Nullable(20); - n3 = null; - Nullable[] items = { n1, n2, n3 }; + public static void Main() + { + Nullable n1 = new Nullable(10); + Nullable n2 = null; + Nullable n3 = new Nullable(20); + n3 = null; + Nullable[] items = { n1, n2, n3 }; - foreach (var item in items) { - Console.WriteLine("Has a value: {0}", item.HasValue); - if (item.HasValue) { - Console.WriteLine("Type: {0}", item.GetType().Name); - Console.WriteLine("Value: {0}", item.Value); - } - else { - Console.WriteLine("Null: {0}", item == null); - Console.WriteLine("Default Value: {0}", item.GetValueOrDefault()); - } - Console.WriteLine(); - } - } + foreach (var item in items) + { + Console.WriteLine($"Has a value: {item.HasValue}"); + if (item.HasValue) + { + Console.WriteLine($"Type: {item.GetType().Name}"); + Console.WriteLine($"Value: {item.Value}"); + } + else + { + Console.WriteLine($"Null: {item == null}"); + Console.WriteLine($"Default Value: {item.GetValueOrDefault()}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // Has a value: True @@ -37,4 +40,4 @@ public static void Main() // Has a value: False // Null: True // Default Value: 0 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/Overview/tarow.cs b/snippets/csharp/System/NullableT/Overview/tarow.cs index 04d3a3085b5..541343a4e55 100644 --- a/snippets/csharp/System/NullableT/Overview/tarow.cs +++ b/snippets/csharp/System/NullableT/Overview/tarow.cs @@ -6,55 +6,56 @@ class Sample // Define the "titleAuthor" table of the Microsoft "pubs" database. public struct titleAuthor { - // Author ID; format ###-##-#### - public string au_id; - // Title ID; format AA#### - public string title_id; - // Author ORD is nullable. - public short? au_ord; - // Royalty Percent is nullable. - public int? royaltyper; + // Author ID; format ###-##-#### + public string au_id; + // Title ID; format AA#### + public string title_id; + // Author ORD is nullable. + public short? au_ord; + // Royalty Percent is nullable. + public int? royaltyper; } public static void Main() { - // Declare and initialize the titleAuthor array. - titleAuthor[] ta = new titleAuthor[3]; - ta[0].au_id = "712-32-1176"; - ta[0].title_id = "PS3333"; - ta[0].au_ord = 1; - ta[0].royaltyper = 100; + // Declare and initialize the titleAuthor array. + titleAuthor[] ta = new titleAuthor[3]; + ta[0].au_id = "712-32-1176"; + ta[0].title_id = "PS3333"; + ta[0].au_ord = 1; + ta[0].royaltyper = 100; - ta[1].au_id = "213-46-8915"; - ta[1].title_id = "BU1032"; - ta[1].au_ord = null; - ta[1].royaltyper = null; + ta[1].au_id = "213-46-8915"; + ta[1].title_id = "BU1032"; + ta[1].au_ord = null; + ta[1].royaltyper = null; - ta[2].au_id = "672-71-3249"; - ta[2].title_id = "TC7777"; - ta[2].au_ord = null; - ta[2].royaltyper = 40; + ta[2].au_id = "672-71-3249"; + ta[2].title_id = "TC7777"; + ta[2].au_ord = null; + ta[2].royaltyper = 40; - // Display the values of the titleAuthor array elements, and - // display a legend. - Display("Title Authors Table", ta); - Console.WriteLine("Legend:"); - Console.WriteLine("An Author ORD of -1 means no value is defined."); - Console.WriteLine("A Royalty % of 0 means no value is defined."); + // Display the values of the titleAuthor array elements, and + // display a legend. + Display("Title Authors Table", ta); + Console.WriteLine("Legend:"); + Console.WriteLine("An Author ORD of -1 means no value is defined."); + Console.WriteLine("A Royalty % of 0 means no value is defined."); } // Display the values of the titleAuthor array elements. public static void Display(string dspTitle, titleAuthor[] dspAllTitleAuthors) { - Console.WriteLine("*** {0} ***", dspTitle); - foreach (titleAuthor dspTA in dspAllTitleAuthors) { - Console.WriteLine("Author ID ... {0}", dspTA.au_id); - Console.WriteLine("Title ID .... {0}", dspTA.title_id); - Console.WriteLine("Author ORD .. {0}", dspTA.au_ord ?? -1); - Console.WriteLine("Royalty % ... {0}", dspTA.royaltyper ?? 0); - Console.WriteLine(); - } + Console.WriteLine($"*** {dspTitle} ***"); + foreach (titleAuthor dspTA in dspAllTitleAuthors) + { + Console.WriteLine($"Author ID ... {dspTA.au_id}"); + Console.WriteLine($"Title ID .... {dspTA.title_id}"); + Console.WriteLine($"Author ORD .. {dspTA.au_ord ?? -1}"); + Console.WriteLine($"Royalty % ... {dspTA.royaltyper ?? 0}"); + Console.WriteLine(); + } } } // The example displays the following output: @@ -77,4 +78,4 @@ public static void Display(string dspTitle, // Legend: // An Author ORD of -1 means no value is defined. // A Royalty % of 0 means no value is defined. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/ToString/ts.cs b/snippets/csharp/System/NullableT/ToString/ts.cs index 3636eb9ddce..5736259dbc3 100644 --- a/snippets/csharp/System/NullableT/ToString/ts.cs +++ b/snippets/csharp/System/NullableT/ToString/ts.cs @@ -8,28 +8,28 @@ class Sample { public static void Main() { - DateTime? nullableDate; + DateTime? nullableDate; -// Display the current date and time. - nullableDate = DateTime.Now; - Display("1)", nullableDate); + // Display the current date and time. + nullableDate = DateTime.Now; + Display("1)", nullableDate); -// Assign null (Nothing in Visual Basic) to nullableDate, then -// display its value. - nullableDate = null; - Display("2)", nullableDate); + // Assign null (Nothing in Visual Basic) to nullableDate, then + // display its value. + nullableDate = null; + Display("2)", nullableDate); } -// Display the text representation of a nullable DateTime. + // Display the text representation of a nullable DateTime. public static void Display(string title, DateTime? dspDT) { - string msg = dspDT.ToString(); + string msg = dspDT.ToString(); - Console.Write("{0} ", title); - if (String.IsNullOrEmpty(msg)) - Console.WriteLine("The nullable DateTime has no defined value."); - else - Console.WriteLine("The current date and time is {0}.", msg); + Console.Write($"{title} "); + if (string.IsNullOrEmpty(msg)) + Console.WriteLine("The nullable DateTime has no defined value."); + else + Console.WriteLine($"The current date and time is {msg}."); } } @@ -40,4 +40,4 @@ public static void Display(string title, DateTime? dspDT) 2) The nullable DateTime has no defined value. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs b/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs index c8b71550f9b..e98b1ec2a02 100644 --- a/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs +++ b/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs @@ -3,16 +3,16 @@ public class Example { - public static void Main() - { - var nullInt = new Nullable(172); - // Convert with CInt conversion method. - Console.WriteLine((int)nullInt); - // Convert with Convert.ChangeType. - Console.WriteLine(Convert.ChangeType(nullInt, typeof(int))); - } + public static void Main() + { + var nullInt = new Nullable(172); + // Convert with CInt conversion method. + Console.WriteLine((int)nullInt); + // Convert with Convert.ChangeType. + Console.WriteLine(Convert.ChangeType(nullInt, typeof(int))); + } } // The example displays the following output: // 172 // 172 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Object/Equals/equals2.cs b/snippets/csharp/System/Object/Equals/equals2.cs index e64ae9a67b8..e1f943ae930 100644 --- a/snippets/csharp/System/Object/Equals/equals2.cs +++ b/snippets/csharp/System/Object/Equals/equals2.cs @@ -1,4 +1,4 @@ -// +// using System; class Point2 @@ -14,7 +14,7 @@ public Point2(int x, int y) this.y = y; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { //Check for null and compare run-time types. if ((obj == null) || !this.GetType().Equals(obj.GetType())) @@ -28,27 +28,18 @@ public override bool Equals(Object obj) } } - public override int GetHashCode() - { - return HashCode.Combine(x, y); - } + public override int GetHashCode() => HashCode.Combine(x, y); - public override string ToString() - { - return String.Format("Point2({0}, {1})", x, y); - } + public override string ToString() => $"Point2({x}, {y})"; } sealed class Point3D : Point2 { int z; - public Point3D(int x, int y, int z) : base(x, y) - { - this.z = z; - } + public Point3D(int x, int y, int z) : base(x, y) => this.z = z; - public override bool Equals(Object obj) + public override bool Equals(object obj) { Point3D pt3 = obj as Point3D; if (pt3 == null) @@ -57,25 +48,19 @@ public override bool Equals(Object obj) return base.Equals((Point2)obj) && z == pt3.z; } - public override int GetHashCode() - { - return HashCode.Combine(base.GetHashCode(), z); - } + public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), z); - public override String ToString() - { - return String.Format("Point2({0}, {1}, {2})", x, y, z); - } + public override string ToString() => $"Point2({x}, {y}, {z})"; } class Example7 { public static void Main() { - Point2 point2D = new Point2(5, 5); - Point3D point3Da = new Point3D(5, 5, 2); - Point3D point3Db = new Point3D(5, 5, 2); - Point3D point3Dc = new Point3D(5, 5, -1); + Point2 point2D = new(5, 5); + Point3D point3Da = new(5, 5, 2); + Point3D point3Db = new(5, 5, 2); + Point3D point3Dc = new(5, 5, -1); Console.WriteLine($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}"); Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}"); diff --git a/snippets/csharp/System/Object/Equals/equals3.cs b/snippets/csharp/System/Object/Equals/equals3.cs index b03eeb114ab..bcf7e2bf2d3 100644 --- a/snippets/csharp/System/Object/Equals/equals3.cs +++ b/snippets/csharp/System/Object/Equals/equals3.cs @@ -1,74 +1,64 @@ -// +// using System; class Rectangle { - private Point a, b; + private Point a, b; - public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY) - { - this.a = new Point(upLeftX, upLeftY); - this.b = new Point(downRightX, downRightY); - } - - public override bool Equals(Object obj) - { - // Perform an equality check on two rectangles (Point object pairs). - if (obj == null || GetType() != obj.GetType()) - return false; - Rectangle r = (Rectangle)obj; - return a.Equals(r.a) && b.Equals(r.b); - } - - public override int GetHashCode() - { - return Tuple.Create(a, b).GetHashCode(); - } + public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY) + { + this.a = new(upLeftX, upLeftY); + this.b = new(downRightX, downRightY); + } - public override String ToString() + public override bool Equals(object obj) { - return String.Format("Rectangle({0}, {1}, {2}, {3})", - a.x, a.y, b.x, b.y); + // Perform an equality check on two rectangles (Point object pairs). + if (obj == null || GetType() != obj.GetType()) + return false; + Rectangle r = (Rectangle)obj; + return a.Equals(r.a) && b.Equals(r.b); } + + public override int GetHashCode() => Tuple.Create(a, b).GetHashCode(); + + public override string ToString() => $"Rectangle({a.x}, {a.y}, {b.x}, {b.y})"; } class Point { - internal int x; - internal int y; + internal int x; + internal int y; - public Point(int X, int Y) - { - this.x = X; - this.y = Y; - } + public Point(int X, int Y) + { + this.x = X; + this.y = Y; + } - public override bool Equals (Object obj) - { - // Performs an equality check on two points (integer pairs). - if (obj == null || GetType() != obj.GetType()) return false; - Point p = (Point)obj; - return (x == p.x) && (y == p.y); - } + public override bool Equals(object obj) + { + // Performs an equality check on two points (integer pairs). + if (obj == null || GetType() != obj.GetType()) return false; + Point p = (Point)obj; + return (x == p.x) && (y == p.y); + } - public override int GetHashCode() - { - return Tuple.Create(x, y).GetHashCode(); - } + public override int GetHashCode() => Tuple.Create(x, y).GetHashCode(); } class Example { - public static void Main() - { - Rectangle r1 = new Rectangle(0, 0, 100, 200); - Rectangle r2 = new Rectangle(0, 0, 100, 200); - Rectangle r3 = new Rectangle(0, 0, 150, 200); + public static void Main() + { + Rectangle r1 = new(0, 0, 100, 200); + Rectangle r2 = new(0, 0, 100, 200); + Rectangle r3 = new(0, 0, 150, 200); - Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}"); - Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}"); - Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}"); - } + Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}"); + Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}"); + Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}"); + } } // The example displays the following output: // Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True diff --git a/snippets/csharp/System/Object/Equals/equals4.cs b/snippets/csharp/System/Object/Equals/equals4.cs index fae811a3bca..69018b798e1 100644 --- a/snippets/csharp/System/Object/Equals/equals4.cs +++ b/snippets/csharp/System/Object/Equals/equals4.cs @@ -1,56 +1,41 @@ -// +// using System; public struct Complex { - public double re, im; + public double re, im; - public override bool Equals(Object obj) - { - return obj is Complex && this == (Complex)obj; - } + public override bool Equals(object obj) => obj is Complex && this == (Complex)obj; - public override int GetHashCode() - { - return Tuple.Create(re, im).GetHashCode(); - } + public override int GetHashCode() => Tuple.Create(re, im).GetHashCode(); - public static bool operator ==(Complex x, Complex y) - { - return x.re == y.re && x.im == y.im; - } + public static bool operator ==(Complex x, Complex y) => x.re == y.re && x.im == y.im; - public static bool operator !=(Complex x, Complex y) - { - return !(x == y); - } + public static bool operator !=(Complex x, Complex y) => !(x == y); - public override String ToString() - { - return String.Format("({0}, {1})", re, im); - } + public override string ToString() => $"({re}, {im})"; } class MyClass { - public static void Main() - { - Complex cmplx1, cmplx2; + public static void Main() + { + Complex cmplx1, cmplx2; - cmplx1.re = 4.0; - cmplx1.im = 1.0; + cmplx1.re = 4.0; + cmplx1.im = 1.0; - cmplx2.re = 2.0; - cmplx2.im = 1.0; + cmplx2.re = 2.0; + cmplx2.im = 1.0; - Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}"); - Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); + Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}"); + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); - cmplx2.re = 4.0; + cmplx2.re = 4.0; - Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}"); - Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); - } + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}"); + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); + } } // The example displays the following output: // (4, 1) <> (2, 1): True diff --git a/snippets/csharp/System/Object/Equals/equals_ref.cs b/snippets/csharp/System/Object/Equals/equals_ref.cs index 8db6b1dc08a..2f9efcc9277 100644 --- a/snippets/csharp/System/Object/Equals/equals_ref.cs +++ b/snippets/csharp/System/Object/Equals/equals_ref.cs @@ -1,38 +1,32 @@ -// +// using System; // Define a reference type that does not override Equals. public class Person { - private string personName; + private string personName; - public Person(string name) - { - this.personName = name; - } + public Person(string name) => this.personName = name; - public override string ToString() - { - return this.personName; - } + public override string ToString() => this.personName; } public class Example1 { - public static void Main() - { - Person person1a = new Person("John"); - Person person1b = person1a; - Person person2 = new Person(person1a.ToString()); + public static void Main() + { + Person person1a = new("John"); + Person person1b = person1a; + Person person2 = new(person1a.ToString()); - Console.WriteLine("Calling Equals:"); - Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}"); - Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}"); + Console.WriteLine("Calling Equals:"); + Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}"); + Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}"); - Console.WriteLine("\nCasting to an Object and calling Equals:"); - Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}"); - Console.WriteLine($"person1a and person2: {((object) person1a).Equals((object) person2)}"); - } + Console.WriteLine("\nCasting to an Object and calling Equals:"); + Console.WriteLine($"person1a and person1b: {((object)person1a).Equals((object)person1b)}"); + Console.WriteLine($"person1a and person2: {((object)person1a).Equals((object)person2)}"); + } } // The example displays the following output: // person1a and person1b: True diff --git a/snippets/csharp/System/Object/Equals/equals_static2.cs b/snippets/csharp/System/Object/Equals/equals_static2.cs index d355f135482..8fdc2b1bb92 100644 --- a/snippets/csharp/System/Object/Equals/equals_static2.cs +++ b/snippets/csharp/System/Object/Equals/equals_static2.cs @@ -3,60 +3,53 @@ public class RefExample { - public static void Main() - { - Dog m1 = new Dog("Alaskan Malamute"); - Dog m2 = new Dog("Alaskan Malamute"); - Dog g1 = new Dog("Great Pyrenees"); - Dog g2 = g1; - Dog d1 = new Dog("Dalmation"); - Dog n1 = null; - Dog n2 = null; + public static void Main() + { + Dog m1 = new("Alaskan Malamute"); + Dog m2 = new("Alaskan Malamute"); + Dog g1 = new("Great Pyrenees"); + Dog g2 = g1; + Dog d1 = new("Dalmatian"); + Dog n1 = null; + Dog n2 = null; - Console.WriteLine("null = null: {0}", Object.Equals(n1, n2)); - Console.WriteLine("null Reference Equals null: {0}\n", Object.ReferenceEquals(n1, n2)); + Console.WriteLine($"null = null: {object.Equals(n1, n2)}"); + Console.WriteLine($"null Reference Equals null: {object.ReferenceEquals(n1, n2)}\n"); - Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2)); - Console.WriteLine("{0} Reference Equals {1}: {2}\n", g1, g2, Object.ReferenceEquals(g1, g2)); + Console.WriteLine($"{g1} = {g2}: {object.Equals(g1, g2)}"); + Console.WriteLine($"{g1} Reference Equals {g2}: {object.ReferenceEquals(g1, g2)}\n"); - Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2)); - Console.WriteLine("{0} Reference Equals {1}: {2}\n", m1, m2, Object.ReferenceEquals(m1, m2)); + Console.WriteLine($"{m1} = {m2}: {object.Equals(m1, m2)}"); + Console.WriteLine($"{m1} Reference Equals {m2}: {object.ReferenceEquals(m1, m2)}\n"); - Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1)); - Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1)); - } + Console.WriteLine($"{m1} = {d1}: {object.Equals(m1, d1)}"); + Console.WriteLine($"{m1} Reference Equals {d1}: {object.ReferenceEquals(m1, d1)}"); + } } public class Dog { - // Public field. - public string Breed; + // Public field. + public string Breed; - // Class constructor. - public Dog(string dogBreed) - { - this.Breed = dogBreed; - } + // Class constructor. + public Dog(string dogBreed) => this.Breed = dogBreed; - public override bool Equals(Object obj) - { - if (obj == null || !(obj is Dog)) - return false; - else - return this.Breed == ((Dog) obj).Breed; - } + public override bool Equals(object obj) + { + if (obj == null || !(obj is Dog)) + return false; + else + return this.Breed == ((Dog)obj).Breed; + } - public override int GetHashCode() - { - return this.Breed.GetHashCode(); - } + public override int GetHashCode() => this.Breed.GetHashCode(); - public override string ToString() - { - return this.Breed; - } + public override string ToString() => this.Breed; } + // The example displays the following output: + // null = null: True // null Reference Equals null: True // @@ -66,6 +59,7 @@ public override string ToString() // Alaskan Malamute = Alaskan Malamute: True // Alaskan Malamute Reference Equals Alaskan Malamute: False // -// Alaskan Malamute = Dalmation: False -// Alaskan Malamute Reference Equals Dalmation: False +// Alaskan Malamute = Dalmatian: False +// Alaskan Malamute Reference Equals Dalmatian: False + // diff --git a/snippets/csharp/System/Object/Equals/equals_val1.cs b/snippets/csharp/System/Object/Equals/equals_val1.cs index 533e01bf098..d8bb277ceb0 100644 --- a/snippets/csharp/System/Object/Equals/equals_val1.cs +++ b/snippets/csharp/System/Object/Equals/equals_val1.cs @@ -1,20 +1,20 @@ -using System; +using System; public class Example2 { - public static void Main() - { - // - byte value1 = 12; - int value2 = 12; + public static void Main() + { + // + byte value1 = 12; + int value2 = 12; - object object1 = value1; - object object2 = value2; + object object1 = value1; + object object2 = value2; - Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}"); + Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}"); - // The example displays the following output: - // 12 (Byte) = 12 (Int32): False - // - } + // The example displays the following output: + // 12 (Byte) = 12 (Int32): False + // + } } diff --git a/snippets/csharp/System/Object/Equals/equals_val2.cs b/snippets/csharp/System/Object/Equals/equals_val2.cs index 2c128e53757..fa6ab1ce4cd 100644 --- a/snippets/csharp/System/Object/Equals/equals_val2.cs +++ b/snippets/csharp/System/Object/Equals/equals_val2.cs @@ -4,32 +4,26 @@ // Define a value type that does not override Equals. public struct Person3 { - private string personName; + private string personName; - public Person3(string name) - { - this.personName = name; - } + public Person3(string name) => this.personName = name; - public override string ToString() - { - return this.personName; - } + public override string ToString() => this.personName; } public struct Example3 { - public static void Main() - { - Person3 person1 = new Person3("John"); - Person3 person2 = new Person3("John"); + public static void Main() + { + Person3 person1 = new("John"); + Person3 person2 = new("John"); - Console.WriteLine("Calling Equals:"); - Console.WriteLine(person1.Equals(person2)); + Console.WriteLine("Calling Equals:"); + Console.WriteLine(person1.Equals(person2)); - Console.WriteLine("\nCasting to an Object and calling Equals:"); - Console.WriteLine(((object) person1).Equals((object) person2)); - } + Console.WriteLine("\nCasting to an Object and calling Equals:"); + Console.WriteLine(((object)person1).Equals((object)person2)); + } } // The example displays the following output: // Calling Equals: diff --git a/snippets/csharp/System/Object/Equals/equalsoverride.cs b/snippets/csharp/System/Object/Equals/equalsoverride.cs index b8da28c242f..7330a16c3e3 100644 --- a/snippets/csharp/System/Object/Equals/equalsoverride.cs +++ b/snippets/csharp/System/Object/Equals/equalsoverride.cs @@ -3,39 +3,36 @@ // public class Person6 { - private string idNumber; - private string personName; + private string idNumber; + private string personName; - public Person6(string name, string id) - { - this.personName = name; - this.idNumber = id; - } + public Person6(string name, string id) + { + this.personName = name; + this.idNumber = id; + } - public override bool Equals(Object obj) - { - Person6 personObj = obj as Person6; - if (personObj == null) - return false; - else - return idNumber.Equals(personObj.idNumber); - } + public override bool Equals(object obj) + { + Person6 personObj = obj as Person6; + if (personObj == null) + return false; + else + return idNumber.Equals(personObj.idNumber); + } - public override int GetHashCode() - { - return this.idNumber.GetHashCode(); - } + public override int GetHashCode() => this.idNumber.GetHashCode(); } public class Example6 { - public static void Main() - { - Person6 p1 = new Person6("John", "63412895"); - Person6 p2 = new Person6("Jack", "63412895"); - Console.WriteLine(p1.Equals(p2)); - Console.WriteLine(Object.Equals(p1, p2)); - } + public static void Main() + { + Person6 p1 = new("John", "63412895"); + Person6 p2 = new("Jack", "63412895"); + Console.WriteLine(p1.Equals(p2)); + Console.WriteLine(object.Equals(p1, p2)); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/Object/Equals/equalssb1.cs b/snippets/csharp/System/Object/Equals/equalssb1.cs index b51fd0e2a2a..368ba138c41 100644 --- a/snippets/csharp/System/Object/Equals/equalssb1.cs +++ b/snippets/csharp/System/Object/Equals/equalssb1.cs @@ -1,21 +1,21 @@ -// +// using System; using System.Text; public class Example5 { - public static void Main() - { - StringBuilder sb1 = new StringBuilder("building a string..."); - StringBuilder sb2 = new StringBuilder("building a string..."); + public static void Main() + { + StringBuilder sb1 = new("building a string..."); + StringBuilder sb2 = new("building a string..."); - Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}"); - Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}"); - Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"); + Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}"); + Console.WriteLine($"((Object) sb1).Equals(sb2): {((object)sb1).Equals(sb2)}"); + Console.WriteLine($"Object.Equals(sb1, sb2): {object.Equals(sb1, sb2)}"); - Object sb3 = new StringBuilder("building a string..."); - Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}"); - } + object sb3 = new StringBuilder("building a string..."); + Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}"); + } } // The example displays the following output: // sb1.Equals(sb2): True diff --git a/snippets/csharp/System/Object/Finalize/finalize1.cs b/snippets/csharp/System/Object/Finalize/finalize1.cs index 2179ebbccb4..7f8bffb1641 100644 --- a/snippets/csharp/System/Object/Finalize/finalize1.cs +++ b/snippets/csharp/System/Object/Finalize/finalize1.cs @@ -4,36 +4,31 @@ public class ExampleClass { - Stopwatch sw; + Stopwatch sw; - public ExampleClass() - { - sw = Stopwatch.StartNew(); - Console.WriteLine("Instantiated object"); - } + public ExampleClass() + { + sw = Stopwatch.StartNew(); + Console.WriteLine("Instantiated object"); + } - public void ShowDuration() - { - Console.WriteLine("This instance of {0} has been in existence for {1}", - this, sw.Elapsed); - } + public void ShowDuration() => Console.WriteLine($"This instance of {this} has been in existence for {sw.Elapsed}"); - ~ExampleClass() - { - Console.WriteLine("Finalizing object"); - sw.Stop(); - Console.WriteLine("This instance of {0} has been in existence for {1}", - this, sw.Elapsed); - } + ~ExampleClass() + { + Console.WriteLine("Finalizing object"); + sw.Stop(); + Console.WriteLine($"This instance of {this} has been in existence for {sw.Elapsed}"); + } } public class Demo { - public static void Main() - { - ExampleClass ex = new ExampleClass(); - ex.ShowDuration(); - } + public static void Main() + { + ExampleClass ex = new(); + ex.ShowDuration(); + } } // The example displays output like the following: // Instantiated object diff --git a/snippets/csharp/System/Object/Finalize/finalize_safe.cs b/snippets/csharp/System/Object/Finalize/finalize_safe.cs index 3206babdc10..e21fdb54061 100644 --- a/snippets/csharp/System/Object/Finalize/finalize_safe.cs +++ b/snippets/csharp/System/Object/Finalize/finalize_safe.cs @@ -51,7 +51,7 @@ public FileAssociationInfo(string fileExtension) if (retVal != ERROR_SUCCESS) throw new Win32Exception(retVal); // Instantiate the first SafeRegistryHandle. - hExtHandle = new SafeRegistryHandle(hExtension, true); + hExtHandle = new(hExtension, true); string appId = new(' ', MAX_PATH); uint appIdLength = (uint)appId.Length; @@ -83,7 +83,7 @@ public FileAssociationInfo(string fileExtension) throw new Win32Exception(retVal); // Instantiate the second SafeRegistryHandle. - hAppIdHandle = new SafeRegistryHandle(hAppId, true); + hAppIdHandle = new(hAppId, true); // Get the executable name for this file type. string exePath = new(' ', MAX_PATH); @@ -117,14 +117,14 @@ public FileAssociationInfo(string fileExtension) public string Open { - get { return openCmd; } + get => openCmd; set { if (hAppIdHandle.IsInvalid | hAppIdHandle.IsClosed) throw new InvalidOperationException("Cannot write to registry key."); if (!File.Exists(value)) { - string message = string.Format("'{0}' does not exist", value); + string message = $"'{value}' does not exist"; throw new FileNotFoundException(message); } string cmd = value + " %1"; diff --git a/snippets/csharp/System/Object/GetHashCode/direct1.cs b/snippets/csharp/System/Object/GetHashCode/direct1.cs index 666b1dff966..81d36c5d115 100644 --- a/snippets/csharp/System/Object/GetHashCode/direct1.cs +++ b/snippets/csharp/System/Object/GetHashCode/direct1.cs @@ -3,48 +3,37 @@ public struct Number { - private int n; + private int n; - public Number(int value) - { - n = value; - } + public Number(int value) => n = value; - public int Value - { - get { return n; } - } + public int Value => n; - public override bool Equals(Object obj) - { - if (obj == null || ! (obj is Number)) - return false; - else - return n == ((Number) obj).n; - } + public override bool Equals(object obj) + { + if (obj == null || !(obj is Number)) + return false; + else + return n == ((Number)obj).n; + } - public override int GetHashCode() - { - return n; - } + public override int GetHashCode() => n; - public override string ToString() - { - return n.ToString(); - } + public override string ToString() => n.ToString(); } public class Example1 { - public static void Main() - { - Random rnd = new Random(); - for (int ctr = 0; ctr <= 9; ctr++) { - int randomN = rnd.Next(Int32.MinValue, Int32.MaxValue); - Number n = new Number(randomN); - Console.WriteLine("n = {0,12}, hash code = {1,12}", n, n.GetHashCode()); - } - } + public static void Main() + { + Random rnd = new(); + for (int ctr = 0; ctr <= 9; ctr++) + { + int randomN = rnd.Next(int.MinValue, int.MaxValue); + Number n = new(randomN); + Console.WriteLine($"n = {n,12}, hash code = {n.GetHashCode(),12}"); + } + } } // The example displays output like the following: // n = -634398368, hash code = -634398368 diff --git a/snippets/csharp/System/Object/GetHashCode/shift1.cs b/snippets/csharp/System/Object/GetHashCode/shift1.cs index c9f7c4431f9..26ab57852b9 100644 --- a/snippets/csharp/System/Object/GetHashCode/shift1.cs +++ b/snippets/csharp/System/Object/GetHashCode/shift1.cs @@ -8,22 +8,19 @@ public struct Point public Point(int x, int y) { - this.x = x; - this.y = y; + this.x = x; + this.y = y; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Point)) return false; + if (!(obj is Point)) return false; - Point p = (Point) obj; - return x == p.x & y == p.y; + Point p = (Point)obj; + return x == p.x & y == p.y; } - public override int GetHashCode() - { - return ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode(); - } + public override int GetHashCode() => ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode(); private int ShiftAndWrap(int value, int positions) { @@ -40,14 +37,14 @@ private int ShiftAndWrap(int value, int positions) public class Example2 { - public static void Main() - { - Point pt = new Point(5, 8); + public static void Main() + { + Point pt = new(5, 8); Console.WriteLine(pt.GetHashCode()); - pt = new Point(8, 5); + pt = new(8, 5); Console.WriteLine(pt.GetHashCode()); - } + } } // The example displays the following output: // 28 @@ -56,7 +53,7 @@ public static void Main() public class Utility { - // + // public int ShiftAndWrap(int value, int positions) { positions = positions & 0x1F; @@ -68,5 +65,5 @@ public int ShiftAndWrap(int value, int positions) // Shift and wrap the discarded bits. return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0); } - // + // } diff --git a/snippets/csharp/System/Object/GetHashCode/xor1.cs b/snippets/csharp/System/Object/GetHashCode/xor1.cs index a37b2efa1b4..d37ec11bd41 100644 --- a/snippets/csharp/System/Object/GetHashCode/xor1.cs +++ b/snippets/csharp/System/Object/GetHashCode/xor1.cs @@ -9,34 +9,31 @@ public struct Point2 public Point2(int x, int y) { - this.x = x; - this.y = y; + this.x = x; + this.y = y; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (! (obj is Point2)) return false; + if (!(obj is Point2)) return false; - Point2 p = (Point2) obj; - return x == p.x & y == p.y; + Point2 p = (Point2)obj; + return x == p.x & y == p.y; } - public override int GetHashCode() - { - return x ^ y; - } + public override int GetHashCode() => x ^ y; } public class Example3 { - public static void Main() - { - Point2 pt = new Point2(5, 8); - Console.WriteLine(pt.GetHashCode()); + public static void Main() + { + Point2 pt = new(5, 8); + Console.WriteLine(pt.GetHashCode()); - pt = new Point2(8, 5); - Console.WriteLine(pt.GetHashCode()); - } + pt = new(8, 5); + Console.WriteLine(pt.GetHashCode()); + } } // The example displays the following output: // 13 diff --git a/snippets/csharp/System/Object/GetHashCode/xor2.cs b/snippets/csharp/System/Object/GetHashCode/xor2.cs index d8ad45dd2f9..bac63c34bf7 100644 --- a/snippets/csharp/System/Object/GetHashCode/xor2.cs +++ b/snippets/csharp/System/Object/GetHashCode/xor2.cs @@ -8,39 +8,36 @@ public struct Point3 public Point3(int x, int y) { - this.x = x; - this.y = y; + this.x = x; + this.y = y; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is Point3) { - Point3 p = (Point3) obj; + Point3 p = (Point3)obj; return x == p.x & y == p.y; } else { return false; - } + } } - public override int GetHashCode() - { - return HashCode.Combine(x, y); - } + public override int GetHashCode() => HashCode.Combine(x, y); } public class Example { - public static void Main() - { - Point3 pt = new Point3(5, 8); + public static void Main() + { + Point3 pt = new(5, 8); Console.WriteLine(pt.GetHashCode()); - pt = new Point3(8, 5); + pt = new(8, 5); Console.WriteLine(pt.GetHashCode()); - } + } } // The example displays output similar to the following. // Note: HashCode.Combine results are not stable across .NET versions. diff --git a/snippets/csharp/System/Object/GetType/GetTypeEx2.cs b/snippets/csharp/System/Object/GetType/GetTypeEx2.cs index 1c3edbca961..7c6d5a6b520 100644 --- a/snippets/csharp/System/Object/GetType/GetTypeEx2.cs +++ b/snippets/csharp/System/Object/GetType/GetTypeEx2.cs @@ -1,36 +1,36 @@ using System; -public class Example +public class ObjectGetTypeExample2 { - public static void Main() - { - // - object[] values = { (int) 12, (long) 10653, (byte) 12, (sbyte) -5, + public static void Run() + { + // + object[] values = { (int) 12, (long) 10653, (byte) 12, (sbyte) -5, 16.3, "string" }; - foreach (var value in values) { - Type t = value.GetType(); - if (t.Equals(typeof(byte))) - Console.WriteLine("{0} is an unsigned byte.", value); - else if (t.Equals(typeof(sbyte))) - Console.WriteLine("{0} is a signed byte.", value); - else if (t.Equals(typeof(int))) - Console.WriteLine("{0} is a 32-bit integer.", value); - else if (t.Equals(typeof(long))) - Console.WriteLine("{0} is a 64-bit integer.", value); - else if (t.Equals(typeof(double))) - Console.WriteLine("{0} is a double-precision floating point.", - value); - else - Console.WriteLine("'{0}' is another data type.", value); - } + foreach (object value in values) + { + Type t = value.GetType(); + if (t.Equals(typeof(byte))) + Console.WriteLine($"{value} is an unsigned byte."); + else if (t.Equals(typeof(sbyte))) + Console.WriteLine($"{value} is a signed byte."); + else if (t.Equals(typeof(int))) + Console.WriteLine($"{value} is a 32-bit integer."); + else if (t.Equals(typeof(long))) + Console.WriteLine($"{value} is a 64-bit integer."); + else if (t.Equals(typeof(double))) + Console.WriteLine($"{value} is a double-precision floating point."); + else + Console.WriteLine($"'{value}' is another data type."); + } - // The example displays the following output: - // 12 is a 32-bit integer. - // 10653 is a 64-bit integer. - // 12 is an unsigned byte. - // -5 is a signed byte. - // 16.3 is a double-precision floating point. - // 'string' is another data type. - // - } + // The example displays the following output: + // 12 is a 32-bit integer. + // 10653 is a 64-bit integer. + // 12 is an unsigned byte. + // -5 is a signed byte. + // 16.3 is a double-precision floating point. + // 'string' is another data type. + // + } } diff --git a/snippets/csharp/System/Object/GetType/Program.cs b/snippets/csharp/System/Object/GetType/Program.cs new file mode 100644 index 00000000000..5fd825006c1 --- /dev/null +++ b/snippets/csharp/System/Object/GetType/Program.cs @@ -0,0 +1,3 @@ +Test.Run(); +ObjectGetTypeExample1.Run(); +ObjectGetTypeExample2.Run(); diff --git a/snippets/csharp/System/Object/GetType/Project.csproj b/snippets/csharp/System/Object/GetType/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/Object/GetType/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/Object/GetType/gettype.cs b/snippets/csharp/System/Object/GetType/gettype.cs index 6979a2f7601..7215196251f 100644 --- a/snippets/csharp/System/Object/GetType/gettype.cs +++ b/snippets/csharp/System/Object/GetType/gettype.cs @@ -1,26 +1,28 @@ // using System; -public class MyBaseClass { +public class MyBaseClass +{ } -public class MyDerivedClass: MyBaseClass { +public class MyDerivedClass : MyBaseClass +{ } public class Test { - public static void Main() - { - MyBaseClass myBase = new MyBaseClass(); - MyDerivedClass myDerived = new MyDerivedClass(); - object o = myDerived; - MyBaseClass b = myDerived; + public static void Run() + { + MyBaseClass myBase = new(); + MyDerivedClass myDerived = new(); + object o = myDerived; + MyBaseClass b = myDerived; - Console.WriteLine("mybase: Type is {0}", myBase.GetType()); - Console.WriteLine("myDerived: Type is {0}", myDerived.GetType()); - Console.WriteLine("object o = myDerived: Type is {0}", o.GetType()); - Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType()); - } + Console.WriteLine($"mybase: Type is {myBase.GetType()}"); + Console.WriteLine($"myDerived: Type is {myDerived.GetType()}"); + Console.WriteLine($"object o = myDerived: Type is {o.GetType()}"); + Console.WriteLine($"MyBaseClass b = myDerived: Type is {b.GetType()}"); + } } // The example displays the following output: // mybase: Type is MyBaseClass diff --git a/snippets/csharp/System/Object/GetType/gettype1.cs b/snippets/csharp/System/Object/GetType/gettype1.cs index f2774e02f1d..5f5f0a7ffc6 100644 --- a/snippets/csharp/System/Object/GetType/gettype1.cs +++ b/snippets/csharp/System/Object/GetType/gettype1.cs @@ -1,22 +1,20 @@ using System; -public class Example +public class ObjectGetTypeExample1 { - public static void Main() - { - // - int n1 = 12; - int n2 = 82; - long n3 = 12; + public static void Run() + { + // + int n1 = 12; + int n2 = 82; + long n3 = 12; - Console.WriteLine("n1 and n2 are the same type: {0}", - Object.ReferenceEquals(n1.GetType(), n2.GetType())); - Console.WriteLine("n1 and n3 are the same type: {0}", - Object.ReferenceEquals(n1.GetType(), n3.GetType())); + Console.WriteLine($"n1 and n2 are the same type: {object.ReferenceEquals(n1.GetType(), n2.GetType())}"); + Console.WriteLine($"n1 and n3 are the same type: {object.ReferenceEquals(n1.GetType(), n3.GetType())}"); - // The example displays the following output: - // n1 and n2 are the same type: True - // n1 and n3 are the same type: False - // - } + // The example displays the following output: + // n1 and n2 are the same type: True + // n1 and n3 are the same type: False + // + } } diff --git a/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs b/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs index d1e01ad251a..7382e05a1a9 100644 --- a/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs +++ b/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs @@ -5,10 +5,7 @@ public class IdInfo { public int IdNumber; - public IdInfo(int IdNumber) - { - this.IdNumber = IdNumber; - } + public IdInfo(int IdNumber) => this.IdNumber = IdNumber; } public class Person @@ -17,15 +14,12 @@ public class Person public string Name; public IdInfo IdInfo; - public Person ShallowCopy() - { - return (Person)MemberwiseClone(); - } + public Person ShallowCopy() => (Person)MemberwiseClone(); public Person DeepCopy() { Person other = (Person)MemberwiseClone(); - other.IdInfo = new IdInfo(IdInfo.IdNumber); + other.IdInfo = new(IdInfo.IdNumber); return other; } } @@ -39,7 +33,7 @@ public static void Main() { Age = 42, Name = "Sam", - IdInfo = new IdInfo(6565) + IdInfo = new(6565) }; // Perform a shallow copy of p1 and assign it to p2. @@ -83,7 +77,7 @@ public static void DisplayValues(Person p) } /* The example displays the following output: - * + * * Original values of p1 and p2: p1 instance values: Name: Sam, Age: 42 diff --git a/snippets/csharp/System/Object/Overview/ObjectX.cs b/snippets/csharp/System/Object/Overview/ObjectX.cs index 9fdea2c6e6b..21a694f6ef0 100644 --- a/snippets/csharp/System/Object/Overview/ObjectX.cs +++ b/snippets/csharp/System/Object/Overview/ObjectX.cs @@ -1,4 +1,4 @@ -//Types:System.Object +//Types:System.Object // using System; @@ -20,33 +20,24 @@ public override bool Equals(object obj) if (obj.GetType() != this.GetType()) return false; // Return true if x and y fields match. - var other = (Point) obj; + var other = (Point)obj; return (this.x == other.x) && (this.y == other.y); } // // // Return the XOR of the x and y fields. - public override int GetHashCode() - { - return x ^ y; - } + public override int GetHashCode() => x ^ y; // // // Return the point's value as a string. - public override String ToString() - { - return $"({x}, {y})"; - } + public override string ToString() => $"({x}, {y})"; // // // Return a copy of this point object by making a simple field copy. - public Point Copy() - { - return (Point) this.MemberwiseClone(); - } + public Point Copy() => (Point)this.MemberwiseClone(); // } @@ -55,7 +46,7 @@ public sealed class App static void Main() { // Construct a Point object. - var p1 = new Point(1,2); + var p1 = new Point(1, 2); // Make another Point object that is a copy of the first. var p2 = p1.Copy(); @@ -63,18 +54,18 @@ static void Main() // Make another variable that references the first Point object. var p3 = p1; - // + // // The line below displays false because p1 and p2 refer to two different objects. - Console.WriteLine(Object.ReferenceEquals(p1, p2)); + Console.WriteLine(object.ReferenceEquals(p1, p2)); // // // The line below displays true because p1 and p2 refer to two different objects that have the same value. - Console.WriteLine(Object.Equals(p1, p2)); + Console.WriteLine(object.Equals(p1, p2)); // // The line below displays true because p1 and p3 refer to one object. - Console.WriteLine(Object.ReferenceEquals(p1, p3)); + Console.WriteLine(object.ReferenceEquals(p1, p3)); // // The line below displays: p1's value is: (1, 2) diff --git a/snippets/csharp/System/Object/ReferenceEquals/Program.cs b/snippets/csharp/System/Object/ReferenceEquals/Program.cs new file mode 100644 index 00000000000..c5491b97f1d --- /dev/null +++ b/snippets/csharp/System/Object/ReferenceEquals/Program.cs @@ -0,0 +1,3 @@ +MyClass.Run(); +ObjectReferenceEqualsExample1.Run(); +ObjectReferenceEqualsExample2.Run(); diff --git a/snippets/csharp/System/Object/ReferenceEquals/Project.csproj b/snippets/csharp/System/Object/ReferenceEquals/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/Object/ReferenceEquals/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs index ce5acd6f484..4e15698ca94 100644 --- a/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs +++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs @@ -1,22 +1,23 @@ using System; -class MyClass { +class MyClass +{ + public static void Run() + { + // + object o = null; + object p = null; + object q = new(); - static void Main() { - // - object o = null; - object p = null; - object q = new Object(); + Console.WriteLine(object.ReferenceEquals(o, p)); + p = q; + Console.WriteLine(object.ReferenceEquals(p, q)); + Console.WriteLine(object.ReferenceEquals(o, p)); - Console.WriteLine(Object.ReferenceEquals(o, p)); - p = q; - Console.WriteLine(Object.ReferenceEquals(p, q)); - Console.WriteLine(Object.ReferenceEquals(o, p)); - - // This code produces the following output: - // True - // True - // False - // - } + // This code produces the following output: + // True + // True + // False + // + } } diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs index 9c3204be773..c6ede57640a 100644 --- a/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs +++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs @@ -1,17 +1,17 @@ using System; -public class Example +public class ObjectReferenceEqualsExample1 { - public static void Main() - { - // - int int1 = 3; - Console.WriteLine(Object.ReferenceEquals(int1, int1)); - Console.WriteLine(int1.GetType().IsValueType); + public static void Run() + { + // + int int1 = 3; + Console.WriteLine(object.ReferenceEquals(int1, int1)); + Console.WriteLine(int1.GetType().IsValueType); - // The example displays the following output: - // False - // True - // - } + // The example displays the following output: + // False + // True + // + } } diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs index 82eb588bce7..1073ab78bd1 100644 --- a/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs +++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs @@ -1,28 +1,26 @@ using System; -public class Example +public class ObjectReferenceEqualsExample2 { - public static void Main() - { - // - String s1 = "String1"; - String s2 = "String1"; - Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2)); - Console.WriteLine("{0} interned: {1}", s1, - String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes"); + public static void Run() + { + // + string s1 = "String1"; + string s2 = "String1"; + Console.WriteLine($"s1 = s2: {object.ReferenceEquals(s1, s2)}"); + Console.WriteLine($"{s1} interned: {(string.IsNullOrEmpty(string.IsInterned(s1)) ? "No" : "Yes")}"); - String suffix = "A"; - String s3 = "String" + suffix; - String s4 = "String" + suffix; - Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4)); - Console.WriteLine("{0} interned: {1}", s3, - String.IsNullOrEmpty(String.IsInterned(s3)) ? "No" : "Yes"); + string suffix = "A"; + string s3 = "String" + suffix; + string s4 = "String" + suffix; + Console.WriteLine($"s3 = s4: {object.ReferenceEquals(s3, s4)}"); + Console.WriteLine($"{s3} interned: {(string.IsNullOrEmpty(string.IsInterned(s3)) ? "No" : "Yes")}"); - // The example displays the following output: - // s1 = s2: True - // String1 interned: Yes - // s3 = s4: False - // StringA interned: No - // - } + // The example displays the following output: + // s1 = s2: True + // String1 interned: Yes + // s3 = s4: False + // StringA interned: No + // + } } diff --git a/snippets/csharp/System/Object/ToString/array1.cs b/snippets/csharp/System/Object/ToString/array1.cs index cf7b237be0c..6ed34b9f10a 100644 --- a/snippets/csharp/System/Object/ToString/array1.cs +++ b/snippets/csharp/System/Object/ToString/array1.cs @@ -3,18 +3,18 @@ public class Example { - public static void Main() - { - // - int[] values = { 1, 2, 4, 8, 16, 32, 64, 128 }; - Console.WriteLine(values.ToString()); + public static void Main() + { + // + int[] values = { 1, 2, 4, 8, 16, 32, 64, 128 }; + Console.WriteLine(values.ToString()); - List list = new List(values); - Console.WriteLine(list.ToString()); + List list = new(values); + Console.WriteLine(list.ToString()); - // The example displays the following output: - // System.Int32[] - // System.Collections.Generic.List`1[System.Int32] - // - } + // The example displays the following output: + // System.Int32[] + // System.Collections.Generic.List`1[System.Int32] + // + } } diff --git a/snippets/csharp/System/Object/ToString/customize1.cs b/snippets/csharp/System/Object/ToString/customize1.cs index 6a8593a7b6c..d7fc7c42bb3 100644 --- a/snippets/csharp/System/Object/ToString/customize1.cs +++ b/snippets/csharp/System/Object/ToString/customize1.cs @@ -4,34 +4,33 @@ public class CList : List { - public CList(IEnumerable collection) : base(collection) - { } + public CList(IEnumerable collection) : base(collection) + { } - public CList() : base() - {} + public CList() : base() + { } - public override string ToString() - { - string retVal = string.Empty; - foreach (T item in this) { - if (string.IsNullOrEmpty(retVal)) - retVal += item.ToString(); - else - retVal += string.Format(", {0}", item); - } - return retVal; - } + public override string ToString() + { + string retVal = string.Empty; + foreach (T item in this) + { + if (string.IsNullOrEmpty(retVal)) + retVal += item.ToString(); + else + retVal += $", {item}"; + } + return retVal; + } } public class Example2 { - public static void Main() - { - var list2 = new CList(); - list2.Add(1000); - list2.Add(2000); - Console.WriteLine(list2.ToString()); - } + public static void Main() + { + var list2 = new CList() { 1000, 2000 }; + Console.WriteLine(list2.ToString()); + } } // The example displays the following output: // 1000, 2000 diff --git a/snippets/csharp/System/Object/ToString/customize2.cs b/snippets/csharp/System/Object/ToString/customize2.cs index bc7495d7690..3161e420315 100644 --- a/snippets/csharp/System/Object/ToString/customize2.cs +++ b/snippets/csharp/System/Object/ToString/customize2.cs @@ -4,42 +4,43 @@ public static class StringExtensions { - public static string ToString2(this List l) - { - string retVal = string.Empty; - foreach (T item in l) - retVal += string.Format("{0}{1}", string.IsNullOrEmpty(retVal) ? - "" : ", ", - item); - return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }"; - } + public static string ToString2(this List l) + { + string retVal = string.Empty; + foreach (T item in l) + retVal += $"{(string.IsNullOrEmpty(retVal) ? + "" : ", ")}{item}"; + return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }"; + } - public static string ToString(this List l, string fmt) - { - string retVal = string.Empty; - foreach (T item in l) { - IFormattable ifmt = item as IFormattable; - if (ifmt != null) - retVal += string.Format("{0}{1}", - string.IsNullOrEmpty(retVal) ? - "" : ", ", ifmt.ToString(fmt, null)); - else - retVal += ToString2(l); - } - return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }"; - } + public static string ToString(this List l, string fmt) + { + string retVal = string.Empty; + foreach (T item in l) + { + IFormattable ifmt = item as IFormattable; + if (ifmt != null) + retVal += $"{(string.IsNullOrEmpty(retVal) ? + "" : ", ")}{ifmt.ToString(fmt, null)}"; + else + retVal += ToString2(l); + } + return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }"; + } } public class Example3 { - public static void Main() - { - List list = new List(); - list.Add(1000); - list.Add(2000); - Console.WriteLine(list.ToString2()); - Console.WriteLine(list.ToString("N0")); - } + public static void Main() + { + List list = new() + { + 1000, + 2000 + }; + Console.WriteLine(list.ToString2()); + Console.WriteLine(list.ToString("N0")); + } } // The example displays the following output: // { 1000, 2000 } diff --git a/snippets/csharp/System/Object/ToString/tostring1.cs b/snippets/csharp/System/Object/ToString/tostring1.cs index 4651e461af2..ffe03decb9e 100644 --- a/snippets/csharp/System/Object/ToString/tostring1.cs +++ b/snippets/csharp/System/Object/ToString/tostring1.cs @@ -2,14 +2,14 @@ public class Example4 { - public static void Main() - { - // - Object obj = new Object(); - Console.WriteLine(obj.ToString()); + public static void Main() + { + // + object obj = new(); + Console.WriteLine(obj.ToString()); - // The example displays the following output: - // System.Object - // - } + // The example displays the following output: + // System.Object + // + } } diff --git a/snippets/csharp/System/Object/ToString/tostring2.cs b/snippets/csharp/System/Object/ToString/tostring2.cs index 651cd69732c..d4daca9616b 100644 --- a/snippets/csharp/System/Object/ToString/tostring2.cs +++ b/snippets/csharp/System/Object/ToString/tostring2.cs @@ -4,18 +4,18 @@ namespace Examples { - public class Object1 - { - } + public class Object1 + { + } } public class Example5 { - public static void Main() - { - object obj1 = new Object1(); - Console.WriteLine(obj1.ToString()); - } + public static void Main() + { + object obj1 = new Object1(); + Console.WriteLine(obj1.ToString()); + } } // The example displays the following output: // Examples.Object1 diff --git a/snippets/csharp/System/Object/ToString/tostring3.cs b/snippets/csharp/System/Object/ToString/tostring3.cs index 8752cac0b47..b9101a8114f 100644 --- a/snippets/csharp/System/Object/ToString/tostring3.cs +++ b/snippets/csharp/System/Object/ToString/tostring3.cs @@ -3,26 +3,20 @@ public class Object2 { - private object value; + private object value; - public Object2(object value) - { - this.value = value; - } + public Object2(object value) => this.value = value; - public override string ToString() - { - return base.ToString() + ": " + value.ToString(); - } + public override string ToString() => base.ToString() + ": " + value.ToString(); } public class Example6 { - public static void Main() - { - Object2 obj2 = new Object2('a'); - Console.WriteLine(obj2.ToString()); - } + public static void Main() + { + Object2 obj2 = new('a'); + Console.WriteLine(obj2.ToString()); + } } // The example displays the following output: // Object2: a diff --git a/snippets/csharp/System/Object/ToString/tostringoverload1.cs b/snippets/csharp/System/Object/ToString/tostringoverload1.cs index 83cf6df70ad..81a7c57be79 100644 --- a/snippets/csharp/System/Object/ToString/tostringoverload1.cs +++ b/snippets/csharp/System/Object/ToString/tostringoverload1.cs @@ -3,71 +3,60 @@ public class Automobile { - private int _doors; - private string _cylinders; - private int _year; - private string _model; + private int _doors; + private string _cylinders; + private int _year; + private string _model; - public Automobile(string model, int year , int doors, - string cylinders) - { - _model = model; - _year = year; - _doors = doors; - _cylinders = cylinders; - } + public Automobile(string model, int year, int doors, + string cylinders) + { + _model = model; + _year = year; + _doors = doors; + _cylinders = cylinders; + } - public int Doors - { get { return _doors; } } + public int Doors => _doors; - public string Model - { get { return _model; } } + public string Model => _model; - public int Year - { get { return _year; } } + public int Year => _year; - public string Cylinders - { get { return _cylinders; } } + public string Cylinders => _cylinders; - public override string ToString() - { - return ToString("G"); - } + public override string ToString() => ToString("G"); - public string ToString(string fmt) - { - if (string.IsNullOrEmpty(fmt)) - fmt = "G"; + public string ToString(string fmt) + { + if (string.IsNullOrEmpty(fmt)) + fmt = "G"; - switch (fmt.ToUpperInvariant()) - { - case "G": - return string.Format("{0} {1}", _year, _model); - case "D": - return string.Format("{0} {1}, {2} dr.", - _year, _model, _doors); - case "C": - return string.Format("{0} {1}, {2}", - _year, _model, _cylinders); - case "A": - return string.Format("{0} {1}, {2} dr. {3}", - _year, _model, _doors, _cylinders); - default: - string msg = string.Format("'{0}' is an invalid format string", - fmt); - throw new ArgumentException(msg); - } - } + switch (fmt.ToUpperInvariant()) + { + case "G": + return $"{_year} {_model}"; + case "D": + return $"{_year} {_model}, {_doors} dr."; + case "C": + return $"{_year} {_model}, {_cylinders}"; + case "A": + return $"{_year} {_model}, {_doors} dr. {_cylinders}"; + default: + string msg = $"'{fmt}' is an invalid format string"; + throw new ArgumentException(msg); + } + } } public class Example7 { - public static void Main() - { - var auto = new Automobile("Lynx", 2016, 4, "V8"); - Console.WriteLine(auto.ToString()); - Console.WriteLine(auto.ToString("A")); - } + public static void Main() + { + var auto = new Automobile("Lynx", 2016, 4, "V8"); + Console.WriteLine(auto.ToString()); + Console.WriteLine(auto.ToString("A")); + } } // The example displays the following output: // 2016 Lynx diff --git a/snippets/csharp/System/Object/ToString/tostringoverload2.cs b/snippets/csharp/System/Object/ToString/tostringoverload2.cs index cce98befd3e..75a86b2fbfe 100644 --- a/snippets/csharp/System/Object/ToString/tostringoverload2.cs +++ b/snippets/csharp/System/Object/ToString/tostringoverload2.cs @@ -1,19 +1,20 @@ -// +// using System; using System.Globalization; public class Example8 { - public static void Main() - { - string[] cultureNames = { "en-US", "en-GB", "fr-FR", + public static void Main() + { + string[] cultureNames = { "en-US", "en-GB", "fr-FR", "hr-HR", "ja-JP" }; - Decimal value = 1603.49m; - foreach (var cultureName in cultureNames) { - CultureInfo culture = new CultureInfo(cultureName); - Console.WriteLine($"{culture.Name}: {value.ToString("C2", culture)}"); - } - } + decimal value = 1603.49m; + foreach (string cultureName in cultureNames) + { + CultureInfo culture = new(cultureName); + Console.WriteLine($"{culture.Name}: {value.ToString("C2", culture)}"); + } + } } // The example displays the following output: // en-US: $1,603.49 diff --git a/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs b/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs index 684182d5d88..f48c42eaeed 100644 --- a/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs +++ b/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs @@ -4,21 +4,18 @@ public class Example { - public static void Main() - { - Timer t = new Timer(TimerNotification, null, - 100, Timeout.Infinite); - Thread.Sleep(2000); - t.Dispose(); + public static void Main() + { + Timer t = new(TimerNotification, null, + 100, Timeout.Infinite); + Thread.Sleep(2000); + t.Dispose(); - t.Change(200, 1000); - Thread.Sleep(3000); - } + t.Change(200, 1000); + Thread.Sleep(3000); + } - private static void TimerNotification(Object obj) - { - Console.WriteLine("Timer event fired at {0:F}", DateTime.Now); - } + private static void TimerNotification(object obj) => Console.WriteLine($"Timer event fired at {DateTime.Now:F}"); } // The example displays output like the following: // Timer event fired at Monday, July 14, 2014 11:54:08 AM diff --git a/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs b/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs index 162dc2167b1..fcd6b575cae 100644 --- a/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs +++ b/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs @@ -4,18 +4,18 @@ public class ObjectDisposedExceptionTest { - public static void Main() - { - MemoryStream ms = new MemoryStream(16); - ms.Close(); - try - { - ms.ReadByte(); - } - catch (ObjectDisposedException e) - { - Console.WriteLine("Caught: {0}", e.Message); - } - } + public static void Main() + { + MemoryStream ms = new(16); + ms.Close(); + try + { + ms.ReadByte(); + } + catch (ObjectDisposedException e) + { + Console.WriteLine($"Caught: {e.Message}"); + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs b/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs index 9c1c3d1348c..0cd8229c448 100644 --- a/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs +++ b/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs @@ -4,51 +4,45 @@ public class Example { - // Mark OldProperty As Obsolete. - [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)] - public string OldProperty - { get { return "The old property value."; } } + // Mark OldProperty As Obsolete. + [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)] + public string OldProperty => "The old property value."; - public string NewProperty - { get { return "The new property value."; } } + public string NewProperty => "The new property value."; - // Mark OldMethod As Obsolete. - [ObsoleteAttribute("This method is obsolete. Call NewMethod instead.", true)] - public string OldMethod() - { - return "You have called OldMethod."; - } + // Mark OldMethod As Obsolete. + [ObsoleteAttribute("This method is obsolete. Call NewMethod instead.", true)] + public string OldMethod() => "You have called OldMethod."; - public string NewMethod() - { - return "You have called NewMethod."; - } + public string NewMethod() => "You have called NewMethod."; - public static void Main() - { - // Get all public members of this type. - MemberInfo[] members = typeof(Example).GetMembers(); - // Count total obsolete members. - int n = 0; + public static void Main() + { + // Get all public members of this type. + MemberInfo[] members = typeof(Example).GetMembers(); + // Count total obsolete members. + int n = 0; - // Try to get the ObsoleteAttribute for each public member. - Console.WriteLine("Obsolete members in the Example class:\n"); - foreach (var member in members) { - ObsoleteAttribute[] attribs = (ObsoleteAttribute[]) - member.GetCustomAttributes(typeof(ObsoleteAttribute), - false); - if (attribs.Length > 0) { - ObsoleteAttribute attrib = attribs[0]; - Console.WriteLine("Member Name: {0}.{1}", member.DeclaringType.FullName, member.Name); - Console.WriteLine(" Message: {0}", attrib.Message); - Console.WriteLine(" Warning/Error: {0}", attrib.IsError ? "Error" : "Warning"); - n++; - } - } + // Try to get the ObsoleteAttribute for each public member. + Console.WriteLine("Obsolete members in the Example class:\n"); + foreach (var member in members) + { + ObsoleteAttribute[] attribs = (ObsoleteAttribute[]) + member.GetCustomAttributes(typeof(ObsoleteAttribute), + false); + if (attribs.Length > 0) + { + ObsoleteAttribute attrib = attribs[0]; + Console.WriteLine($"Member Name: {member.DeclaringType.FullName}.{member.Name}"); + Console.WriteLine($" Message: {attrib.Message}"); + Console.WriteLine($" Warning/Error: {(attrib.IsError ? "Error" : "Warning")}"); + n++; + } + } - if (n == 0) - Console.WriteLine("The Example type has no obsolete attributes."); - } + if (n == 0) + Console.WriteLine("The Example type has no obsolete attributes."); + } } // The example displays the following output: // Obsolete members in the Example class: diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj b/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs b/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs index b363324a60a..dea87202a8d 100644 --- a/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs +++ b/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs @@ -1,39 +1,34 @@ -// -using System; -using System.Reflection; +using System; public class Example { - // Mark OldProperty As Obsolete. - [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)] - public static string OldProperty - { get { return "The old property value."; } } - - public static string NewProperty - { get { return "The new property value."; } } - - // Mark CallOldMethod As Obsolete. - [ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", true)] - public static string CallOldMethod() - { - return "You have called CallOldMethod."; - } - - public static string CallNewMethod() - { - return "You have called CallNewMethod."; - } - - public static void Main() - { - Console.WriteLine(OldProperty); - Console.WriteLine(); - Console.WriteLine(CallOldMethod()); - } + // + + // Mark OldProperty As Obsolete. + [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)] + public static string OldProperty => "The old property value."; + + public static string NewProperty => "The new property value."; + + // Mark CallOldMethod As Obsolete. + [ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", true)] + public static string CallOldMethod() => "You have called CallOldMethod."; + + public static string CallNewMethod() => "You have called CallNewMethod."; + + public static void Main() + { + Console.WriteLine(OldProperty); + Console.WriteLine(); + // This call intentionally results in a compiler error. + Console.WriteLine(CallOldMethod()); + } + + // The attempt to compile this example produces output like the following output: + // Example.cs(31,25): error CS0619: 'Example.CallOldMethod()' is obsolete: + // 'This method is obsolete. Call CallNewMethod instead.' + // Example.cs(29,25): warning CS0618: 'Example.OldProperty' is obsolete: + // 'This property is obsolete. Use NewProperty instead.' + + // } -// The attempt to compile this example produces output like the following output: -// Example.cs(31,25): error CS0619: 'Example.CallOldMethod()' is obsolete: -// 'This method is obsolete. Call CallNewMethod instead.' -// Example.cs(29,25): warning CS0618: 'Example.OldProperty' is obsolete: -// 'This property is obsolete. Use NewProperty instead.' -// diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json b/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json new file mode 100644 index 00000000000..11be0770fa1 --- /dev/null +++ b/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json @@ -0,0 +1,10 @@ +{ + "host": "dotnet", + "expectederrors": [ + { + "file": "snippets\\csharp\\System\\ObsoleteAttribute\\Overview\\obsoleteattributeex1.cs", + "line": 24, + "error": "CS0619" + } + ] +} diff --git a/snippets/csharp/System/OperatingSystem/Clone/clone.cs b/snippets/csharp/System/OperatingSystem/Clone/clone.cs index 705fcb4c7f6..7d31c8ad8a2 100644 --- a/snippets/csharp/System/OperatingSystem/Clone/clone.cs +++ b/snippets/csharp/System/OperatingSystem/Clone/clone.cs @@ -5,42 +5,34 @@ class CloneCompareDemo { // Copy, clone, and duplicate an OperatingSystem object. - static void CopyOperatingSystemObjects( ) + static void CopyOperatingSystemObjects() { // The Version object does not need to correspond to an // actual OS version. - Version verMMBVer = new Version( 5, 6, 7, 8 ); + Version verMMBVer = new(5, 6, 7, 8); - OperatingSystem opCreate1 = new - OperatingSystem( PlatformID.Win32NT, verMMBVer ); + OperatingSystem opCreate1 = new(PlatformID.Win32NT, verMMBVer); // Create another OperatingSystem object with the same // parameters as opCreate1. - OperatingSystem opCreate2 = new - OperatingSystem( PlatformID.Win32NT, verMMBVer ); + OperatingSystem opCreate2 = new(PlatformID.Win32NT, verMMBVer); // Clone opCreate1 and copy the opCreate1 reference. OperatingSystem opClone = - (OperatingSystem)opCreate1.Clone( ); + (OperatingSystem)opCreate1.Clone(); OperatingSystem opCopy = opCreate1; // Compare the various objects for equality. - Console.WriteLine( "{0,-50}{1}", - "Is the second object the same as the original?", - opCreate1.Equals( opCreate2 ) ); - Console.WriteLine( "{0,-50}{1}", - "Is the object clone the same as the original?", - opCreate1.Equals( opClone ) ); - Console.WriteLine( "{0,-50}{1}", - "Is the copied object the same as the original?", - opCreate1.Equals( opCopy ) ); + Console.WriteLine($"{"Is the second object the same as the original?",-50}{opCreate1.Equals(opCreate2)}"); + Console.WriteLine($"{"Is the object clone the same as the original?",-50}{opCreate1.Equals(opClone)}"); + Console.WriteLine($"{"Is the copied object the same as the original?",-50}{opCreate1.Equals(opCopy)}"); } - static void Main( ) + static void Main() { Console.WriteLine( "This example of OperatingSystem.Clone( ) " + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Create an OperatingSystem object, and then " + "create another object with the \n" + @@ -49,9 +41,9 @@ static void Main( ) "each object with the original " + "using the Equals( ) method. Equals( ) \n" + "returns true only when both " + - "references refer to the same object.\n" ); + "references refer to the same object.\n"); - CopyOperatingSystemObjects( ); + CopyOperatingSystemObjects(); } } diff --git a/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs b/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs index dc03f9023a9..c25e34a4dd8 100644 --- a/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs +++ b/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - var os = Environment.OSVersion; - Console.WriteLine("Current OS Information:\n"); - Console.WriteLine("Platform: {0:G}", os.Platform); - Console.WriteLine("Version String: {0}", os.VersionString); - Console.WriteLine("Version Information:"); - Console.WriteLine(" Major: {0}", os.Version.Major); - Console.WriteLine(" Minor: {0}", os.Version.Minor); - Console.WriteLine("Service Pack: '{0}'", os.ServicePack); - } + public static void Main() + { + var os = Environment.OSVersion; + Console.WriteLine("Current OS Information:\n"); + Console.WriteLine($"Platform: {os.Platform:G}"); + Console.WriteLine($"Version String: {os.VersionString}"); + Console.WriteLine("Version Information:"); + Console.WriteLine($" Major: {os.Version.Major}"); + Console.WriteLine($" Minor: {os.Version.Minor}"); + Console.WriteLine($"Service Pack: '{os.ServicePack}'"); + } } // If run on a Windows 8.1 system, the example displays output like the following: // Current OS Information: @@ -33,4 +33,4 @@ public static void Main() // Major: 6 // Minor: 1 // Service Pack: 'Service Pack 1' -// \ No newline at end of file +// diff --git a/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs b/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs index 05b27d594c2..0d606fc6876 100644 --- a/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs +++ b/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs @@ -7,52 +7,51 @@ class PlatformVersionDemo { // Create an OperatingSystem object and display the Platform // and Version properties. - static void BuildOSObj( PlatformID pID, Version ver ) + static void BuildOSObj(PlatformID pID, Version ver) { - OperatingSystem opSys = new OperatingSystem( pID, ver ); - PlatformID platform = opSys.Platform; - Version version = opSys.Version; + OperatingSystem opSys = new(pID, ver); + PlatformID platform = opSys.Platform; + Version version = opSys.Version; - Console.WriteLine( " Platform: {0,-15} Version: {1}", - platform, version ); + Console.WriteLine($" Platform: {platform,-15} Version: {version}"); } - static void BuildOperatingSystemObjects( ) + static void BuildOperatingSystemObjects() { // The Version object does not need to correspond to an // actual OS version. - Version verNull = new Version( ); - Version verString = new Version( "3.5.8.13" ); - Version verMajMin = new Version( 6, 10 ); - Version verMMBld = new Version( 5, 25, 5025 ); - Version verMMBVer = new Version( 5, 6, 7, 8 ); + Version verNull = new(); + Version verString = new("3.5.8.13"); + Version verMajMin = new(6, 10); + Version verMMBld = new(5, 25, 5025); + Version verMMBVer = new(5, 6, 7, 8); // All PlatformID members are shown here. - BuildOSObj( PlatformID.Win32NT, verNull ); - BuildOSObj( PlatformID.Win32S, verString ); - BuildOSObj( PlatformID.Win32Windows, verMajMin ); - BuildOSObj( PlatformID.WinCE, verMMBld ); - BuildOSObj( PlatformID.Win32NT, verMMBVer ); + BuildOSObj(PlatformID.Win32NT, verNull); + BuildOSObj(PlatformID.Win32S, verString); + BuildOSObj(PlatformID.Win32Windows, verMajMin); + BuildOSObj(PlatformID.WinCE, verMMBld); + BuildOSObj(PlatformID.Win32NT, verMMBVer); } - static void Main( ) + static void Main() { Console.WriteLine( "This example of OperatingSystem.Platform " + "and OperatingSystem.Version \n" + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Create several OperatingSystem objects " + - "and display their properties:\n" ); + "and display their properties:\n"); - BuildOperatingSystemObjects( ); + BuildOperatingSystemObjects(); Console.WriteLine( - "\nThe operating system of the host computer is:\n" ); + "\nThe operating system of the host computer is:\n"); BuildOSObj( Environment.OSVersion.Platform, - Environment.OSVersion.Version ); + Environment.OSVersion.Version); } } diff --git a/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs b/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs index d3bbb823032..f8c8b572acc 100644 --- a/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs +++ b/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs @@ -6,9 +6,9 @@ class Sample { public static void Main() { - OperatingSystem os = Environment.OSVersion; - String sp = os.ServicePack; - Console.WriteLine("Service pack version = \"{0}\"", sp); + OperatingSystem os = Environment.OSVersion; + string sp = os.ServicePack; + Console.WriteLine($"Service pack version = \"{sp}\""); } } /* @@ -17,4 +17,4 @@ public static void Main() Service pack version = "Service Pack 1" */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs b/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs index eb0d575a92e..19f36ac13dc 100644 --- a/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs +++ b/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs @@ -6,46 +6,44 @@ class OpSysConstructDemo { // Create and display an OperatingSystem object. - static void BuildOSObj( PlatformID pID, Version ver ) + static void BuildOSObj(PlatformID pID, Version ver) { - OperatingSystem os = new OperatingSystem( pID, ver ); + OperatingSystem os = new(pID, ver); - Console.WriteLine( " {0}", os.ToString( ) ); + Console.WriteLine($" {os.ToString()}"); } - static void BuildOperatingSystemObjects( ) + static void BuildOperatingSystemObjects() { // The Version object does not need to correspond to an // actual OS version. - Version verNull = new Version( ); - Version verMajMin = new Version( 3, 11 ); - Version verMMBld = new Version( 5, 25, 625 ); - Version verMMBVer = new Version( 5, 6, 7, 8 ); - Version verString = new Version( "3.5.8.13" ); + Version verNull = new(); + Version verMajMin = new(3, 11); + Version verMMBld = new(5, 25, 625); + Version verMMBVer = new(5, 6, 7, 8); + Version verString = new("3.5.8.13"); // All PlatformID members are shown here. - BuildOSObj( PlatformID.Win32NT, verNull ); - BuildOSObj( PlatformID.Win32S, verMajMin ); - BuildOSObj( PlatformID.Win32Windows, verMMBld ); - BuildOSObj( PlatformID.WinCE, verMMBVer ); - BuildOSObj( PlatformID.Win32NT, verString ); + BuildOSObj(PlatformID.Win32NT, verNull); + BuildOSObj(PlatformID.Win32S, verMajMin); + BuildOSObj(PlatformID.Win32Windows, verMMBld); + BuildOSObj(PlatformID.WinCE, verMMBVer); + BuildOSObj(PlatformID.Win32NT, verString); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the OperatingSystem constructor " + "and \nOperatingSystem.ToString( ) " + - "generates the following output.\n" ); + "generates the following output.\n"); Console.WriteLine( "Create and display several different " + - "OperatingSystem objects:\n" ); + "OperatingSystem objects:\n"); - BuildOperatingSystemObjects( ); + BuildOperatingSystemObjects(); - Console.WriteLine( - "\nThe OS version of the host computer is:\n\n {0}", - Environment.OSVersion.ToString( ) ); + Console.WriteLine($"\nThe OS version of the host computer is:\n\n {Environment.OSVersion.ToString()}"); } } diff --git a/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs b/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs index 330baa296cf..909f0330401 100644 --- a/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs +++ b/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs @@ -6,10 +6,10 @@ class Sample { public static void Main() { - OperatingSystem os = Environment.OSVersion; -// Display the value of OperatingSystem.VersionString. By default, this is -// the same value as OperatingSystem.ToString. - Console.WriteLine("This operating system is {0}", os.VersionString); + OperatingSystem os = Environment.OSVersion; + // Display the value of OperatingSystem.VersionString. By default, this is + // the same value as OperatingSystem.ToString. + Console.WriteLine($"This operating system is {os.VersionString}"); } } /* @@ -17,4 +17,4 @@ public static void Main() This operating system is Microsoft Windows NT 5.1.2600.0 Service Pack 1 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs b/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs new file mode 100644 index 00000000000..e40728734f5 --- /dev/null +++ b/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs @@ -0,0 +1,4 @@ +OutOfMemoryExceptionExample1.Run(); +OutOfMemoryExceptionExample2.Run(); +OutOfMemoryExceptionExample3.Run(); +OutOfMemoryExceptionExample4.Run(); diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj b/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs index c1426bc6baf..1aa2d6eb7d5 100644 --- a/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs +++ b/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs @@ -2,37 +2,36 @@ using System; using System.Collections.Generic; -public class Example +public class OutOfMemoryExceptionExample1 { - public static void Main() - { - Double[] values = GetData(); - // Compute mean. - Console.WriteLine("Sample mean: {0}, N = {1}", - GetMean(values), values.Length); - } + public static void Run() + { + double[] values = GetData(); + // Compute mean. + Console.WriteLine($"Sample mean: {GetMean(values)}, N = {values.Length}"); + } - private static Double[] GetData() - { - Random rnd = new Random(); - List values = new List(); - for (int ctr = 1; ctr <= 200000000; ctr++) { - values.Add(rnd.NextDouble()); - if (ctr % 10000000 == 0) - Console.WriteLine("Retrieved {0:N0} items of data.", - ctr); - } - return values.ToArray(); - } + private static double[] GetData() + { + Random rnd = new(); + List values = new(); + for (int ctr = 1; ctr <= 200000000; ctr++) + { + values.Add(rnd.NextDouble()); + if (ctr % 10000000 == 0) + Console.WriteLine($"Retrieved {ctr:N0} items of data."); + } + return values.ToArray(); + } - private static Double GetMean(Double[] values) - { - Double sum = 0; - foreach (var value in values) - sum += value; + private static double GetMean(double[] values) + { + double sum = 0; + foreach (double value in values) + sum += value; - return sum / values.Length; - } + return sum / values.Length; + } } // The example displays output like the following: // Retrieved 10,000,000 items of data. diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs b/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs index 1bc52b4c686..af03dede687 100644 --- a/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs +++ b/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs @@ -1,43 +1,44 @@ // using System; -using System.IO; -public class Example + +public class OutOfMemoryExceptionExample2 { - public static void Main() - { - Tuple result = GetResult(); - Console.WriteLine("Sample mean: {0}, N = {1:N0}", - result.Item1, result.Item2); - } + public static void Run() + { + Tuple result = GetResult(); + Console.WriteLine($"Sample mean: {result.Item1}, N = {result.Item2:N0}"); + } - private static Tuple GetResult() - { - int chunkSize = 50000000; - int nToGet = 200000000; - Random rnd = new Random(); - // FileStream fs = new FileStream(@".\data.bin", FileMode.Create); - // BinaryWriter bin = new BinaryWriter(fs); - // bin.Write((int)0); - int n = 0; - Double sum = 0; - for (int outer = 0; - outer <= ((int) Math.Ceiling(nToGet * 1.0 / chunkSize) - 1); - outer++) { - for (int inner = 0; - inner <= Math.Min(nToGet - n - 1, chunkSize - 1); - inner++) { - Double value = rnd.NextDouble(); - sum += value; - n++; - // bin.Write(value); - } - } - // bin.Seek(0, SeekOrigin.Begin); - // bin.Write(n); - // bin.Close(); - return new Tuple(sum/n, n); - } + private static Tuple GetResult() + { + int chunkSize = 50000000; + int nToGet = 200000000; + Random rnd = new(); + // FileStream fs = new FileStream(@".\data.bin", FileMode.Create); + // BinaryWriter bin = new BinaryWriter(fs); + // bin.Write((int)0); + int n = 0; + double sum = 0; + for (int outer = 0; + outer <= ((int)Math.Ceiling(nToGet * 1.0 / chunkSize) - 1); + outer++) + { + for (int inner = 0; + inner <= Math.Min(nToGet - n - 1, chunkSize - 1); + inner++) + { + double value = rnd.NextDouble(); + sum += value; + n++; + // bin.Write(value); + } + } + // bin.Seek(0, SeekOrigin.Begin); + // bin.Write(n); + // bin.Close(); + return new Tuple(sum / n, n); + } } // The example displays output like the following: // Sample mean: 0.500022771458399, N = 200,000,000 diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs index 4f491b0a9c4..b294c975cca 100644 --- a/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs +++ b/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs @@ -1,31 +1,34 @@ // using System; -public class Example +public class OutOfMemoryExceptionExample3 { - public static void Main() - { - try { - // Outer block to handle any unexpected exceptions. - try { - string s = "This"; - s = s.Insert(2, "is "); + public static void Run() + { + try + { + // Outer block to handle any unexpected exceptions. + try + { + string s = "This"; + s = s.Insert(2, "is "); - // Throw an OutOfMemoryException exception. - throw new OutOfMemoryException(); - } - catch (ArgumentException) { - Console.WriteLine("ArgumentException in String.Insert"); - } + // Throw an OutOfMemoryException exception. + throw new OutOfMemoryException(); + } + catch (ArgumentException) + { + Console.WriteLine("ArgumentException in String.Insert"); + } - // Execute program logic. - } - catch (OutOfMemoryException e) { - Console.WriteLine("Terminating application unexpectedly..."); - Environment.FailFast(String.Format("Out of Memory: {0}", - e.Message)); - } - } + // Execute program logic. + } + catch (OutOfMemoryException e) + { + Console.WriteLine("Terminating application unexpectedly..."); + Environment.FailFast($"Out of Memory: {e.Message}"); + } + } } // The example displays the following output: // Terminating application unexpectedly... diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs index a879f70bc01..03bff3781f7 100644 --- a/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs +++ b/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs @@ -2,19 +2,21 @@ using System; using System.Text; -public class Example +public class OutOfMemoryExceptionExample4 { - public static void Main() - { - StringBuilder sb = new StringBuilder(15, 15); - sb.Append("Substring #1 "); - try { - sb.Insert(0, "Substring #2 ", 1); - } - catch (OutOfMemoryException e) { - Console.WriteLine("Out of Memory: {0}", e.Message); - } - } + public static void Run() + { + StringBuilder sb = new(15, 15); + sb.Append("Substring #1 "); + try + { + sb.Insert(0, "Substring #2 ", 1); + } + catch (OutOfMemoryException e) + { + Console.WriteLine($"Out of Memory: {e.Message}"); + } + } } // The example displays the following output: // Out of Memory: Insufficient memory to continue the execution of the program. diff --git a/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs b/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs index 40759953456..09ae86bef64 100644 --- a/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs +++ b/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs @@ -2,63 +2,68 @@ public class Example { - public static void Main() - { - // - int value = 780000000; - checked { - try { - // Square the original value. - int square = value * value; - Console.WriteLine("{0} ^ 2 = {1}", value, square); - } - catch (OverflowException) { - double square = Math.Pow(value, 2); - Console.WriteLine("Exception: {0} > {1:E}.", - square, Int32.MaxValue); - } } - // The example displays the following output: - // Exception: 6.084E+17 > 2.147484E+009. - // + public static void Main() + { + // + int value = 780000000; + checked + { + try + { + // Square the original value. + int square = value * value; + Console.WriteLine($"{value} ^ 2 = {square}"); + } + catch (OverflowException) + { + double square = Math.Pow(value, 2); + Console.WriteLine($"Exception: {square} > {int.MaxValue:E}."); + } + } + // The example displays the following output: + // Exception: 6.084E+17 > 2.147484E+009. + // - Cast(); - Unchecked(); - } + Cast(); + Unchecked(); + } - private static void Cast() - { - // - byte value = 241; - checked { - try { - sbyte newValue = (sbyte) value; - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - newValue.GetType().Name, newValue); - } - catch (OverflowException) { - Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue); - } } - // The example displays the following output: - // Exception: 241 > 127. - // - } + private static void Cast() + { + // + byte value = 241; + checked + { + try + { + sbyte newValue = (sbyte)value; + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {newValue.GetType().Name} value {newValue}."); + } + catch (OverflowException) + { + Console.WriteLine($"Exception: {value} > {sbyte.MaxValue}."); + } + } + // The example displays the following output: + // Exception: 241 > 127. + // + } - private static void Unchecked() - { - // - byte value = 241; - try { - sbyte newValue = (sbyte) value; - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - newValue.GetType().Name, newValue); - } - catch (OverflowException) { - Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue); - } - // The example displays the following output: - // Converted the Byte value 241 to the SByte value -15. - // - } + private static void Unchecked() + { + // + byte value = 241; + try + { + sbyte newValue = (sbyte)value; + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {newValue.GetType().Name} value {newValue}."); + } + catch (OverflowException) + { + Console.WriteLine($"Exception: {value} > {sbyte.MaxValue}."); + } + // The example displays the following output: + // Converted the Byte value 241 to the SByte value -15. + // + } } diff --git a/xml/System/ObsoleteAttribute.xml b/xml/System/ObsoleteAttribute.xml index 2d2d6ef8d0f..3fa1933077f 100644 --- a/xml/System/ObsoleteAttribute.xml +++ b/xml/System/ObsoleteAttribute.xml @@ -1,3 +1,4 @@ + @@ -55,14 +56,8 @@ - - Marks program elements that are no longer in use. - - - Source code imported from - - ObsoleteAttribute.cs without any changes, all resulting warnings ignored accordingly. - + Marks program elements that are no longer in use. + To be added. attribute. Accessing the value of the `OldProperty` property in code generates a compiler warning, but calling the `CallOldMethod` method generates a compiler error. The example also shows the output that results when you attempt to compile the source code. From e6022b7639b38efa9782523fe6ff8d271094c428 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:55:30 -0700 Subject: [PATCH 4/9] Modernize C# code snippets - System/Type (#12973) --- .../Type/AssemblyQualifiedName/fullname1.cs | 6 +- .../System/Type/Attributes/attributes1.cs | 162 +++++++++--------- .../csharp/System/Type/BaseType/basetype3.cs | 42 ++--- .../csharp/System/Type/BaseType/remarks.cs | 6 +- .../System/Type/BaseType/testbasetype.cs | 4 +- .../Type/ContainsGenericParameters/source.cs | 29 ++-- .../System/Type/DeclaringMethod/source.cs | 26 +-- .../System/Type/DeclaringType/remarks.cs | 8 +- .../System/Type/DeclaringType/source.cs | 8 +- .../Type/DefaultBinder/type_defaultbinder.cs | 15 +- .../System/Type/EmptyTypes/Project.csproj | 6 + .../csharp/System/Type/EmptyTypes/source.cs | 12 +- .../csharp/System/Type/Equals/EqualsEx1.cs | 71 ++++---- snippets/csharp/System/Type/Equals/Program.cs | 2 + .../csharp/System/Type/Equals/Project.csproj | 6 + snippets/csharp/System/Type/Equals/source.cs | 22 +-- .../FilterAttribute/type_filterattribute.cs | 18 +- .../System/Type/FilterName/Project.csproj | 6 + .../csharp/System/Type/FilterName/source.cs | 30 ++-- .../type_filternameignorecase.cs | 16 +- .../FindInterfaces/type_findinterfaces.cs | 36 ++-- .../Type/FindMembers/type_findmembers.cs | 18 +- .../csharp/System/Type/FullName/Fullname3.cs | 34 ++-- .../csharp/System/Type/FullName/Fullname4.cs | 59 +++---- .../csharp/System/Type/FullName/Fullname5.cs | 50 +++--- .../csharp/System/Type/FullName/Program.cs | 5 + .../System/Type/FullName/Project.csproj | 6 + .../System/Type/FullName/fullnameex1.cs | 20 +-- .../System/Type/FullName/testfullname.cs | 8 +- snippets/csharp/System/Type/GUID/type_guid.cs | 8 +- .../Type/GenericParameterAttributes/source.cs | 38 ++-- .../Type/GenericParameterPosition/remarks.cs | 11 +- .../Type/GetArrayRank/type_getarrayrank.cs | 8 +- .../System/Type/GetConstructors/Program.cs | 2 + .../Type/GetConstructors/Project.csproj | 6 + .../System/Type/GetConstructors/source1.cs | 32 ++-- .../System/Type/GetConstructors/source2.cs | 36 ++-- .../System/Type/GetDefaultMembers/source2.cs | 24 +-- .../type_getdefaultmembers.cs | 24 +-- .../Type/GetElementType/testgetelementtype.cs | 10 +- .../csharp/System/Type/GetEvent/Program.cs | 2 + .../System/Type/GetEvent/Project.csproj | 7 + .../System/Type/GetEvent/type_getevent.cs | 20 +-- .../System/Type/GetEvent/type_getevent1.cs | 20 +-- .../csharp/System/Type/GetEvents/Program.cs | 2 + .../System/Type/GetEvents/Project.csproj | 7 + .../System/Type/GetEvents/type_getevents1.cs | 14 +- .../System/Type/GetEvents/type_getevents2.cs | 14 +- .../System/Type/GetField/type_getfield.cs | 19 +- .../Type/GetFields/fieldinfo_isspecialname.cs | 13 +- .../csharp/System/Type/GetFields/source.cs | 11 +- .../System/Type/GetGenericArguments/source.cs | 23 +-- .../Type/GetGenericTypeDefinition/source.cs | 18 +- .../System/Type/GetHashCode/Project.csproj | 7 + .../GetHashCode/type_gethashcode_getfields.cs | 31 ++-- .../System/Type/GetInterface/Project.csproj | 6 + .../Type/GetInterface/type_getinterface.cs | 40 ++--- .../Type/GetInterfaceMap/Project.csproj | 6 + .../Type/GetInterfaceMap/interfacemapping1.cs | 60 +++---- .../System/Type/GetMember/type_getmember.cs | 48 +++--- .../csharp/System/Type/GetMembers/Program.cs | 2 + .../System/Type/GetMembers/Project.csproj | 6 + .../Type/GetMembers/type_getmembers1.cs | 72 ++++---- .../Type/GetMembers/type_getmembers2.cs | 82 ++++----- .../System/Type/GetMethod/GetMethod1.cs | 88 +++++----- .../Type/GetMethod/GetMethodWithOverloads1.cs | 32 ++-- .../Type/GetMethod/GetMethodWithOverloads2.cs | 21 +-- .../System/Type/GetMethod/type_getmethod1.cs | 2 +- .../System/Type/GetMethod/type_getmethod2.cs | 2 +- .../System/Type/GetMethod/type_getmethod3.cs | 92 +++++----- .../System/Type/GetMethod/type_getmethod4.cs | 64 +++---- .../System/Type/GetMethod/type_getmethod5.cs | 82 ++++----- .../Type/GetMethods/type_getmethods2.cs | 28 ++- .../type_getnestedclassesabs.cs | 12 +- .../GetNestedTypes/type_getnestedtypes.cs | 20 +-- .../Type/GetProperties/type_getproperties2.cs | 87 ++++------ .../Type/GetProperties/type_gettypecode.cs | 30 ++-- .../Type/GetProperty/type_getproperty1.cs | 2 +- .../Type/GetProperty/type_getproperty2.cs | 2 +- .../Type/GetProperty/type_getproperty21.cs | 26 ++- .../Type/GetProperty/type_getproperty3.cs | 17 +- .../GetProperty/type_getproperty_types.cs | 12 +- .../csharp/System/Type/GetType/Project.csproj | 4 +- .../Type/GetType/mypath/v5.0/myassembly.cs | 4 +- snippets/csharp/System/Type/GetType/source.cs | 2 +- .../System/Type/GetType/type_gettype.cs | 43 ++--- .../System/Type/GetTypeCode/iconvertible.cs | 107 +++--------- .../System/Type/GetTypeFromCLSID/Program.cs | 5 + .../Type/GetTypeFromCLSID/Project.csproj | 6 + .../GetTypeFromCLSID/gettypefromclsid1.cs | 35 ++-- .../GetTypeFromCLSID/gettypefromclsid11.cs | 108 ++++++------ .../GetTypeFromCLSID/gettypefromclsid_ex2.cs | 48 +++--- .../GetTypeFromCLSID/gettypefromclsid_ex3.cs | 46 ++--- .../GetTypeFromCLSID/gettypefromclsid_ex4.cs | 56 +++--- .../type_gettypefromhandle.cs | 18 +- .../System/Type/GetTypeFromProgID/Program.cs | 3 + .../Type/GetTypeFromProgID/Project.csproj | 6 + .../type_gettypefromprogid2.cs | 20 +-- .../type_gettypefromprogid3.cs | 22 +-- .../type_gettypefromprogid4.cs | 22 +-- .../System/Type/HasElementType/Project.csproj | 7 + .../HasElementType/type_haselementtype.cs | 25 ++- .../type_haselementtypeimpl.cs | 31 ++-- .../System/Type/InvokeMember/invokemem.cs | 34 ++-- .../System/Type/IsAbstract/isabstract1.cs | 36 ++-- .../Type/IsAnsiClass/type_isansiclass.cs | 16 +- .../csharp/System/Type/IsArray/isarray2.cs | 19 +- .../Type/IsArrayImpl/type_isarrayimpl.cs | 25 ++- .../IsAssignableFrom/IsAssignableFrom2.cs | 20 +-- .../IsAssignableFrom/IsAssignableFrom3.cs | 26 +-- .../System/Type/IsAssignableFrom/Program.cs | 4 + .../Type/IsAssignableFrom/Project.csproj | 6 + .../IsAssignableFrom/isassignablefrom_ex1.cs | 31 ++-- .../IsAssignableFrom/testisassignablefrom.cs | 114 ++++++------ .../Type/IsAutoLayout/type_isautolayout.cs | 7 +- .../System/Type/IsClass/type_isclass.cs | 12 +- .../System/Type/IsContextful/Project.csproj | 6 + .../Type/IsContextful/type_iscontextful.cs | 28 ++- .../IsContextfulImpl/type_iscontextfulimpl.cs | 25 ++- .../csharp/System/Type/IsEnum/testisenum.cs | 14 +- .../IsExplicitLayout/type_isexplicitlayout.cs | 29 ++-- .../System/Type/IsGenericParameter/source.cs | 23 +-- .../System/Type/IsGenericType/Program.cs | 2 + .../System/Type/IsGenericType/Project.csproj | 6 + .../System/Type/IsGenericType/remarks.cs | 20 +-- .../System/Type/IsGenericType/source.cs | 32 ++-- .../IsInstanceOfType/testisinstanceoftype.cs | 23 +-- .../Type/IsInterface/type_isinterface.cs | 12 +- .../type_islayoutsequential.cs | 18 +- .../type_ismarshalbyrefimpl.cs | 25 ++- .../IsNested/isnestedfamilyandassembly1.cs | 47 ++--- .../csharp/System/Type/IsNotPublic/source.cs | 8 +- .../IsPrimitiveImpl/type_isprimitiveimpl.cs | 27 ++- .../System/Type/IsPublic/type_ispublic.cs | 18 +- .../System/Type/IsSealed/type_issealed.cs | 32 ++-- .../IsSubclassOf/issubclassof_interface1.cs | 21 +-- .../Type/IsSubclassOf/testissubclassof.cs | 8 +- .../Type/IsValueType/type_isvaluetype.cs | 4 +- .../csharp/System/Type/IsVisible/source.cs | 18 +- .../System/Type/MakeByRefType/source.cs | 14 +- .../System/Type/MakeGenericType/remarks.cs | 10 +- .../System/Type/MakeGenericType/source.cs | 29 ++-- .../csharp/System/Type/Missing/Project.csproj | 9 + snippets/csharp/System/Type/Missing/source.cs | 17 +- .../System/Type/Module/type_tostring.cs | 20 +-- .../csharp/System/Type/Overview/Equals1.cs | 8 +- .../csharp/System/Type/Overview/GetType1.cs | 6 +- .../csharp/System/Type/Overview/source.cs | 10 +- .../System/Type/ReflectedType/source.cs | 5 +- .../Type/StructLayoutAttribute/source.cs | 8 +- .../System/Type/TypeHandle/type_typehandle.cs | 14 +- .../Overview/Missing1.cs | 20 +-- .../Overview/Missing1a.cs | 23 +-- .../Overview/Regex1.cs | 6 +- .../Overview/ctorException1.cs | 32 ++-- .../.ctor/typeloadexception_constructor2.cs | 32 ++-- .../.ctor/typeloadexception_constructor3.cs | 64 +++---- .../Message/typeloadexception_typename.cs | 41 +++-- .../System/TypedReference/Overview/source.cs | 28 +-- 159 files changed, 1886 insertions(+), 2003 deletions(-) create mode 100644 snippets/csharp/System/Type/EmptyTypes/Project.csproj create mode 100644 snippets/csharp/System/Type/Equals/Program.cs create mode 100644 snippets/csharp/System/Type/Equals/Project.csproj create mode 100644 snippets/csharp/System/Type/FilterName/Project.csproj create mode 100644 snippets/csharp/System/Type/FullName/Program.cs create mode 100644 snippets/csharp/System/Type/FullName/Project.csproj create mode 100644 snippets/csharp/System/Type/GetConstructors/Program.cs create mode 100644 snippets/csharp/System/Type/GetConstructors/Project.csproj create mode 100644 snippets/csharp/System/Type/GetEvent/Program.cs create mode 100644 snippets/csharp/System/Type/GetEvent/Project.csproj create mode 100644 snippets/csharp/System/Type/GetEvents/Program.cs create mode 100644 snippets/csharp/System/Type/GetEvents/Project.csproj create mode 100644 snippets/csharp/System/Type/GetHashCode/Project.csproj create mode 100644 snippets/csharp/System/Type/GetInterface/Project.csproj create mode 100644 snippets/csharp/System/Type/GetInterfaceMap/Project.csproj create mode 100644 snippets/csharp/System/Type/GetMembers/Program.cs create mode 100644 snippets/csharp/System/Type/GetMembers/Project.csproj create mode 100644 snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs create mode 100644 snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj create mode 100644 snippets/csharp/System/Type/GetTypeFromProgID/Program.cs create mode 100644 snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj create mode 100644 snippets/csharp/System/Type/HasElementType/Project.csproj create mode 100644 snippets/csharp/System/Type/IsAssignableFrom/Program.cs create mode 100644 snippets/csharp/System/Type/IsAssignableFrom/Project.csproj create mode 100644 snippets/csharp/System/Type/IsContextful/Project.csproj create mode 100644 snippets/csharp/System/Type/IsGenericType/Program.cs create mode 100644 snippets/csharp/System/Type/IsGenericType/Project.csproj create mode 100644 snippets/csharp/System/Type/Missing/Project.csproj diff --git a/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs b/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs index 4ff74780f6b..ce3d21c98c2 100644 --- a/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs +++ b/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs @@ -7,17 +7,17 @@ public class Example { public static void Main() { - Type t = typeof(String); + Type t = typeof(string); ShowTypeInfo(t); t = typeof(List<>); ShowTypeInfo(t); - var list = new List(); + var list = new List(); t = list.GetType(); ShowTypeInfo(t); - Object v = 12; + object v = 12; t = v.GetType(); ShowTypeInfo(t); diff --git a/snippets/csharp/System/Type/Attributes/attributes1.cs b/snippets/csharp/System/Type/Attributes/attributes1.cs index c76637c5c15..290499fb41e 100644 --- a/snippets/csharp/System/Type/Attributes/attributes1.cs +++ b/snippets/csharp/System/Type/Attributes/attributes1.cs @@ -9,99 +9,99 @@ internal struct S public abstract class Example { - protected sealed class NestedClass {} + protected sealed class NestedClass { } - public interface INested {} + public interface INested { } public static void Main() { // Create an array of types. - Type[] types = { typeof(Example), typeof(NestedClass), - typeof(INested), typeof(S) }; + Type[] types = [typeof(Example), typeof(NestedClass), + typeof(INested), typeof(S)]; - foreach (var t in types) + foreach (var t in types) { - Console.WriteLine("Attributes for type {0}:", t.Name); + Console.WriteLine($"Attributes for type {t.Name}:"); - TypeAttributes attr = t.Attributes; + TypeAttributes attr = t.Attributes; - // To test for visibility attributes, you must use the visibility mask. - TypeAttributes visibility = attr & TypeAttributes.VisibilityMask; - switch (visibility) - { - case TypeAttributes.NotPublic: - Console.WriteLine(" ...is not public"); - break; - case TypeAttributes.Public: - Console.WriteLine(" ...is public"); - break; - case TypeAttributes.NestedPublic: - Console.WriteLine(" ...is nested and public"); - break; - case TypeAttributes.NestedPrivate: - Console.WriteLine(" ...is nested and private"); - break; - case TypeAttributes.NestedFamANDAssem: - Console.WriteLine(" ...is nested, and inheritable only within the assembly" + - "\n (cannot be declared in C#)"); - break; - case TypeAttributes.NestedAssembly: - Console.WriteLine(" ...is nested and internal"); - break; - case TypeAttributes.NestedFamily: - Console.WriteLine(" ...is nested and protected"); - break; - case TypeAttributes.NestedFamORAssem: - Console.WriteLine(" ...is nested and protected internal"); - break; - } + // To test for visibility attributes, you must use the visibility mask. + TypeAttributes visibility = attr & TypeAttributes.VisibilityMask; + switch (visibility) + { + case TypeAttributes.NotPublic: + Console.WriteLine(" ...is not public"); + break; + case TypeAttributes.Public: + Console.WriteLine(" ...is public"); + break; + case TypeAttributes.NestedPublic: + Console.WriteLine(" ...is nested and public"); + break; + case TypeAttributes.NestedPrivate: + Console.WriteLine(" ...is nested and private"); + break; + case TypeAttributes.NestedFamANDAssem: + Console.WriteLine(" ...is nested, and inheritable only within the assembly" + + "\n (cannot be declared in C#)"); + break; + case TypeAttributes.NestedAssembly: + Console.WriteLine(" ...is nested and internal"); + break; + case TypeAttributes.NestedFamily: + Console.WriteLine(" ...is nested and protected"); + break; + case TypeAttributes.NestedFamORAssem: + Console.WriteLine(" ...is nested and protected internal"); + break; + } - // Use the layout mask to test for layout attributes. - TypeAttributes layout = attr & TypeAttributes.LayoutMask; - switch (layout) - { - case TypeAttributes.AutoLayout: - Console.WriteLine(" ...is AutoLayout"); - break; - case TypeAttributes.SequentialLayout: - Console.WriteLine(" ...is SequentialLayout"); - break; - case TypeAttributes.ExplicitLayout: - Console.WriteLine(" ...is ExplicitLayout"); - break; - } + // Use the layout mask to test for layout attributes. + TypeAttributes layout = attr & TypeAttributes.LayoutMask; + switch (layout) + { + case TypeAttributes.AutoLayout: + Console.WriteLine(" ...is AutoLayout"); + break; + case TypeAttributes.SequentialLayout: + Console.WriteLine(" ...is SequentialLayout"); + break; + case TypeAttributes.ExplicitLayout: + Console.WriteLine(" ...is ExplicitLayout"); + break; + } - // Use the class semantics mask to test for class semantics attributes. - TypeAttributes classSemantics = attr & TypeAttributes.ClassSemanticsMask; - switch (classSemantics) - { - case TypeAttributes.Class: - if (t.IsValueType) - { - Console.WriteLine(" ...is a value type"); - } - else - { - Console.WriteLine(" ...is a class"); - } - break; - case TypeAttributes.Interface: - Console.WriteLine(" ...is an interface"); - break; - } + // Use the class semantics mask to test for class semantics attributes. + TypeAttributes classSemantics = attr & TypeAttributes.ClassSemanticsMask; + switch (classSemantics) + { + case TypeAttributes.Class: + if (t.IsValueType) + { + Console.WriteLine(" ...is a value type"); + } + else + { + Console.WriteLine(" ...is a class"); + } + break; + case TypeAttributes.Interface: + Console.WriteLine(" ...is an interface"); + break; + } - if ((attr & TypeAttributes.Abstract) != 0) - { - Console.WriteLine(" ...is abstract"); - } + if ((attr & TypeAttributes.Abstract) != 0) + { + Console.WriteLine(" ...is abstract"); + } - if ((attr & TypeAttributes.Sealed) != 0) - { - Console.WriteLine(" ...is sealed"); - } - - Console.WriteLine(); - } + if ((attr & TypeAttributes.Sealed) != 0) + { + Console.WriteLine(" ...is sealed"); + } + + Console.WriteLine(); + } } } // The example displays the following output: @@ -128,4 +128,4 @@ public static void Main() // ...is SequentialLayout // ...is a value type // ...is sealed -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/BaseType/basetype3.cs b/snippets/csharp/System/Type/BaseType/basetype3.cs index 500bf5b7dd4..6d0aed03f61 100644 --- a/snippets/csharp/System/Type/BaseType/basetype3.cs +++ b/snippets/csharp/System/Type/BaseType/basetype3.cs @@ -3,39 +3,41 @@ public class Example { - public static void Main() - { - foreach (var t in typeof(Example).Assembly.GetTypes()) { - Console.WriteLine("{0} derived from: ", t.FullName); - var derived = t; - do { - derived = derived.BaseType; - if (derived != null) - Console.WriteLine(" {0}", derived.FullName); - } while (derived != null); - Console.WriteLine(); - } - } + public static void Main() + { + foreach (var t in typeof(Example).Assembly.GetTypes()) + { + Console.WriteLine($"{t.FullName} derived from: "); + var derived = t; + do + { + derived = derived.BaseType; + if (derived != null) + Console.WriteLine($" {derived.FullName}"); + } while (derived != null); + Console.WriteLine(); + } + } } -public class A {} +public class A { } public class B : A -{} +{ } -public class C : B -{} +public class C : B +{ } // The example displays the following output: // Example derived from: // System.Object -// +// // A derived from: // System.Object -// +// // B derived from: // A // System.Object -// +// // C derived from: // B // A diff --git a/snippets/csharp/System/Type/BaseType/remarks.cs b/snippets/csharp/System/Type/BaseType/remarks.cs index fbc5b1bee05..252849ac5a5 100644 --- a/snippets/csharp/System/Type/BaseType/remarks.cs +++ b/snippets/csharp/System/Type/BaseType/remarks.cs @@ -1,4 +1,4 @@ -using System; + // class B { } @@ -7,5 +7,5 @@ class C : B { } class ProgStubClass { - public static void Main() {} -} \ No newline at end of file + public static void Main() { } +} diff --git a/snippets/csharp/System/Type/BaseType/testbasetype.cs b/snippets/csharp/System/Type/BaseType/testbasetype.cs index 08e8fc01e5e..f324d83297c 100644 --- a/snippets/csharp/System/Type/BaseType/testbasetype.cs +++ b/snippets/csharp/System/Type/BaseType/testbasetype.cs @@ -5,7 +5,7 @@ class TestType public static void Main() { Type t = typeof(int); - Console.WriteLine("{0} inherits from {1}.", t,t.BaseType); + Console.WriteLine($"{t} inherits from {t.BaseType}."); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/ContainsGenericParameters/source.cs b/snippets/csharp/System/Type/ContainsGenericParameters/source.cs index 065bda276aa..c4d1e611e5c 100644 --- a/snippets/csharp/System/Type/ContainsGenericParameters/source.cs +++ b/snippets/csharp/System/Type/ContainsGenericParameters/source.cs @@ -1,7 +1,7 @@ // using System; -using System.Reflection; -using System.Collections.Generic; + + // Define a base class with two type parameters. public class Base { } @@ -25,10 +25,10 @@ public static void Main() "\r\n--- Display a generic type and the open constructed"); Console.WriteLine(" type from which it is derived."); - // Create a Type object representing the generic type definition + // Create a Type object representing the generic type definition // for the Derived type, by omitting the type argument. (For // types with multiple type parameters, supply the commas but - // omit the type arguments.) + // omit the type arguments.) // Type derivedType = typeof(Derived<>); DisplayGenericTypeInfo(derivedType); @@ -39,16 +39,13 @@ public static void Main() private static void DisplayGenericTypeInfo(Type t) { - Console.WriteLine("\r\n{0}", t); + Console.WriteLine($"\r\n{t}"); - Console.WriteLine("\tIs this a generic type definition? {0}", - t.IsGenericTypeDefinition); + Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"); - Console.WriteLine("\tIs it a generic type? {0}", - t.IsGenericType); + Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}"); - Console.WriteLine("\tDoes it have unassigned generic parameters? {0}", - t.ContainsGenericParameters); + Console.WriteLine($"\tDoes it have unassigned generic parameters? {t.ContainsGenericParameters}"); if (t.IsGenericType) { @@ -56,8 +53,7 @@ private static void DisplayGenericTypeInfo(Type t) // Type[] typeArguments = t.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", - typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { @@ -66,14 +62,11 @@ private static void DisplayGenericTypeInfo(Type t) // if (tParam.IsGenericParameter) { - Console.WriteLine( - "\t\t{0} (unassigned - parameter position {1})", - tParam, - tParam.GenericParameterPosition); + Console.WriteLine($"\t\t{tParam} (unassigned - parameter position {tParam.GenericParameterPosition})"); } else { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } diff --git a/snippets/csharp/System/Type/DeclaringMethod/source.cs b/snippets/csharp/System/Type/DeclaringMethod/source.cs index 486c25baa98..391fd17f392 100644 --- a/snippets/csharp/System/Type/DeclaringMethod/source.cs +++ b/snippets/csharp/System/Type/DeclaringMethod/source.cs @@ -6,10 +6,7 @@ // Define a class with a generic method. public class Example { - public static void Generic(T toDisplay) - { - Console.WriteLine("\r\nHere it is: {0}", toDisplay); - } + public static void Generic(T toDisplay) => Console.WriteLine($"\r\nHere it is: {toDisplay}"); } // @@ -37,7 +34,7 @@ public static void Main() // // Invoke the method. - object[] args = {42}; + object[] args = [42]; miConstructed.Invoke(null, args); // Invoke the method normally. @@ -48,28 +45,24 @@ public static void Main() // and show it's the same as the original definition. // MethodInfo miDef = miConstructed.GetGenericMethodDefinition(); - Console.WriteLine("\r\nThe definition is the same: {0}", - miDef == mi); + Console.WriteLine($"\r\nThe definition is the same: {miDef == mi}"); // } private static void DisplayGenericMethodInfo(MethodInfo mi) { - Console.WriteLine("\r\n{0}", mi); + Console.WriteLine($"\r\n{mi}"); // - Console.WriteLine("\tIs this a generic method definition? {0}", - mi.IsGenericMethodDefinition); + Console.WriteLine($"\tIs this a generic method definition? {mi.IsGenericMethodDefinition}"); // // - Console.WriteLine("\tIs it a generic method? {0}", - mi.IsGenericMethod); + Console.WriteLine($"\tIs it a generic method? {mi.IsGenericMethod}"); // // - Console.WriteLine("\tDoes it have unassigned generic parameters? {0}", - mi.ContainsGenericParameters); + Console.WriteLine($"\tDoes it have unassigned generic parameters? {mi.ContainsGenericParameters}"); // // @@ -79,8 +72,7 @@ private static void DisplayGenericMethodInfo(MethodInfo mi) { Type[] typeArguments = mi.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", - typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { @@ -97,7 +89,7 @@ private static void DisplayGenericMethodInfo(MethodInfo mi) } else { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } diff --git a/snippets/csharp/System/Type/DeclaringType/remarks.cs b/snippets/csharp/System/Type/DeclaringType/remarks.cs index 65cefe2b1d1..8df6af54a2b 100644 --- a/snippets/csharp/System/Type/DeclaringType/remarks.cs +++ b/snippets/csharp/System/Type/DeclaringType/remarks.cs @@ -5,9 +5,9 @@ class ProgStubClass { public static void Main() { -// + // Type t = typeof(List).GetMethod("ConvertAll").GetGenericArguments()[0].DeclaringType; -// - Console.WriteLine("Declaring type: {0:s}", t.FullName); + // + Console.WriteLine($"Declaring type: {t.FullName:s}"); } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Type/DeclaringType/source.cs b/snippets/csharp/System/Type/DeclaringType/source.cs index c89abffcee0..1ed1680ee72 100644 --- a/snippets/csharp/System/Type/DeclaringType/source.cs +++ b/snippets/csharp/System/Type/DeclaringType/source.cs @@ -1,6 +1,6 @@ // using System; -using System.Reflection; + public abstract class dtype { @@ -14,11 +14,7 @@ public abstract class MyClassB : MyClassA { } - public static void Main(string[] args) - { - Console.WriteLine("The declaring type of m is {0}.", - typeof(MyClassB).GetMethod("m").DeclaringType); - } + public static void Main(string[] args) => Console.WriteLine($"The declaring type of m is {typeof(MyClassB).GetMethod("m").DeclaringType}."); } /* The example produces the following output: diff --git a/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs b/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs index cf63b5bcb1d..79837db8991 100644 --- a/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs +++ b/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs @@ -9,23 +9,20 @@ public static void Main() try { Binder defaultBinder = Type.DefaultBinder; - MyClass myClass = new MyClass(); + MyClass myClass = new(); // Invoke the HelloWorld method of MyClass. myClass.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod, - defaultBinder, myClass, new object [] {}); + defaultBinder, myClass, []); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception :" + e.Message); } - } + } class MyClass { - public void HelloWorld() - { - Console.WriteLine("Hello World"); - } + public void HelloWorld() => Console.WriteLine("Hello World"); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/EmptyTypes/Project.csproj b/snippets/csharp/System/Type/EmptyTypes/Project.csproj new file mode 100644 index 00000000000..1eddf5e00ac --- /dev/null +++ b/snippets/csharp/System/Type/EmptyTypes/Project.csproj @@ -0,0 +1,6 @@ + + + Library + net10.0 + + diff --git a/snippets/csharp/System/Type/EmptyTypes/source.cs b/snippets/csharp/System/Type/EmptyTypes/source.cs index 904cf7bd34d..dfe135cac1a 100644 --- a/snippets/csharp/System/Type/EmptyTypes/source.cs +++ b/snippets/csharp/System/Type/EmptyTypes/source.cs @@ -1,15 +1,15 @@ using System; -using System.IO; using System.Reflection; public class Sample { - public void Method(Type type) { + public void Method(Type type) + { ConstructorInfo cInfo; -// -cInfo = type.GetConstructor (BindingFlags.ExactBinding, null, - Type.EmptyTypes, null); -// + // + cInfo = type.GetConstructor(BindingFlags.ExactBinding, null, + Type.EmptyTypes, null); + // } } diff --git a/snippets/csharp/System/Type/Equals/EqualsEx1.cs b/snippets/csharp/System/Type/Equals/EqualsEx1.cs index 6d50d87251a..acb0ad6a5d3 100644 --- a/snippets/csharp/System/Type/Equals/EqualsEx1.cs +++ b/snippets/csharp/System/Type/Equals/EqualsEx1.cs @@ -3,50 +3,49 @@ using System.Collections.Generic; using System.Reflection; -public class Example +public class EqualsEx1Example { - public static void Main() - { - Type t =typeof(int); - Object obj1 = typeof(int).GetTypeInfo(); - IsEqualTo(t, obj1); + public static void Run() + { + Type t = typeof(int); + object obj1 = typeof(int).GetTypeInfo(); + IsEqualTo(t, obj1); - Object obj2 = typeof(String); - IsEqualTo(t, obj2); - - t = typeof(Object); - Object obj3 = typeof(Object); - IsEqualTo(t, obj3); - - t = typeof(List<>); - Object obj4 = (new List()).GetType(); - IsEqualTo(t, obj4); - - t = typeof(Type); - Object obj5 = null; - IsEqualTo(t, obj5); - } - - private static void IsEqualTo(Type t, Object inst) - { - Type t2 = inst as Type; - if (t2 != null) - Console.WriteLine("{0} = {1}: {2}", t.Name, t2.Name, - t.Equals(t2)); - else - Console.WriteLine("Cannot cast the argument to a type."); + object obj2 = typeof(string); + IsEqualTo(t, obj2); - Console.WriteLine(); - } + t = typeof(object); + object obj3 = typeof(object); + IsEqualTo(t, obj3); + + t = typeof(List<>); + object obj4 = (new List()).GetType(); + IsEqualTo(t, obj4); + + t = typeof(Type); + object obj5 = null; + IsEqualTo(t, obj5); + } + + private static void IsEqualTo(Type t, object inst) + { + Type t2 = inst as Type; + if (t2 != null) + Console.WriteLine($"{t.Name} = {t2.Name}: {t.Equals(t2)}"); + else + Console.WriteLine("Cannot cast the argument to a type."); + + Console.WriteLine(); + } } // The example displays the following output: // Int32 = Int32: True -// +// // Int32 = String: False -// +// // Object = Object: True -// +// // List`1 = List`1: False -// +// // Cannot cast the argument to a type. // diff --git a/snippets/csharp/System/Type/Equals/Program.cs b/snippets/csharp/System/Type/Equals/Program.cs new file mode 100644 index 00000000000..eee72699813 --- /dev/null +++ b/snippets/csharp/System/Type/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsEx1Example.Run(); +EqualsSourceExample.Run(); diff --git a/snippets/csharp/System/Type/Equals/Project.csproj b/snippets/csharp/System/Type/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/Equals/source.cs b/snippets/csharp/System/Type/Equals/source.cs index 2e1a1ec3040..e8abbf1e765 100644 --- a/snippets/csharp/System/Type/Equals/source.cs +++ b/snippets/csharp/System/Type/Equals/source.cs @@ -1,32 +1,32 @@ // using System; -using System.Reflection; -class Example + +class EqualsSourceExample { - public static void Main() + public static void Run() { - Type a = typeof(System.String); - Type b = typeof(System.Int32); + Type a = typeof(string); + Type b = typeof(int); - Console.WriteLine("{0} == {1}: {2}", a, b, a.Equals(b)); + Console.WriteLine($"{a} == {b}: {a.Equals(b)}"); // The Type objects in a and b are not equal, // because they represent different types. - a = typeof(Example); - b = new Example().GetType(); + a = typeof(EqualsSourceExample); + b = new EqualsSourceExample().GetType(); - Console.WriteLine("{0} is equal to {1}: {2}", a, b, a.Equals(b)); + Console.WriteLine($"{a} is equal to {b}: {a.Equals(b)}"); // The Type objects in a and b are equal, // because they both represent type Example. b = typeof(Type); - Console.WriteLine("typeof({0}).Equals(typeof({1})): {2}", a, b, a.Equals(b)); + Console.WriteLine($"typeof({a}).Equals(typeof({b})): {a.Equals(b)}"); // The Type objects in a and b are not equal, // because variable a represents type Example @@ -42,4 +42,4 @@ public static void Main() Example is equal to Example: True typeof(Example).Equals(typeof(System.Type)): False */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs b/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs index f2a0fe4c3e0..178b7278b03 100644 --- a/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs +++ b/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs @@ -10,28 +10,28 @@ public static void Main() try { MemberFilter myFilter = Type.FilterAttribute; - Type myType = typeof(System.String); + Type myType = typeof(string); MemberInfo[] myMemberInfoArray = myType.FindMembers(MemberTypes.Constructor - |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | + | MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, myFilter, MethodAttributes.SpecialName); foreach (MemberInfo myMemberinfo in myMemberInfoArray) { - Console.Write ("\n" + myMemberinfo.Name); - Console.Write (" is a " + myMemberinfo.MemberType.ToString()); + Console.Write("\n" + myMemberinfo.Name); + Console.Write(" is a " + myMemberinfo.MemberType); } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.Write("ArgumentNullException : " + e.Message); } - catch(SecurityException e) + catch (SecurityException e) { Console.Write("SecurityException : " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.Write("Exception :" + e.Message); } - } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/FilterName/Project.csproj b/snippets/csharp/System/Type/FilterName/Project.csproj new file mode 100644 index 00000000000..1eddf5e00ac --- /dev/null +++ b/snippets/csharp/System/Type/FilterName/Project.csproj @@ -0,0 +1,6 @@ + + + Library + net10.0 + + diff --git a/snippets/csharp/System/Type/FilterName/source.cs b/snippets/csharp/System/Type/FilterName/source.cs index 350fbe03859..fb3126f09c6 100644 --- a/snippets/csharp/System/Type/FilterName/source.cs +++ b/snippets/csharp/System/Type/FilterName/source.cs @@ -3,22 +3,24 @@ public class Sample { - public void Method() - { -// - // Get the set of methods associated with the type - MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor | - MemberTypes.Method, - BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | - BindingFlags.Instance | BindingFlags.DeclaredOnly, - Type.FilterName, "*"); - Console.WriteLine("Number of methods (includes constructors): " + mi.Length); -// - } + public void Method() + { + // + // Get the set of methods associated with the type + MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor | + MemberTypes.Method, + BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | + BindingFlags.Instance | BindingFlags.DeclaredOnly, + Type.FilterName, "*"); + Console.WriteLine("Number of methods (includes constructors): " + mi.Length); + // + } } // Class added so sample will compile -public class Application { - public void Method() { +public class Application +{ + public void Method() + { } } diff --git a/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs b/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs index 419668f72c1..39d5c5df732 100644 --- a/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs +++ b/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs @@ -7,31 +7,31 @@ public class MyFilterNameIgnoreCaseSample public static void Main() { try - { + { MemberFilter myFilter = Type.FilterNameIgnoreCase; - Type myType = typeof(System.String); + Type myType = typeof(string); MemberInfo[] myMemberinfo1 = myType.FindMembers(MemberTypes.Constructor - |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | + | MemberTypes.Method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, myFilter, "C*"); foreach (MemberInfo myMemberinfo2 in myMemberinfo1) { Console.Write("\n" + myMemberinfo2.Name); MemberTypes Mymembertypes = myMemberinfo2.MemberType; - Console.WriteLine(" is a " + Mymembertypes.ToString()); + Console.WriteLine(" is a " + Mymembertypes); } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.Write("ArgumentNullException : " + e.Message); } - catch(SecurityException e) + catch (SecurityException e) { Console.Write("SecurityException : " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.Write("Exception : " + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs b/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs index bf7c4b78a44..896ac2b0612 100644 --- a/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs +++ b/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs @@ -9,55 +9,51 @@ public static void Main() { try { - XmlDocument myXMLDoc = new XmlDocument(); + XmlDocument myXMLDoc = new(); myXMLDoc.LoadXml("" + "Pride And Prejudice" + ""); Type myType = myXMLDoc.GetType(); // Specify the TypeFilter delegate that compares the // interfaces against filter criteria. - TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); - String[] myInterfaceList = new String[2] - {"System.Collections.IEnumerable", - "System.Collections.ICollection"}; - for(int index=0; index < myInterfaceList.Length; index++) + TypeFilter myFilter = new(MyInterfaceFilter); + string[] myInterfaceList = + ["System.Collections.IEnumerable", + "System.Collections.ICollection"]; + for (int index = 0; index < myInterfaceList.Length; index++) { Type[] myInterfaces = myType.FindInterfaces(myFilter, myInterfaceList[index]); if (myInterfaces.Length > 0) { - Console.WriteLine("\n{0} implements the interface {1}.", - myType, myInterfaceList[index]); - for(int j =0;j < myInterfaces.Length;j++) - Console.WriteLine("Interfaces supported: {0}.", - myInterfaces[j].ToString()); + Console.WriteLine($"\n{myType} implements the interface {myInterfaceList[index]}."); + for (int j = 0; j < myInterfaces.Length; j++) + Console.WriteLine($"Interfaces supported: {myInterfaces[j]}."); } else - Console.WriteLine( - "\n{0} does not implement the interface {1}.", - myType,myInterfaceList[index]); + Console.WriteLine($"\n{myType} does not implement the interface {myInterfaceList[index]}."); } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } - catch(TargetInvocationException e) + catch (TargetInvocationException e) { Console.WriteLine("TargetInvocationException: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } - public static bool MyInterfaceFilter(Type typeObj,Object criteriaObj) + public static bool MyInterfaceFilter(Type typeObj, object criteriaObj) { - if(typeObj.ToString() == criteriaObj.ToString()) + if (typeObj.FullName == criteriaObj as string) return true; else return false; } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/FindMembers/type_findmembers.cs b/snippets/csharp/System/Type/FindMembers/type_findmembers.cs index e0fee47a706..5caae3e13b4 100644 --- a/snippets/csharp/System/Type/FindMembers/type_findmembers.cs +++ b/snippets/csharp/System/Type/FindMembers/type_findmembers.cs @@ -6,29 +6,29 @@ class MyFindMembersClass { public static void Main() { - Object objTest = new Object(); - Type objType = objTest.GetType (); + object objTest = new(); + Type objType = objTest.GetType(); MemberInfo[] arrayMemberInfo; try { //Find all static or public methods in the Object class that match the specified name. arrayMemberInfo = objType.FindMembers(MemberTypes.Method, - BindingFlags.Public | BindingFlags.Static| BindingFlags.Instance, + BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, new MemberFilter(DelegateToSearchCriteria), "ReferenceEquals"); - for(int index=0;index < arrayMemberInfo.Length ;index++) - Console.WriteLine ("Result of FindMembers -\t"+ arrayMemberInfo[index].ToString() +"\n"); + for (int index = 0; index < arrayMemberInfo.Length; index++) + Console.WriteLine("Result of FindMembers -\t" + arrayMemberInfo[index] + "\n"); } catch (Exception e) { - Console.WriteLine ("Exception : " + e.ToString() ); + Console.WriteLine("Exception : " + e); } } - public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object objSearch) + public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, object objSearch) { // Compare the name of the member function with the filter criteria. - if(objMemberInfo.Name.ToString() == objSearch.ToString()) + if (objMemberInfo.Name == objSearch as string) return true; else return false; @@ -38,4 +38,4 @@ public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object obj Result of FindMembers - Boolean ReferenceEquals(System.Object, System.Object) */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/FullName/Fullname3.cs b/snippets/csharp/System/Type/FullName/Fullname3.cs index 3e1a2dcf054..edae78a295d 100644 --- a/snippets/csharp/System/Type/FullName/Fullname3.cs +++ b/snippets/csharp/System/Type/FullName/Fullname3.cs @@ -1,23 +1,25 @@ // using System; -using System.Reflection; -public class Example + +public class FullName3Example { - public static void Main() - { - Type t = typeof(Nullable<>); - Console.WriteLine(t.FullName); - if (t.IsGenericType) { - Console.Write(" Generic Type Parameters: "); - Type[] gtArgs = t.GetGenericArguments(); - for (int ctr = 0; ctr < gtArgs.Length; ctr++) { - Console.WriteLine(gtArgs[ctr].FullName ?? - "(unassigned) " + gtArgs[ctr].ToString()); - } - Console.WriteLine(); - } - } + public static void Run() + { + Type t = typeof(Nullable<>); + Console.WriteLine(t.FullName); + if (t.IsGenericType) + { + Console.Write(" Generic Type Parameters: "); + Type[] gtArgs = t.GetGenericArguments(); + for (int ctr = 0; ctr < gtArgs.Length; ctr++) + { + Console.WriteLine(gtArgs[ctr].FullName ?? + "(unassigned) " + gtArgs[ctr]); + } + Console.WriteLine(); + } + } } // The example displays the following output: // System.Nullable`1 diff --git a/snippets/csharp/System/Type/FullName/Fullname4.cs b/snippets/csharp/System/Type/FullName/Fullname4.cs index 0d349fefccc..759c08a48a0 100644 --- a/snippets/csharp/System/Type/FullName/Fullname4.cs +++ b/snippets/csharp/System/Type/FullName/Fullname4.cs @@ -2,41 +2,38 @@ using System; using System.Reflection; -public class GenericType1 +public class GenericType1 { - public void Display(T[] elements) - {} - - public void HandleT(T obj) - {} - - public bool ChangeValue(ref T arg) - { - return true; - } + public void Display(T[] elements) + { } + + public void HandleT(T obj) + { } + + public bool ChangeValue(ref T arg) => true; } -public class Example +public class FullName4Example { - public static void Main() - { - Type t = typeof(GenericType1<>); - Console.WriteLine("Type Name: {0}", t.FullName); - MethodInfo[] methods = t.GetMethods(BindingFlags.Instance | - BindingFlags.DeclaredOnly | - BindingFlags.Public); - foreach (var method in methods) { - Console.WriteLine(" Method: {0}", method.Name); - // Get method parameters. - ParameterInfo param = method.GetParameters()[0]; - Type paramType = param.ParameterType; - if (method.Name == "HandleT") - paramType = paramType.MakePointerType(); - Console.WriteLine(" Parameter: {0}", - paramType.FullName ?? - paramType.ToString() + " (unassigned)"); - } - } + public static void Run() + { + Type t = typeof(GenericType1<>); + Console.WriteLine($"Type Name: {t.FullName}"); + MethodInfo[] methods = t.GetMethods(BindingFlags.Instance | + BindingFlags.DeclaredOnly | + BindingFlags.Public); + foreach (var method in methods) + { + Console.WriteLine($" Method: {method.Name}"); + // Get method parameters. + ParameterInfo param = method.GetParameters()[0]; + Type paramType = param.ParameterType; + if (method.Name == "HandleT") + paramType = paramType.MakePointerType(); + Console.WriteLine($" Parameter: {paramType.FullName ?? + paramType + " (unassigned)"}"); + } + } } // The example displays the following output: // Type Name: GenericType1`1 diff --git a/snippets/csharp/System/Type/FullName/Fullname5.cs b/snippets/csharp/System/Type/FullName/Fullname5.cs index c2bd57eb565..90538136f52 100644 --- a/snippets/csharp/System/Type/FullName/Fullname5.cs +++ b/snippets/csharp/System/Type/FullName/Fullname5.cs @@ -1,51 +1,43 @@ // using System; -using System.Reflection; + public class Base { } public class Derived : Base { } -public class Example +public class FullName5Example { - public static void Main() - { - Type t = typeof(Derived<>); - Console.WriteLine("Generic Class: {0}", t.FullName); - Console.WriteLine(" Contains Generic Paramters: {0}", - t.ContainsGenericParameters); - Console.WriteLine(" Generic Type Definition: {0}\n", - t.IsGenericTypeDefinition); + public static void Run() + { + Type t = typeof(Derived<>); + Console.WriteLine($"Generic Class: {t.FullName}"); + Console.WriteLine($" Contains Generic Paramters: {t.ContainsGenericParameters}"); + Console.WriteLine($" Generic Type Definition: {t.IsGenericTypeDefinition}\n"); - Type baseType = t.BaseType; - Console.WriteLine("Its Base Class: {0}", - baseType.FullName ?? - "(unassigned) " + baseType.ToString()); - Console.WriteLine(" Contains Generic Paramters: {0}", - baseType.ContainsGenericParameters); - Console.WriteLine(" Generic Type Definition: {0}", - baseType.IsGenericTypeDefinition); - Console.WriteLine(" Full Name: {0}\n", - baseType.GetGenericTypeDefinition().FullName); + Type baseType = t.BaseType; + Console.WriteLine($"Its Base Class: {baseType.FullName ?? + "(unassigned) " + baseType}"); + Console.WriteLine($" Contains Generic Paramters: {baseType.ContainsGenericParameters}"); + Console.WriteLine($" Generic Type Definition: {baseType.IsGenericTypeDefinition}"); + Console.WriteLine($" Full Name: {baseType.GetGenericTypeDefinition().FullName}\n"); - t = typeof(Base<>); - Console.WriteLine("Generic Class: {0}", t.FullName); - Console.WriteLine(" Contains Generic Paramters: {0}", - t.ContainsGenericParameters); - Console.WriteLine(" Generic Type Definition: {0}\n", - t.IsGenericTypeDefinition); - } + t = typeof(Base<>); + Console.WriteLine($"Generic Class: {t.FullName}"); + Console.WriteLine($" Contains Generic Paramters: {t.ContainsGenericParameters}"); + Console.WriteLine($" Generic Type Definition: {t.IsGenericTypeDefinition}\n"); + } } // The example displays the following output: // Generic Class: Derived`1 // Contains Generic Paramters: True // Generic Type Definition: True -// +// // Its Base Class: (unassigned) Base`1[T] // Contains Generic Paramters: True // Generic Type Definition: False // Full Name: Base`1 -// +// // Generic Class: Base`1 // Contains Generic Paramters: True // Generic Type Definition: True diff --git a/snippets/csharp/System/Type/FullName/Program.cs b/snippets/csharp/System/Type/FullName/Program.cs new file mode 100644 index 00000000000..7356154ae2f --- /dev/null +++ b/snippets/csharp/System/Type/FullName/Program.cs @@ -0,0 +1,5 @@ +FullName3Example.Run(); +FullName4Example.Run(); +FullName5Example.Run(); +FullNameEx1Example.Run(); +TestFullName.Run(); diff --git a/snippets/csharp/System/Type/FullName/Project.csproj b/snippets/csharp/System/Type/FullName/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/FullName/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/FullName/fullnameex1.cs b/snippets/csharp/System/Type/FullName/fullnameex1.cs index ef2b91e4e60..612ee255318 100644 --- a/snippets/csharp/System/Type/FullName/fullnameex1.cs +++ b/snippets/csharp/System/Type/FullName/fullnameex1.cs @@ -2,18 +2,18 @@ using System; using System.Collections.Generic; -public class Example +public class FullNameEx1Example { - public static void Main() - { - Type t = typeof(List<>); - Console.WriteLine(t.FullName); - Console.WriteLine(); + public static void Run() + { + Type t = typeof(List<>); + Console.WriteLine(t.FullName); + Console.WriteLine(); - List list = new List(); - t = list.GetType(); - Console.WriteLine(t.FullName); - } + List list = new(); + t = list.GetType(); + Console.WriteLine(t.FullName); + } } // The example displays the following output: // System.Collections.Generic.List`1 diff --git a/snippets/csharp/System/Type/FullName/testfullname.cs b/snippets/csharp/System/Type/FullName/testfullname.cs index cd4311ff848..770a078fd45 100644 --- a/snippets/csharp/System/Type/FullName/testfullname.cs +++ b/snippets/csharp/System/Type/FullName/testfullname.cs @@ -2,10 +2,10 @@ using System; class TestFullName { -public static void Main() + public static void Run() { - Type t = typeof(Array); - Console.WriteLine("The full name of the Array type is {0}.", t.FullName); + Type t = typeof(Array); + Console.WriteLine($"The full name of the Array type is {t.FullName}."); } } @@ -13,4 +13,4 @@ public static void Main() The full name of the Array type is System.Array. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GUID/type_guid.cs b/snippets/csharp/System/Type/GUID/type_guid.cs index 3d8d9ae108f..338f32dcfee 100644 --- a/snippets/csharp/System/Type/GUID/type_guid.cs +++ b/snippets/csharp/System/Type/GUID/type_guid.cs @@ -1,4 +1,4 @@ -// +// using System; class MyGetTypeFromCLSID @@ -14,9 +14,9 @@ public static void Main() // Get the type corresponding to the class MyClass. Type myType = typeof(MyClass1); // Get the object of the Guid. - Guid myGuid =(Guid) myType.GUID; - Console.WriteLine("The name of the class is "+myType.ToString()); - Console.WriteLine("The ClassId of MyClass is "+myType.GUID); + Guid myGuid = (Guid)myType.GUID; + Console.WriteLine("The name of the class is " + myType); + Console.WriteLine("The ClassId of MyClass is " + myType.GUID); } } // diff --git a/snippets/csharp/System/Type/GenericParameterAttributes/source.cs b/snippets/csharp/System/Type/GenericParameterAttributes/source.cs index de9251c2277..a7706371fc2 100644 --- a/snippets/csharp/System/Type/GenericParameterAttributes/source.cs +++ b/snippets/csharp/System/Type/GenericParameterAttributes/source.cs @@ -3,24 +3,25 @@ using System.Reflection; // Define a sample interface to use as an interface constraint. -public interface ITest {} +public interface ITest { } // Define a base type to use as a base class constraint. -public class Base {} +public class Base { } // Define the generic type to examine. The first generic type parameter, // T, derives from the class Base and implements ITest. This demonstrates -// a base class constraint and an interface constraint. The second generic -// type parameter, U, must be a reference type (class) and must have a +// a base class constraint and an interface constraint. The second generic +// type parameter, U, must be a reference type (class) and must have a // default constructor (new()). This demonstrates special constraints. // -public class Test - where T : Base, ITest - where U : class, new() {} +public class Test + where T : Base, ITest + where U : class, new() +{ } // Define a type that derives from Base and implements ITest. This type // satisfies the constraints on T in class Test. -public class Derived : Base, ITest {} +public class Derived : Base, ITest { } public class Example { @@ -28,10 +29,10 @@ public static void Main() { // To get the generic type definition, omit the type // arguments but retain the comma to indicate the number - // of type arguments. + // of type arguments. // Type def = typeof(Test<,>); - Console.WriteLine("\r\nExamining generic type {0}", def); + Console.WriteLine($"\r\nExamining generic type {def}"); // Get the type parameters of the generic type definition, // and display them. @@ -39,30 +40,29 @@ public static void Main() Type[] defparams = def.GetGenericArguments(); foreach (Type tp in defparams) { - Console.WriteLine("\r\nType parameter: {0}", tp.Name); - Console.WriteLine("\t{0}", - ListGenericParameterAttributes(tp)); + Console.WriteLine($"\r\nType parameter: {tp.Name}"); + Console.WriteLine($"\t{ListGenericParameterAttributes(tp)}"); // List the base class and interface constraints. The - // constraints are returned in no particular order. If + // constraints are returned in no particular order. If // there are no class or interface constraints, an empty // array is returned. // Type[] tpConstraints = tp.GetGenericParameterConstraints(); foreach (Type tpc in tpConstraints) { - Console.WriteLine("\t{0}", tpc); + Console.WriteLine($"\t{tpc}"); } } } - // List the variance and special constraint flags. + // List the variance and special constraint flags. // private static string ListGenericParameterAttributes(Type t) { string retval; GenericParameterAttributes gpa = t.GenericParameterAttributes; - GenericParameterAttributes variance = gpa & + GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask; // Select the variance flags. @@ -78,8 +78,8 @@ private static string ListGenericParameterAttributes(Type t) retval = "Contravariant;"; } - // Select - GenericParameterAttributes constraints = gpa & + // Select + GenericParameterAttributes constraints = gpa & GenericParameterAttributes.SpecialConstraintMask; if (constraints == GenericParameterAttributes.None) diff --git a/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs b/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs index 007f013977c..5966452546e 100644 --- a/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs +++ b/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs @@ -1,17 +1,14 @@ -using System; + // public class B { } public class A { - public B GetSomething() - { - return new B(); - } + public B GetSomething() => new B(); } // class ProgStubClass { - public static void Main() {} -} \ No newline at end of file + public static void Main() { } +} diff --git a/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs b/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs index 0048d76a9dc..ce178bbc8e8 100644 --- a/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs +++ b/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs @@ -7,19 +7,19 @@ public static void Main() { try { - int[,,] myArray = new int[,,] {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}}; + int[,,] myArray = new int[,,] { { { 12, 2, 35 }, { 300, 78, 33 } }, { { 92, 42, 135 }, { 30, 7, 3 } } }; Type myType = myArray.GetType(); Console.WriteLine("Contents of myArray: {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}}"); - Console.WriteLine("myArray has {0} dimensions.", myType.GetArrayRank()); + Console.WriteLine($"myArray has {myType.GetArrayRank()} dimensions."); } - catch(NotSupportedException e) + catch (NotSupportedException e) { Console.WriteLine("NotSupportedException raised."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception raised."); Console.WriteLine("Source: " + e.Source); diff --git a/snippets/csharp/System/Type/GetConstructors/Program.cs b/snippets/csharp/System/Type/GetConstructors/Program.cs new file mode 100644 index 00000000000..4c65e4bcd95 --- /dev/null +++ b/snippets/csharp/System/Type/GetConstructors/Program.cs @@ -0,0 +1,2 @@ +ConstructorSample1.Run(); +ConstructorSample2.Run(); diff --git a/snippets/csharp/System/Type/GetConstructors/Project.csproj b/snippets/csharp/System/Type/GetConstructors/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetConstructors/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetConstructors/source1.cs b/snippets/csharp/System/Type/GetConstructors/source1.cs index 64bca042ab6..884433d1674 100644 --- a/snippets/csharp/System/Type/GetConstructors/source1.cs +++ b/snippets/csharp/System/Type/GetConstructors/source1.cs @@ -1,19 +1,21 @@ // - using System; - using System.Reflection; +using System; +using System.Reflection; - public class t { - public t() {} - static t() {} - public t(int i) {} +public class ConstructorSample1 +{ + public ConstructorSample1() { } + static ConstructorSample1() { } + public ConstructorSample1(int i) { } + public static void Run() + { + ConstructorInfo[] p = typeof(ConstructorSample1).GetConstructors(); + Console.WriteLine(p.Length); - public static void Main() { - ConstructorInfo[] p = typeof(t).GetConstructors(); - Console.WriteLine(p.Length); - - for (int i=0;i diff --git a/snippets/csharp/System/Type/GetConstructors/source2.cs b/snippets/csharp/System/Type/GetConstructors/source2.cs index 4a8a66813cd..ebecc5c5ca9 100644 --- a/snippets/csharp/System/Type/GetConstructors/source2.cs +++ b/snippets/csharp/System/Type/GetConstructors/source2.cs @@ -1,21 +1,23 @@ // - using System; - using System.Reflection; +using System; +using System.Reflection; - public class t { - public t() {} - static t() {} - public t(int i) {} +public class ConstructorSample2 +{ + public ConstructorSample2() { } + static ConstructorSample2() { } + public ConstructorSample2(int i) { } + public static void Run() + { + ConstructorInfo[] p = typeof(ConstructorSample2).GetConstructors( + BindingFlags.Public | BindingFlags.Static | + BindingFlags.NonPublic | BindingFlags.Instance); + Console.WriteLine(p.Length); - public static void Main() { - ConstructorInfo[] p = typeof(t).GetConstructors( - BindingFlags.Public | BindingFlags.Static | - BindingFlags.NonPublic | BindingFlags.Instance); - Console.WriteLine(p.Length); - - for (int i=0;i diff --git a/snippets/csharp/System/Type/GetDefaultMembers/source2.cs b/snippets/csharp/System/Type/GetDefaultMembers/source2.cs index e5be6267577..7bc4770e6c5 100644 --- a/snippets/csharp/System/Type/GetDefaultMembers/source2.cs +++ b/snippets/csharp/System/Type/GetDefaultMembers/source2.cs @@ -15,15 +15,9 @@ public Class1() sval = "6040"; } - public int GetIVal() - { - return ival; - } + public int GetIVal() => ival; - public string GetSVal() - { - return sval; - } + public string GetSVal() => sval; } // @@ -32,10 +26,10 @@ public class GetMemberExample public static void Main() { // - Class1 c = new Class1(); + Class1 c = new(); object o; o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, null, c, new object[0]); - Console.WriteLine("Default member result: {0}", o); + Console.WriteLine($"Default member result: {o}"); // GetDefMemberExample1(); @@ -52,9 +46,9 @@ public static void GetDefMemberExample1() (DefaultMemberAttribute)Attribute.GetCustomAttribute((MemberInfo)classType, attribType); MemberInfo[] memInfo = classType.GetMember(defMem.MemberName); // - if ( memInfo.Length > 0) + if (memInfo.Length > 0) { - Console.WriteLine("Default Member: {0}", memInfo[0].Name); + Console.WriteLine($"Default Member: {memInfo[0].Name}"); } } @@ -64,9 +58,9 @@ public static void GetDefMemberExample2() Type t = typeof(Class1); MemberInfo[] memInfo = t.GetDefaultMembers(); // - if ( memInfo.Length > 0) + if (memInfo.Length > 0) { - Console.WriteLine("Default Member: {0}", memInfo[0].Name); + Console.WriteLine($"Default Member: {memInfo[0].Name}"); } } @@ -81,7 +75,7 @@ public static void GetDefMemberExample3() MemberInfo[] memInfo = t.GetMember(defMem.MemberName); if (memInfo.Length > 0) { - Console.WriteLine("Default Member: {0}", memInfo[0].Name); + Console.WriteLine($"Default Member: {memInfo[0].Name}"); } } // diff --git a/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs b/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs index 11ac59b32f6..2d6817171e9 100644 --- a/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs +++ b/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs @@ -6,25 +6,19 @@ [DefaultMemberAttribute("Age")] public class MyClass { - public void Name(String s) {} - public int Age - { - get - { - return 20; - } - } + public void Name(string s) { } + public int Age => 20; public static void Main() { try { - Type myType = typeof(MyClass); + Type myType = typeof(MyClass); MemberInfo[] memberInfoArray = myType.GetDefaultMembers(); if (memberInfoArray.Length > 0) { - foreach(MemberInfo memberInfoObj in memberInfoArray) + foreach (MemberInfo memberInfoObj in memberInfoArray) { - Console.WriteLine("The default member name is: " + memberInfoObj.ToString()); + Console.WriteLine("The default member name is: " + memberInfoObj); } } else @@ -32,18 +26,18 @@ public static void Main() Console.WriteLine("No default members are available."); } } - catch(InvalidOperationException e) + catch (InvalidOperationException e) { Console.WriteLine("InvalidOperationException: " + e.Message); } - catch(IOException e) + catch (IOException e) { Console.WriteLine("IOException: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs b/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs index fa98300952f..acc79ca852e 100644 --- a/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs +++ b/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs @@ -4,14 +4,14 @@ class TestGetElementType { public static void Main() { - int[] array = {1,2,3}; + int[] array = [1, 2, 3]; Type t = array.GetType(); Type t2 = t.GetElementType(); - Console.WriteLine("The element type of {0} is {1}.",array, t2.ToString()); - TestGetElementType newMe = new TestGetElementType(); + Console.WriteLine($"The element type of {array} is {t2}."); + TestGetElementType newMe = new(); t = newMe.GetType(); t2 = t.GetElementType(); - Console.WriteLine("The element type of {0} is {1}.", newMe, t2==null? "null" : t2.ToString()); + Console.WriteLine($"The element type of {newMe} is {(t2 == null ? "null" : t2.ToString())}."); } } @@ -20,4 +20,4 @@ public static void Main() The element type of System.Int32[] is System.Int32. The element type of TestGetElementType is null. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetEvent/Program.cs b/snippets/csharp/System/Type/GetEvent/Program.cs new file mode 100644 index 00000000000..d36c4a66d43 --- /dev/null +++ b/snippets/csharp/System/Type/GetEvent/Program.cs @@ -0,0 +1,2 @@ +EventExample.Run(); +EventExample1.Run(); diff --git a/snippets/csharp/System/Type/GetEvent/Project.csproj b/snippets/csharp/System/Type/GetEvent/Project.csproj new file mode 100644 index 00000000000..1ef5ac9aa71 --- /dev/null +++ b/snippets/csharp/System/Type/GetEvent/Project.csproj @@ -0,0 +1,7 @@ + + + Exe + net10.0-windows + true + + diff --git a/snippets/csharp/System/Type/GetEvent/type_getevent.cs b/snippets/csharp/System/Type/GetEvent/type_getevent.cs index 159dad978ab..a9a65b4ef60 100644 --- a/snippets/csharp/System/Type/GetEvent/type_getevent.cs +++ b/snippets/csharp/System/Type/GetEvent/type_getevent.cs @@ -3,38 +3,38 @@ using System.Reflection; using System.Security; -class MyEventExample +class EventExample { - public static void Main() + public static void Run() { try { Type myType = typeof(System.Windows.Forms.Button); EventInfo myEvent = myType.GetEvent("Click"); - if(myEvent != null) + if (myEvent != null) { Console.WriteLine("Looking for the Click event in the Button class."); - Console.WriteLine(myEvent.ToString()); + Console.WriteLine(myEvent); } else { Console.WriteLine("The Click event is not available in the Button class."); } } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message :"+e.Message); + Console.WriteLine("Message :" + e.Message); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message :"+e.Message); + Console.WriteLine("Message :" + e.Message); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("The following exception was raised : {0}",e.Message); + Console.WriteLine($"The following exception was raised : {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/GetEvent/type_getevent1.cs b/snippets/csharp/System/Type/GetEvent/type_getevent1.cs index 336fb59f405..b15ee9b115d 100644 --- a/snippets/csharp/System/Type/GetEvent/type_getevent1.cs +++ b/snippets/csharp/System/Type/GetEvent/type_getevent1.cs @@ -3,9 +3,9 @@ using System.Reflection; using System.Security; -class MyEventExample +class EventExample1 { - public static void Main() + public static void Run() { try { @@ -14,29 +14,29 @@ public static void Main() BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; Type myTypeBindingFlags = typeof(System.Windows.Forms.Button); EventInfo myEventBindingFlags = myTypeBindingFlags.GetEvent("Click", myBindingFlags); - if(myEventBindingFlags != null) + if (myEventBindingFlags != null) { Console.WriteLine("Looking for the Click event in the Button class with the specified BindingFlags."); - Console.WriteLine(myEventBindingFlags.ToString()); + Console.WriteLine(myEventBindingFlags); } else { Console.WriteLine("The Click event is not available with the Button class."); } } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message :"+e.Message); + Console.WriteLine("Message :" + e.Message); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message :"+e.Message); + Console.WriteLine("Message :" + e.Message); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("The following exception was raised : {0}",e.Message); + Console.WriteLine($"The following exception was raised : {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/GetEvents/Program.cs b/snippets/csharp/System/Type/GetEvents/Program.cs new file mode 100644 index 00000000000..25e38f87f7b --- /dev/null +++ b/snippets/csharp/System/Type/GetEvents/Program.cs @@ -0,0 +1,2 @@ +EventsSample1.Run(); +EventsSample2.Run(); diff --git a/snippets/csharp/System/Type/GetEvents/Project.csproj b/snippets/csharp/System/Type/GetEvents/Project.csproj new file mode 100644 index 00000000000..1ef5ac9aa71 --- /dev/null +++ b/snippets/csharp/System/Type/GetEvents/Project.csproj @@ -0,0 +1,7 @@ + + + Exe + net10.0-windows + true + + diff --git a/snippets/csharp/System/Type/GetEvents/type_getevents1.cs b/snippets/csharp/System/Type/GetEvents/type_getevents1.cs index 35382b881ce..0ef51c21f60 100644 --- a/snippets/csharp/System/Type/GetEvents/type_getevents1.cs +++ b/snippets/csharp/System/Type/GetEvents/type_getevents1.cs @@ -3,9 +3,9 @@ using System.Reflection; using System.Security; -class EventsSample +class EventsSample1 { - public static void Main() + public static void Run() { try { @@ -16,21 +16,21 @@ public static void Main() Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are : "); for (int index = 0; index < myEventsBindingFlags.Length; index++) { - Console.WriteLine(myEventsBindingFlags[index].ToString()); + Console.WriteLine(myEventsBindingFlags[index]); } } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("SecurityException :" + e.Message); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException : " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception : " + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetEvents/type_getevents2.cs b/snippets/csharp/System/Type/GetEvents/type_getevents2.cs index 3ab6230ee4f..741a70c984b 100644 --- a/snippets/csharp/System/Type/GetEvents/type_getevents2.cs +++ b/snippets/csharp/System/Type/GetEvents/type_getevents2.cs @@ -3,9 +3,9 @@ using System.Reflection; using System.Security; -class EventsSample +class EventsSample2 { - public static void Main() + public static void Run() { try { @@ -16,21 +16,21 @@ public static void Main() Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are:"); for (int index = 0; index < myEventsBindingFlags.Length; index++) { - Console.WriteLine(myEventsBindingFlags[index].ToString()); + Console.WriteLine(myEventsBindingFlags[index]); } } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("SecurityException:" + e.Message); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetField/type_getfield.cs b/snippets/csharp/System/Type/GetField/type_getfield.cs index fcd7cc1a842..8af2e2b7908 100644 --- a/snippets/csharp/System/Type/GetField/type_getfield.cs +++ b/snippets/csharp/System/Type/GetField/type_getfield.cs @@ -14,15 +14,12 @@ public class MyFieldClassB private string field = "B Field"; public string Field { - get - { - return field; - } + get => field; set { - if (field!=value) + if (field != value) { - field=value; + field = value; } } } @@ -32,8 +29,8 @@ public class MyFieldInfoClass { public static void Main() { - MyFieldClassB myFieldObjectB = new MyFieldClassB(); - MyFieldClassA myFieldObjectA = new MyFieldClassA(); + MyFieldClassB myFieldObjectB = new(); + MyFieldClassA myFieldObjectA = new(); Type myTypeA = typeof(MyFieldClassA); FieldInfo myFieldInfo = myTypeA.GetField("Field"); @@ -42,10 +39,8 @@ public static void Main() FieldInfo myFieldInfo1 = myTypeB.GetField("field", BindingFlags.NonPublic | BindingFlags.Instance); - Console.WriteLine("The value of the public field is: '{0}'", - myFieldInfo.GetValue(myFieldObjectA)); - Console.WriteLine("The value of the private field is: '{0}'", - myFieldInfo1.GetValue(myFieldObjectB)); + Console.WriteLine($"The value of the public field is: '{myFieldInfo.GetValue(myFieldObjectA)}'"); + Console.WriteLine($"The value of the private field is: '{myFieldInfo1.GetValue(myFieldObjectB)}'"); } } // diff --git a/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs b/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs index 7b01efe830f..577256cc55a 100644 --- a/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs +++ b/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs @@ -16,20 +16,19 @@ public static void Main() FieldInfo[] myField = myType.GetFields(); Console.WriteLine("\nDisplaying fields that have SpecialName attributes:\n"); - for(int i = 0; i < myField.Length; i++) + for (int i = 0; i < myField.Length; i++) { // Determine whether or not each field is a special name. - if(myField[i].IsSpecialName) + if (myField[i].IsSpecialName) { - Console.WriteLine("The field {0} has a SpecialName attribute.", - myField[i].Name); + Console.WriteLine($"The field {myField[i].Name} has a SpecialName attribute."); } } } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("Exception : {0} " , e.Message); + Console.WriteLine($"Exception : {e.Message} "); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetFields/source.cs b/snippets/csharp/System/Type/GetFields/source.cs index bc3aefc9d1d..b0af8444d62 100644 --- a/snippets/csharp/System/Type/GetFields/source.cs +++ b/snippets/csharp/System/Type/GetFields/source.cs @@ -1,18 +1,15 @@ -// +// using System; using System.Reflection; class AttributesSample { - public void Mymethod (int int1m, out string str2m, ref string str3m) - { - str2m = "in Mymethod"; - } + public void Mymethod(int int1m, out string str2m, ref string str3m) => str2m = "in Mymethod"; public static int Main(string[] args) { - Console.WriteLine ("Reflection.MethodBase.Attributes Sample"); + Console.WriteLine("Reflection.MethodBase.Attributes Sample"); // Get the type. Type MyType = Type.GetType("AttributesSample"); @@ -27,7 +24,7 @@ public static int Main(string[] args) MethodAttributes Myattributes = Mymethodbase.Attributes; // Display the flags that are set. - PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes); + PrintAttributes(typeof(System.Reflection.MethodAttributes), (int)Myattributes); return 0; } diff --git a/snippets/csharp/System/Type/GetGenericArguments/source.cs b/snippets/csharp/System/Type/GetGenericArguments/source.cs index aff8b688c19..b129230bb08 100644 --- a/snippets/csharp/System/Type/GetGenericArguments/source.cs +++ b/snippets/csharp/System/Type/GetGenericArguments/source.cs @@ -1,19 +1,17 @@ // using System; -using System.Reflection; + using System.Collections.Generic; public class Test { private static void DisplayGenericTypeInfo(Type t) { - Console.WriteLine("\r\n{0}", t); + Console.WriteLine($"\r\n{t}"); - Console.WriteLine("\tIs this a generic type definition? {0}", - t.IsGenericTypeDefinition); + Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"); - Console.WriteLine("\tIs it a generic type? {0}", - t.IsGenericType); + Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}"); // if (t.IsGenericType) @@ -22,8 +20,7 @@ private static void DisplayGenericTypeInfo(Type t) // Type[] typeArguments = t.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", - typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { @@ -32,13 +29,11 @@ private static void DisplayGenericTypeInfo(Type t) // if (tParam.IsGenericParameter) { - Console.WriteLine("\t\t{0}\t(unassigned - parameter position {1})", - tParam, - tParam.GenericParameterPosition); + Console.WriteLine($"\t\t{tParam}\t(unassigned - parameter position {tParam.GenericParameterPosition})"); } else { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } @@ -51,8 +46,8 @@ public static void Main() Console.WriteLine(" generic type definition, and an ordinary type."); // Create a Dictionary of Test objects, using strings for the - // keys. - Dictionary d = new Dictionary(); + // keys. + Dictionary d = new(); // Display information for the constructed type and its generic // type definition. diff --git a/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs b/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs index cb7b7df42ce..98438f97aba 100644 --- a/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs +++ b/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs @@ -1,6 +1,6 @@ // using System; -using System.Reflection; + using System.Collections.Generic; public class Test @@ -10,8 +10,8 @@ public static void Main() Console.WriteLine("\r\n--- Get the generic type that defines a constructed type."); // Create a Dictionary of Test objects, using strings for the - // keys. - Dictionary d = new Dictionary(); + // keys. + Dictionary d = new(); // Get a Type object representing the constructed type. // @@ -24,16 +24,14 @@ public static void Main() private static void DisplayTypeInfo(Type t) { - Console.WriteLine("\r\n{0}", t); - Console.WriteLine("\tIs this a generic type definition? {0}", - t.IsGenericTypeDefinition); - Console.WriteLine("\tIs it a generic type? {0}", - t.IsGenericType); + Console.WriteLine($"\r\n{t}"); + Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"); + Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}"); Type[] typeArguments = t.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } diff --git a/snippets/csharp/System/Type/GetHashCode/Project.csproj b/snippets/csharp/System/Type/GetHashCode/Project.csproj new file mode 100644 index 00000000000..1ef5ac9aa71 --- /dev/null +++ b/snippets/csharp/System/Type/GetHashCode/Project.csproj @@ -0,0 +1,7 @@ + + + Exe + net10.0-windows + true + + diff --git a/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs b/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs index 779f730e297..9dd0048525b 100644 --- a/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs +++ b/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs @@ -5,37 +5,36 @@ class FieldsSample { - public static void Main() + public static void Main() { Type myType = typeof(System.Net.IPAddress); - FieldInfo [] myFields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic); - Console.WriteLine ("\nThe IPAddress class has the following nonpublic fields: "); + FieldInfo[] myFields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic); + Console.WriteLine("\nThe IPAddress class has the following nonpublic fields: "); foreach (FieldInfo myField in myFields) { - Console.WriteLine(myField.ToString()); + Console.WriteLine(myField); } Type myType1 = typeof(System.Net.IPAddress); - FieldInfo [] myFields1 = myType1.GetFields(); - Console.WriteLine ("\nThe IPAddress class has the following public fields: "); + FieldInfo[] myFields1 = myType1.GetFields(); + Console.WriteLine("\nThe IPAddress class has the following public fields: "); foreach (FieldInfo myField in myFields1) { - Console.WriteLine(myField.ToString()); + Console.WriteLine(myField); } try { - Console.WriteLine("The HashCode of the System.Windows.Forms.Button type is: {0}", - typeof(System.Windows.Forms.Button).GetHashCode()); - } - catch(SecurityException e) + Console.WriteLine($"The HashCode of the System.Windows.Forms.Button type is: {typeof(System.Windows.Forms.Button).GetHashCode()}"); + } + catch (SecurityException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message: "+e.Message); + Console.WriteLine("Message: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Message: "+e.Message); - } + Console.WriteLine("Message: " + e.Message); + } } -} +} // diff --git a/snippets/csharp/System/Type/GetInterface/Project.csproj b/snippets/csharp/System/Type/GetInterface/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetInterface/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetInterface/type_getinterface.cs b/snippets/csharp/System/Type/GetInterface/type_getinterface.cs index 010de7d835e..72060d5ddd9 100644 --- a/snippets/csharp/System/Type/GetInterface/type_getinterface.cs +++ b/snippets/csharp/System/Type/GetInterface/type_getinterface.cs @@ -13,42 +13,42 @@ with the specified name. Then prints the method name of that interface. class MyInterfaceClass { -// -// -// + // + // + // public static void Main() { - Hashtable hashtableObj = new Hashtable(); + Hashtable hashtableObj = new(); Type objType = hashtableObj.GetType(); MethodInfo[] arrayMethodInfo; MemberInfo[] arrayMemberInfo; try { // Get the methods implemented in 'IDeserializationCallback' interface. - arrayMethodInfo =objType.GetInterface("IDeserializationCallback").GetMethods(); - Console.WriteLine ("\nMethods of 'IDeserializationCallback' Interface :"); - foreach(MethodInfo methodInfo in arrayMethodInfo) - Console.WriteLine (methodInfo); + arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods(); + Console.WriteLine("\nMethods of 'IDeserializationCallback' Interface :"); + foreach (MethodInfo methodInfo in arrayMethodInfo) + Console.WriteLine(methodInfo); // Get FullName for interface by using Ignore case search. - Console.WriteLine ("\nMethods of 'IEnumerable' Interface"); - arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods(); - foreach(MethodInfo methodInfo in arrayMethodInfo) - Console.WriteLine (methodInfo); + Console.WriteLine("\nMethods of 'IEnumerable' Interface"); + arrayMethodInfo = objType.GetInterface("ienumerable", true).GetMethods(); + foreach (MethodInfo methodInfo in arrayMethodInfo) + Console.WriteLine(methodInfo); //Get the Interface methods for 'IDictionary' interface - InterfaceMapping interfaceMappingOb = objType.GetInterfaceMap(typeof(IDictionary)); + InterfaceMapping interfaceMappingObj = objType.GetInterfaceMap(typeof(IDictionary)); arrayMemberInfo = interfaceMappingObj.InterfaceMethods; - Console.WriteLine ("\nHashtable class Implements the following IDictionary Interface methods :"); - foreach(MemberInfo memberInfo in arrayMemberInfo) - Console.WriteLine (memberInfo); + Console.WriteLine("\nHashtable class Implements the following IDictionary Interface methods :"); + foreach (MemberInfo memberInfo in arrayMemberInfo) + Console.WriteLine(memberInfo); } catch (Exception e) { - Console.WriteLine ("Exception : " + e.ToString()); + Console.WriteLine("Exception : " + e); } } -// -// -// + // + // + // } diff --git a/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj b/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs b/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs index 1ce9ac58388..aa607622e13 100644 --- a/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs +++ b/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs @@ -5,50 +5,32 @@ public class Example { - public static void Main() - { - Type[] interf = { typeof(IFormatProvider), typeof(IAppDomainSetup) }; - Type[] impl = { typeof(CultureInfo), typeof(AppDomainSetup) }; + public static void Main() + { + Type[] interf = [typeof(IFormatProvider), typeof(IFormattable)]; + Type[] impl = [typeof(CultureInfo), typeof(DateTime)]; - for (int ctr = 0; ctr < interf.Length; ctr++) - ShowInterfaceMapping(interf[ctr], impl[ctr]); - } + for (int ctr = 0; ctr < interf.Length; ctr++) + ShowInterfaceMapping(interf[ctr], impl[ctr]); + } - private static void ShowInterfaceMapping(Type intType, Type implType) - { - InterfaceMapping map = implType.GetInterfaceMap(intType); - Console.WriteLine("Mapping of {0} to {1}: ", map.InterfaceType, map.TargetType); - for (int ctr = 0; ctr < map.InterfaceMethods.Length; ctr++) { - MethodInfo im = map.InterfaceMethods[ctr]; - MethodInfo tm = map.TargetMethods[ctr]; - Console.WriteLine(" {0} --> {1}", im.Name,tm.Name); - } - Console.WriteLine(); - } + private static void ShowInterfaceMapping(Type intType, Type implType) + { + InterfaceMapping map = implType.GetInterfaceMap(intType); + Console.WriteLine($"Mapping of {map.InterfaceType} to {map.TargetType}: "); + for (int ctr = 0; ctr < map.InterfaceMethods.Length; ctr++) + { + MethodInfo im = map.InterfaceMethods[ctr]; + MethodInfo tm = map.TargetMethods[ctr]; + Console.WriteLine($" {im.Name} --> {tm.Name}"); + } + Console.WriteLine(); + } } // The example displays the following output: // Mapping of System.IFormatProvider to System.Globalization.CultureInfo: // GetFormat --> GetFormat // -// Mapping of System.IAppDomainSetup to System.AppDomainSetup: -// get_ApplicationBase --> get_ApplicationBase -// set_ApplicationBase --> set_ApplicationBase -// get_ApplicationName --> get_ApplicationName -// set_ApplicationName --> set_ApplicationName -// get_CachePath --> get_CachePath -// set_CachePath --> set_CachePath -// get_ConfigurationFile --> get_ConfigurationFile -// set_ConfigurationFile --> set_ConfigurationFile -// get_DynamicBase --> get_DynamicBase -// set_DynamicBase --> set_DynamicBase -// get_LicenseFile --> get_LicenseFile -// set_LicenseFile --> set_LicenseFile -// get_PrivateBinPath --> get_PrivateBinPath -// set_PrivateBinPath --> set_PrivateBinPath -// get_PrivateBinPathProbe --> get_PrivateBinPathProbe -// set_PrivateBinPathProbe --> set_PrivateBinPathProbe -// get_ShadowCopyDirectories --> get_ShadowCopyDirectories -// set_ShadowCopyDirectories --> set_ShadowCopyDirectories -// get_ShadowCopyFiles --> get_ShadowCopyFiles -// set_ShadowCopyFiles --> set_ShadowCopyFiles +// Mapping of System.IFormattable to System.DateTime: +// ToString --> ToString // diff --git a/snippets/csharp/System/Type/GetMember/type_getmember.cs b/snippets/csharp/System/Type/GetMember/type_getmember.cs index 745de08fe85..e9df7340968 100644 --- a/snippets/csharp/System/Type/GetMember/type_getmember.cs +++ b/snippets/csharp/System/Type/GetMember/type_getmember.cs @@ -8,32 +8,32 @@ public class MyMemberSample { public static void Main() { - MyMemberSample myClass = new MyMemberSample(); + MyMemberSample myClass = new(); try { myClass.GetMemberInfo(); - myClass.GetPublicStaticMemberInfo(); - myClass.GetPublicInstanceMethodMemberInfo(); + myClass.GetPublicStaticMemberInfo(); + myClass.GetPublicInstanceMethodMemberInfo(); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException occurred."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } - catch(NotSupportedException e) + catch (NotSupportedException e) { Console.WriteLine("NotSupportedException occurred."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("SecurityException occurred."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception occurred."); Console.WriteLine("Source: " + e.Source); @@ -43,16 +43,16 @@ public static void Main() public void GetMemberInfo() { - String myString = "GetMember_String"; + string myString = "GetMember_String"; Type myType = myString.GetType(); // Get the members for myString starting with the letter C. MemberInfo[] myMembers = myType.GetMember("C*"); - if(myMembers.Length > 0) + if (myMembers.Length > 0) { - Console.WriteLine("\nThe member(s) starting with the letter C for type {0}:", myType); - for(int index=0; index < myMembers.Length; index++) - Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString()); + Console.WriteLine($"\nThe member(s) starting with the letter C for type {myType}:"); + for (int index = 0; index < myMembers.Length; index++) + Console.WriteLine($"Member {index + 1}: {myMembers[index]}"); } else { @@ -64,16 +64,16 @@ public void GetMemberInfo() // public void GetPublicStaticMemberInfo() { - String myString = "GetMember_String_BindingFlag"; + string myString = "GetMember_String_BindingFlag"; Type myType = myString.GetType(); // Get the public static members for the class myString starting with the letter C. MemberInfo[] myMembers = myType.GetMember("C*", - BindingFlags.Public |BindingFlags.Static); - if(myMembers.Length > 0) + BindingFlags.Public | BindingFlags.Static); + if (myMembers.Length > 0) { - Console.WriteLine("\nThe public static member(s) starting with the letter C for type {0}:", myType); - for(int index=0; index < myMembers.Length; index++) - Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString()); + Console.WriteLine($"\nThe public static member(s) starting with the letter C for type {myType}:"); + for (int index = 0; index < myMembers.Length; index++) + Console.WriteLine($"Member {index + 1}: {myMembers[index]}"); } else { @@ -85,16 +85,16 @@ public void GetPublicStaticMemberInfo() // public void GetPublicInstanceMethodMemberInfo() { - String myString = "GetMember_String_MemberType_BindingFlag"; + string myString = "GetMember_String_MemberType_BindingFlag"; Type myType = myString.GetType(); // Get the public instance methods for myString starting with the letter C. MemberInfo[] myMembers = myType.GetMember("C*", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); - if(myMembers.Length > 0) + if (myMembers.Length > 0) { - Console.WriteLine("\nThe public instance method(s) starting with the letter C for type {0}:", myType); - for(int index=0; index < myMembers.Length; index++) - Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString()); + Console.WriteLine($"\nThe public instance method(s) starting with the letter C for type {myType}:"); + for (int index = 0; index < myMembers.Length; index++) + Console.WriteLine($"Member {index + 1}: {myMembers[index]}"); } else { @@ -102,4 +102,4 @@ public void GetPublicInstanceMethodMemberInfo() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetMembers/Program.cs b/snippets/csharp/System/Type/GetMembers/Program.cs new file mode 100644 index 00000000000..5407163430d --- /dev/null +++ b/snippets/csharp/System/Type/GetMembers/Program.cs @@ -0,0 +1,2 @@ +Type_GetMembers.Run(); +Type_GetMembers_BindingFlags.Run(); diff --git a/snippets/csharp/System/Type/GetMembers/Project.csproj b/snippets/csharp/System/Type/GetMembers/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetMembers/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs b/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs index 370d3130ecb..f95358629b9 100644 --- a/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs +++ b/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs @@ -11,45 +11,45 @@ of the class 'MyClass' and displays the same to the console. using System.Security; // -class MyClass +class MembersSampleClass { - public int myInt = 0; - public string myString = null; - - public MyClass() - { - } - public void Myfunction() - { - } + public int myInt = 0; + public string myString = null; + + public MembersSampleClass() + { + } + public void Myfunction() + { + } } class Type_GetMembers { - public static void Main() - { - try - { - MyClass myObject = new MyClass(); - MemberInfo[] myMemberInfo; - - // Get the type of 'MyClass'. - Type myType = myObject.GetType(); - - // Get the information related to all public member's of 'MyClass'. - myMemberInfo = myType.GetMembers(); - - Console.WriteLine( "\nThe members of class '{0}' are :\n", myType); - for (int i =0 ; i < myMemberInfo.Length ; i++) - { - // Display name and type of the concerned member. - Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType); - } - } - catch(SecurityException e) - { - Console.WriteLine("Exception : " + e.Message ); - } - } + public static void Run() + { + try + { + MembersSampleClass myObject = new(); + MemberInfo[] myMemberInfo; + + // Get the type of 'MyClass'. + Type myType = myObject.GetType(); + + // Get the information related to all public member's of 'MyClass'. + myMemberInfo = myType.GetMembers(); + + Console.WriteLine($"\nThe members of class '{myType}' are :\n"); + for (int i = 0; i < myMemberInfo.Length; i++) + { + // Display name and type of the concerned member. + Console.WriteLine($"'{myMemberInfo[i].Name}' is a {myMemberInfo[i].MemberType}"); + } + } + catch (SecurityException e) + { + Console.WriteLine("Exception : " + e.Message); + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs b/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs index 5c51ce13c01..7f941571765 100644 --- a/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs +++ b/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs @@ -13,58 +13,58 @@ the console. // -class MyClass +class MembersBindingFlagsSampleClass { - public int myInt = 0; - public string myString = null; + public int myInt = 0; + public string myString = null; - public MyClass() - { - } - public void Myfunction() - { - } + public MembersBindingFlagsSampleClass() + { + } + public void Myfunction() + { + } } class Type_GetMembers_BindingFlags { - public static void Main() - { - try - { - MyClass MyObject = new MyClass(); - MemberInfo [] myMemberInfo; + public static void Run() + { + try + { + MembersBindingFlagsSampleClass MyObject = new(); + MemberInfo[] myMemberInfo; - // Get the type of the class 'MyClass'. - Type myType = MyObject.GetType(); + // Get the type of the class 'MyClass'. + Type myType = MyObject.GetType(); - // Get the public instance members of the class 'MyClass'. - myMemberInfo = myType.GetMembers(BindingFlags.Public|BindingFlags.Instance); + // Get the public instance members of the class 'MyClass'. + myMemberInfo = myType.GetMembers(BindingFlags.Public | BindingFlags.Instance); - Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", myType); - for (int i =0 ; i < myMemberInfo.Length ; i++) - { - // Display name and type of the member of 'MyClass'. - Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType); - } - } - catch (SecurityException e) - { - Console.WriteLine("SecurityException : " + e.Message ); - } + Console.WriteLine($"\nThe public instance members of class '{myType}' are : \n"); + for (int i = 0; i < myMemberInfo.Length; i++) + { + // Display name and type of the member of 'MyClass'. + Console.WriteLine($"'{myMemberInfo[i].Name}' is a {myMemberInfo[i].MemberType}"); + } + } + catch (SecurityException e) + { + Console.WriteLine("SecurityException : " + e.Message); + } - //Output: - //The public instance members of class 'MyClass' are : + //Output: + //The public instance members of class 'MyClass' are : - //'Myfunction' is a Method - //'ToString' is a Method - //'Equals' is a Method - //'GetHashCode' is a Method - //'GetType' is a Method - //'.ctor' is a Constructor - //'myInt' is a Field - //'myString' is a Field - } + //'Myfunction' is a Method + //'ToString' is a Method + //'Equals' is a Method + //'GetHashCode' is a Method + //'GetType' is a Method + //'.ctor' is a Constructor + //'myInt' is a Field + //'myString' is a Field + } } // diff --git a/snippets/csharp/System/Type/GetMethod/GetMethod1.cs b/snippets/csharp/System/Type/GetMethod/GetMethod1.cs index f1fea4624d6..2dba736e77e 100644 --- a/snippets/csharp/System/Type/GetMethod/GetMethod1.cs +++ b/snippets/csharp/System/Type/GetMethod/GetMethod1.cs @@ -6,53 +6,55 @@ public class Example { - public static void Main() - { - // Get a Type object that represents a non-generic type. - GetAddMethod(typeof(ArrayList)); + public static void Main() + { + // Get a Type object that represents a non-generic type. + GetAddMethod(typeof(ArrayList)); - var list = new List(); - // Get a Type object that represents a constructed generic type. - Type closed = list.GetType(); - GetAddMethod(closed); - - // Get a Type object that represents an open generic type. - Type open = typeof(List<>); - GetAddMethod(open); - } + var list = new List(); + // Get a Type object that represents a constructed generic type. + Type closed = list.GetType(); + GetAddMethod(closed); - private static void GetAddMethod(Type typ) - { - MethodInfo method; - // Determine if this is a generic type. - if (typ.IsGenericType) { - // Is it an open generic type? - if (typ.ContainsGenericParameters) - method = typ.GetMethod("Add", typ.GetGenericArguments()); - // Get closed generic type arguments. - else - method = typ.GetMethod("Add", typ.GenericTypeArguments); - } - // This is not a generic type. - else { - method = typ.GetMethod("Add", new Type[] { typeof(Object) } ); - } + // Get a Type object that represents an open generic type. + Type open = typeof(List<>); + GetAddMethod(open); + } - // Test if an Add method was found. - if (method == null) { - Console.WriteLine("No Add method found."); - return; - } - - Type t = method.ReflectedType; - Console.Write("{0}.{1}.{2}(", t.Namespace, t.Name, method.Name); - ParameterInfo[] parms = method.GetParameters(); - for (int ctr = 0; ctr < parms.Length; ctr++) - Console.Write("{0}{1}", parms[ctr].ParameterType.Name, - ctr < parms.Length - 1 ? ", " : ""); + private static void GetAddMethod(Type typ) + { + MethodInfo method; + // Determine if this is a generic type. + if (typ.IsGenericType) + { + // Is it an open generic type? + if (typ.ContainsGenericParameters) + method = typ.GetMethod("Add", typ.GetGenericArguments()); + // Get closed generic type arguments. + else + method = typ.GetMethod("Add", typ.GenericTypeArguments); + } + // This is not a generic type. + else + { + method = typ.GetMethod("Add", [typeof(object)]); + } - Console.WriteLine(")"); - } + // Test if an Add method was found. + if (method == null) + { + Console.WriteLine("No Add method found."); + return; + } + + Type t = method.ReflectedType; + Console.Write($"{t.Namespace}.{t.Name}.{method.Name}("); + ParameterInfo[] parms = method.GetParameters(); + for (int ctr = 0; ctr < parms.Length; ctr++) + Console.Write($"{parms[ctr].ParameterType.Name}{(ctr < parms.Length - 1 ? ", " : "")}"); + + Console.WriteLine(")"); + } } // The example displays the following output: // System.Collections.ArrayList.Add(Object) diff --git a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs index e54e8d6d12a..3c6b0b60463 100644 --- a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs +++ b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs @@ -4,25 +4,13 @@ public class TestClass { - public void DisplayValue(String s) - { - Console.WriteLine(s); - } + public void DisplayValue(string s) => Console.WriteLine(s); - public void DisplayValue(String s, params Object[] values) - { - Console.WriteLine(s, values); - } + public void DisplayValue(string s, params object[] values) => Console.WriteLine(s, values); - public static bool Equals(TestClass t1, TestClass t2) - { - return Object.ReferenceEquals(t1, t2); - } + public static bool Equals(TestClass t1, TestClass t2) => object.ReferenceEquals(t1, t2); - public bool Equals(TestClass t) - { - return Object.ReferenceEquals(this, t); - } + public bool Equals(TestClass t) => object.ReferenceEquals(this, t); } public class Example1 @@ -40,14 +28,14 @@ public static void Main() RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Static); } - private static void RetrieveMethod(Type t, String name, BindingFlags flags) + private static void RetrieveMethod(Type t, string name, BindingFlags flags) { try { MethodInfo m = t.GetMethod(name, flags); if (m != null) { - Console.Write("{0}.{1}(", t.Name, m.Name); + Console.Write($"{t.Name}.{m.Name}("); ParameterInfo[] parms = m.GetParameters(); for (int ctr = 0; ctr < parms.Length; ctr++) { @@ -70,7 +58,7 @@ private static void RetrieveMethod(Type t, String name, BindingFlags flags) { if (method.Name != name) continue; - Console.Write(" {0}.{1}(", t.Name, method.Name); + Console.Write($" {t.Name}.{method.Name}("); ParameterInfo[] parms = method.GetParameters(); for (int ctr = 0; ctr < parms.Length; ctr++) { @@ -88,12 +76,12 @@ private static void RetrieveMethod(Type t, String name, BindingFlags flags) // The following duplicate matches were found: // TestClass.DisplayValue(String) // TestClass.DisplayValue(String, Object[]) -// +// // The following duplicate matches were found: // TestClass.Equals(TestClass) // TestClass.Equals(Object) -// +// // TestClass.Equals(TestClass) -// +// // TestClass.Equals(TestClass, TestClass) // diff --git a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs index a20302fe188..76fee533016 100644 --- a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs +++ b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs @@ -4,13 +4,10 @@ public class Person { - public String FirstName; - public String LastName; + public string FirstName; + public string LastName; - public override String ToString() - { - return (FirstName + " " + LastName).Trim(); - } + public override string ToString() => (FirstName + " " + LastName).Trim(); } public class Example2 @@ -20,25 +17,23 @@ public static void Main() Type t = typeof(Person); RetrieveMethod(t, "ToString"); - t = typeof(Int32); + t = typeof(int); RetrieveMethod(t, "ToString"); } - private static void RetrieveMethod(Type t, String name) + private static void RetrieveMethod(Type t, string name) { try { MethodInfo m = t.GetMethod(name); if (m != null) - Console.WriteLine("{0}.{1}: {2} method", m.ReflectedType.Name, - m.Name, m.IsStatic ? "Static" : "Instance"); + Console.WriteLine($"{m.ReflectedType.Name}.{m.Name}: {(m.IsStatic ? "Static" : "Instance")} method"); else - Console.WriteLine("{0}.ToString method not found", t.Name); + Console.WriteLine($"{t.Name}.ToString method not found"); } catch (AmbiguousMatchException) { - Console.WriteLine("{0}.{1} has multiple public overloads.", - t.Name, name); + Console.WriteLine($"{t.Name}.{name} has multiple public overloads."); } } } diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs index daa6c4a49ff..02904730e99 100644 --- a/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs +++ b/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs @@ -14,7 +14,7 @@ static void Main(string[] args) // Get MethodA() MethodInfo mInfo = typeof(Program).GetMethod("MethodA"); - Console.WriteLine("Found method: {0}", mInfo); + Console.WriteLine($"Found method: {mInfo}"); } } // diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs index 90bca4d28cb..2b71ad9dbd6 100644 --- a/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs +++ b/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs @@ -12,7 +12,7 @@ static void Main(string[] args) // Get MethodA() MethodInfo mInfo = typeof(Program).GetMethod("MethodA", BindingFlags.Public | BindingFlags.Instance); - Console.WriteLine("Found method: {0}", mInfo); + Console.WriteLine($"Found method: {mInfo}"); } } // diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs index 71abd1f72aa..ff7b8bdf725 100644 --- a/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs +++ b/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs @@ -13,59 +13,59 @@ public void MethodA(int[] i) { } public unsafe void MethodA(int* i) { } - public void MethodA(ref int r) {} + public void MethodA(ref int r) { } // Method that takes an out parameter: - public void MethodA(int i, out int o) { o = 100;} + public void MethodA(int i, out int o) => o = 100; - static void Main(string[] args) - { - MethodInfo mInfo; + static void Main(string[] args) + { + MethodInfo mInfo; - // Get MethodA(int i, int j) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(int), typeof(int) }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int i, int j) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + CallingConventions.Any, + [typeof(int), typeof(int)], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int[] i) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(int[]) }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int[] i) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + CallingConventions.Any, + [typeof(int[])], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int* i) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(int).MakePointerType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int* i) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + CallingConventions.Any, + [typeof(int).MakePointerType()], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(ref int r) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(int).MakeByRefType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(ref int r) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + CallingConventions.Any, + [typeof(int).MakeByRefType()], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int i, out int o) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(int), typeof(int).MakeByRefType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); - } + // Get MethodA(int i, out int o) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + CallingConventions.Any, + [typeof(int), typeof(int).MakeByRefType()], + null); + Console.WriteLine($"Found method: {mInfo}"); + } } // diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs index 9275c15de43..c22aec78060 100644 --- a/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs +++ b/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs @@ -13,39 +13,39 @@ public void MethodA(int[] i) { } public unsafe void MethodA(int* i) { } - public void MethodA(ref int r) {} + public void MethodA(ref int r) { } // Method that takes an out parameter: - public void MethodA(int i, out int o) { o = 100;} - - static void Main(string[] args) - { - MethodInfo mInfo; - - // Get MethodA(int i, int i) - mInfo = typeof(Program).GetMethod("MethodA", - new Type[] { typeof(int), typeof(int) }); - Console.WriteLine("Found method: {0}", mInfo); - - // Get MethodA(int[] i) - mInfo = typeof(Program).GetMethod("MethodA", - new Type[] { typeof(int[]) }); - Console.WriteLine("Found method: {0}", mInfo); - - // Get MethodA(int* i) - mInfo = typeof(Program).GetMethod("MethodA", - new Type[] { typeof(int).MakePointerType() }); - Console.WriteLine("Found method: {0}", mInfo); - - // Get MethodA(ref int r) - mInfo = typeof(Program).GetMethod("MethodA", - new Type[] { typeof(int).MakeByRefType() }); - Console.WriteLine("Found method: {0}", mInfo); - - // Get MethodA(int i, out int o) - mInfo = typeof(Program).GetMethod("MethodA", - new Type[] { typeof(int), typeof(int).MakeByRefType() }); - Console.WriteLine("Found method: {0}", mInfo); - } + public void MethodA(int i, out int o) => o = 100; + + static void Main(string[] args) + { + MethodInfo mInfo; + + // Get MethodA(int i, int i) + mInfo = typeof(Program).GetMethod("MethodA", + [typeof(int), typeof(int)]); + Console.WriteLine($"Found method: {mInfo}"); + + // Get MethodA(int[] i) + mInfo = typeof(Program).GetMethod("MethodA", + [typeof(int[])]); + Console.WriteLine($"Found method: {mInfo}"); + + // Get MethodA(int* i) + mInfo = typeof(Program).GetMethod("MethodA", + [typeof(int).MakePointerType()]); + Console.WriteLine($"Found method: {mInfo}"); + + // Get MethodA(ref int r) + mInfo = typeof(Program).GetMethod("MethodA", + [typeof(int).MakeByRefType()]); + Console.WriteLine($"Found method: {mInfo}"); + + // Get MethodA(int i, out int o) + mInfo = typeof(Program).GetMethod("MethodA", + [typeof(int), typeof(int).MakeByRefType()]); + Console.WriteLine($"Found method: {mInfo}"); + } } // diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs index bdd2e23efcb..b130195db1e 100644 --- a/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs +++ b/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs @@ -13,54 +13,54 @@ public void MethodA(int[] i) { } public unsafe void MethodA(int* i) { } - public void MethodA(ref int r) {} + public void MethodA(ref int r) { } // Method that takes an out parameter. - public void MethodA(int i, out int o) { o = 100; } + public void MethodA(int i, out int o) => o = 100; - static void Main(string[] args) - { - MethodInfo mInfo; + static void Main(string[] args) + { + MethodInfo mInfo; - // Get MethodA(int i, int j) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - new Type[] { typeof(int), typeof(int) }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int i, int j) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + [typeof(int), typeof(int)], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int[] i) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - new Type[] { typeof(int[]) }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int[] i) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + [typeof(int[])], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int* i) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - new Type[] { typeof(int).MakePointerType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(int* i) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + [typeof(int).MakePointerType()], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(ref int r) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - new Type[] { typeof(int).MakeByRefType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); + // Get MethodA(ref int r) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + [typeof(int).MakeByRefType()], + null); + Console.WriteLine($"Found method: {mInfo}"); - // Get MethodA(int i, out int o) - mInfo = typeof(Program).GetMethod("MethodA", - BindingFlags.Public | BindingFlags.Instance, - null, - new Type[] { typeof(int), typeof(int).MakeByRefType() }, - null); - Console.WriteLine("Found method: {0}", mInfo); - } + // Get MethodA(int i, out int o) + mInfo = typeof(Program).GetMethod("MethodA", + BindingFlags.Public | BindingFlags.Instance, + null, + [typeof(int), typeof(int).MakeByRefType()], + null); + Console.WriteLine($"Found method: {mInfo}"); + } } // diff --git a/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs b/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs index f50aed0e5f4..952b4f26bfc 100644 --- a/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs +++ b/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs @@ -1,7 +1,7 @@ // using System; using System.Reflection; -using System.Reflection.Emit; + // Create a class having two public methods and one protected method. public class MyTypeClass @@ -9,38 +9,32 @@ public class MyTypeClass public void MyMethods() { } - public int MyMethods1() - { - return 3; - } - protected String MyMethods2() - { - return "hello"; - } + public int MyMethods1() => 3; + protected string MyMethods2() => "hello"; } public class TypeMain { public static void Main() { - Type myType =(typeof(MyTypeClass)); + Type myType = (typeof(MyTypeClass)); // Get the public methods. - MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly); - Console.WriteLine("\nThe number of public methods is {0}.", myArrayMethodInfo.Length); + MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); + Console.WriteLine($"\nThe number of public methods is {myArrayMethodInfo.Length}."); // Display all the methods. DisplayMethodInfo(myArrayMethodInfo); // Get the nonpublic methods. - MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly); - Console.WriteLine("\nThe number of protected methods is {0}.", myArrayMethodInfo1.Length); + MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); + Console.WriteLine($"\nThe number of protected methods is {myArrayMethodInfo1.Length}."); // Display information for all methods. - DisplayMethodInfo(myArrayMethodInfo1); + DisplayMethodInfo(myArrayMethodInfo1); } public static void DisplayMethodInfo(MethodInfo[] myArrayMethodInfo) { // Display information for all methods. - for(int i=0;i \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs b/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs index 0815b133ce2..dc0981e5a4d 100644 --- a/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs +++ b/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs @@ -1,15 +1,15 @@ // using System; -using System.Reflection; + public class MyClass { public class NestClass { - public static int myPublicInt=0; + public static int myPublicInt = 0; } public struct NestStruct { - public static int myPublicInt=0; + public static int myPublicInt = 0; } } @@ -20,16 +20,16 @@ public static void Main() try { // Get the Type object corresponding to MyClass. - Type myType=typeof(MyClass); + Type myType = typeof(MyClass); // Get an array of nested type objects in MyClass. - Type[] nestType=myType.GetNestedTypes(); - Console.WriteLine("The number of nested types is {0}.", nestType.Length); - foreach(Type t in nestType) - Console.WriteLine("Nested type is {0}.", t.ToString()); + Type[] nestType = myType.GetNestedTypes(); + Console.WriteLine($"The number of nested types is {nestType.Length}."); + foreach (Type t in nestType) + Console.WriteLine($"Nested type is {t}."); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("Error"+e.Message); + Console.WriteLine("Error" + e.Message); } } } diff --git a/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs b/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs index 0ccfc43b7ee..0296cbaba17 100644 --- a/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs +++ b/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs @@ -5,35 +5,17 @@ // Create a class having six properties. public class PropertyClass { - public String Property1 - { - get { return "hello"; } - } + public string Property1 => "hello"; - public String Property2 - { - get { return "hello"; } - } + public string Property2 => "hello"; - protected String Property3 - { - get { return "hello"; } - } + protected string Property3 => "hello"; - private Int32 Property4 - { - get { return 32; } - } + private int Property4 => 32; - internal String Property5 - { - get { return "value"; } - } + internal string Property5 => "value"; - protected internal String Property6 - { - get { return "value"; } - } + protected internal string Property6 => "value"; } public class Example @@ -42,16 +24,14 @@ public static void Main() { Type t = typeof(PropertyClass); // Get the public properties. - PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public|BindingFlags.Instance); - Console.WriteLine("The number of public properties: {0}.\n", - propInfos.Length); + PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); + Console.WriteLine($"The number of public properties: {propInfos.Length}.\n"); // Display the public properties. DisplayPropertyInfo(propInfos); // Get the nonpublic properties. - PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance); - Console.WriteLine("The number of non-public properties: {0}.\n", - propInfos1.Length); + PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); + Console.WriteLine($"The number of non-public properties: {propInfos1.Length}.\n"); // Display all the nonpublic properties. DisplayPropertyInfo(propInfos1); } @@ -59,39 +39,40 @@ public static void Main() public static void DisplayPropertyInfo(PropertyInfo[] propInfos) { // Display information for all properties. - foreach (var propInfo in propInfos) { + foreach (var propInfo in propInfos) + { bool readable = propInfo.CanRead; bool writable = propInfo.CanWrite; - Console.WriteLine(" Property name: {0}", propInfo.Name); - Console.WriteLine(" Property type: {0}", propInfo.PropertyType); - Console.WriteLine(" Read-Write: {0}", readable & writable); - if (readable) { - MethodInfo getAccessor = propInfo.GetMethod; - Console.WriteLine(" Visibility: {0}", - GetVisibility(getAccessor)); + Console.WriteLine($" Property name: {propInfo.Name}"); + Console.WriteLine($" Property type: {propInfo.PropertyType}"); + Console.WriteLine($" Read-Write: {readable & writable}"); + if (readable) + { + MethodInfo getAccessor = propInfo.GetMethod; + Console.WriteLine($" Visibility: {GetVisibility(getAccessor)}"); } - if (writable) { - MethodInfo setAccessor = propInfo.SetMethod; - Console.WriteLine(" Visibility: {0}", - GetVisibility(setAccessor)); + if (writable) + { + MethodInfo setAccessor = propInfo.SetMethod; + Console.WriteLine($" Visibility: {GetVisibility(setAccessor)}"); } Console.WriteLine(); } } - public static String GetVisibility(MethodInfo accessor) + public static string GetVisibility(MethodInfo accessor) { - if (accessor.IsPublic) - return "Public"; - else if (accessor.IsPrivate) - return "Private"; - else if (accessor.IsFamily) - return "Protected"; - else if (accessor.IsAssembly) - return "Internal/Friend"; - else - return "Protected Internal/Friend"; + if (accessor.IsPublic) + return "Public"; + else if (accessor.IsPrivate) + return "Private"; + else if (accessor.IsFamily) + return "Protected"; + else if (accessor.IsAssembly) + return "Internal/Friend"; + else + return "Protected Internal/Friend"; } } // The example displays the following output: diff --git a/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs b/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs index ea1d3e67d35..be9dba71888 100644 --- a/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs +++ b/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs @@ -20,49 +20,49 @@ class MyClass { static void Main(string[] args) { -// + // // Create an object of 'Type' class. Type myType1 = Type.GetType("System.Int32"); // Get the 'TypeCode' of the 'Type' class object created above. TypeCode myTypeCode = Type.GetTypeCode(myType1); - Console.WriteLine("TypeCode is: {0}",myTypeCode); -// -// + Console.WriteLine($"TypeCode is: {myTypeCode}"); + // + // PropertyInfo[] myPropertyInfo; // Get the properties of 'Type' class object. myPropertyInfo = Type.GetType("System.Type").GetProperties(); Console.WriteLine("Properties of System.Type are:"); for (int i = 0; i < myPropertyInfo.Length; i++) { - Console.WriteLine(myPropertyInfo[i].ToString()); + Console.WriteLine(myPropertyInfo[i]); } -// -// - Object[] myObject = new Object[3]; + // + // + object[] myObject = new object[3]; myObject[0] = 66; myObject[1] = "puri"; myObject[2] = 33.33; // Get the array of 'Type' class objects. Type[] myTypeArray = Type.GetTypeArray(myObject); Console.WriteLine("Full names of the 'Type' objects in the array are:"); - for(int h = 0; h < myTypeArray.Length ; h++) + for (int h = 0; h < myTypeArray.Length; h++) { Console.WriteLine(myTypeArray[h].FullName); } -// -// + // + // try { // Throws 'TypeLoadException' because of case-sensitive search. - Type myType2 = Type.GetType("sYSTem.iNT32",true,false); + Type myType2 = Type.GetType("sYSTem.iNT32", true, false); Console.WriteLine(myType2.FullName); } - catch(TypeLoadException e) + catch (TypeLoadException e) { Console.WriteLine(e.Message); } -// - catch(Exception e) + // + catch (Exception e) { Console.WriteLine(e.Message); } diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs index c1d1196f3c8..60794e62ad2 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs @@ -21,7 +21,7 @@ public static void Main(string[] args) PropertyInfo myPropInfo = myType.GetProperty("MyProperty"); // Display the property name. - Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.Name); + Console.WriteLine($"The {myPropInfo.Name} property exists in MyClass1."); } catch (NullReferenceException e) { diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs index 6d5fdbebbba..f543aa0017b 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs @@ -25,7 +25,7 @@ public static void Main(string[] args) ); // Display Name property to console. - Console.WriteLine("{0} is a property of MyClass2.", myPropInfo.Name); + Console.WriteLine($"{myPropInfo.Name} is a property of MyClass2."); } catch (NullReferenceException e) { diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs index 5f7ee5d3e84..4279b28123f 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs @@ -4,18 +4,12 @@ public class MyPropertyClass { - private readonly int [,] _myPropertyArray = new int[10,10]; + private readonly int[,] _myPropertyArray = new int[10, 10]; // Declare an indexer. - public int this [int i,int j] + public int this[int i, int j] { - get - { - return _myPropertyArray[i,j]; - } - set - { - _myPropertyArray[i,j] = value; - } + get => _myPropertyArray[i, j]; + set => _myPropertyArray[i, j] = value; } } @@ -25,22 +19,22 @@ public static void Main() { try { - Type myType=typeof(MyPropertyClass); + Type myType = typeof(MyPropertyClass); Type[] myTypeArray = new Type[2]; // Create an instance of the Type array representing the number, order // and type of the parameters for the property. - myTypeArray.SetValue(typeof(int),0); - myTypeArray.SetValue(typeof(int),1); + myTypeArray.SetValue(typeof(int), 0); + myTypeArray.SetValue(typeof(int), 1); // Search for the indexed property whose parameters match the // specified argument types and modifiers. PropertyInfo myPropertyInfo = myType.GetProperty("Item", - typeof(int),myTypeArray,null); + typeof(int), myTypeArray, null); Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name + " has a property type of " + myPropertyInfo.PropertyType); - } - catch(Exception ex) + } + catch (Exception ex) { Console.WriteLine("An exception occurred " + ex.Message); } diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs index b30e4da0e67..c29675280b8 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs @@ -9,14 +9,8 @@ class MyClass3 // Declare an indexer. public int this[int i, int j] { - get - { - return _myArray[i, j]; - } - set - { - _myArray[i, j] = value; - } + get => _myArray[i, j]; + set => _myArray[i, j] = value; } } @@ -38,14 +32,13 @@ public static void Main(string[] args) PropertyInfo myPropInfo = myType.GetProperty("Item", myTypeArr); // Display the property. - Console.WriteLine("The {0} property exists in MyClass3.", - myPropInfo.ToString()); + Console.WriteLine($"The {myPropInfo} property exists in MyClass3."); } catch (NullReferenceException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Source : {0}", e.Source); - Console.WriteLine("Message : {0}", e.Message); + Console.WriteLine($"Source : {e.Source}"); + Console.WriteLine($"Message : {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs index 5bd74bc952a..2a7433a34e7 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs @@ -19,10 +19,8 @@ static void Main() // Get the PropertyInfo object representing MyProperty1. PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1", typeof(string)); - Console.WriteLine("The name of the first property of MyPropertyTypeClass is {0}.", - myStringProperties1.Name); - Console.WriteLine("The type of the first property of MyPropertyTypeClass is {0}.", - myStringProperties1.PropertyType); + Console.WriteLine($"The name of the first property of MyPropertyTypeClass is {myStringProperties1.Name}."); + Console.WriteLine($"The type of the first property of MyPropertyTypeClass is {myStringProperties1.PropertyType}."); } catch (ArgumentNullException e) { @@ -34,12 +32,12 @@ static void Main() } catch (NullReferenceException e) { - Console.WriteLine("Source : {0}", e.Source); - Console.WriteLine("Message : {0}", e.Message); + Console.WriteLine($"Source : {e.Source}"); + Console.WriteLine($"Message : {e.Message}"); } //Output: //The name of the first property of MyPropertyTypeClass is MyProperty1. //The type of the first property of MyPropertyTypeClass is System.String. } } -// +// diff --git a/snippets/csharp/System/Type/GetType/Project.csproj b/snippets/csharp/System/Type/GetType/Project.csproj index 874c98f3477..1eddf5e00ac 100644 --- a/snippets/csharp/System/Type/GetType/Project.csproj +++ b/snippets/csharp/System/Type/GetType/Project.csproj @@ -1,8 +1,6 @@ - Library net10.0 - - + diff --git a/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs b/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs index 7141baf6e99..83b7a06f4be 100644 --- a/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs +++ b/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs @@ -1,6 +1,6 @@ -using System; + namespace MyNamespace { - public class MyType {} + public class MyType { } } diff --git a/snippets/csharp/System/Type/GetType/source.cs b/snippets/csharp/System/Type/GetType/source.cs index cdf553928e0..29486be664c 100644 --- a/snippets/csharp/System/Type/GetType/source.cs +++ b/snippets/csharp/System/Type/GetType/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; class Example diff --git a/snippets/csharp/System/Type/GetType/type_gettype.cs b/snippets/csharp/System/Type/GetType/type_gettype.cs index c0345bf6a7a..77611966ab3 100644 --- a/snippets/csharp/System/Type/GetType/type_gettype.cs +++ b/snippets/csharp/System/Type/GetType/type_gettype.cs @@ -3,27 +3,30 @@ class GetTypeExample { - public static void Main() - { - try { - // Get the type of a specified class. - Type myType1 = Type.GetType("System.Int32"); - Console.WriteLine("The full name is {0}.\n", myType1.FullName); - } - catch (TypeLoadException e) - { - Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name); - } + public static void Main() + { + try + { + // Get the type of a specified class. + Type myType1 = Type.GetType("System.Int32"); + Console.WriteLine($"The full name is {myType1.FullName}.\n"); + } + catch (TypeLoadException e) + { + Console.WriteLine($"{e.GetType().Name}: Unable to load type System.Int32"); + } - try { - // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException. - Type myType2 = Type.GetType("NoneSuch", true); - Console.WriteLine("The full name is {0}.", myType2.FullName); - } - catch(TypeLoadException e) { - Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name); - } - } + try + { + // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException. + Type myType2 = Type.GetType("NoneSuch", true); + Console.WriteLine($"The full name is {myType2.FullName}."); + } + catch (TypeLoadException e) + { + Console.WriteLine($"{e.GetType().Name}: Unable to load type NoneSuch"); + } + } } // The example displays the following output: // The full name is System.Int32. diff --git a/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs b/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs index 66c93790914..c9396ce0e7b 100644 --- a/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs +++ b/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs @@ -7,8 +7,8 @@ namespace ConsoleApplication2 /// Class that implements IConvertible class Complex : IConvertible { - double x; - double y; + double x; + double y; public Complex(double x, double y) { @@ -16,98 +16,47 @@ public Complex(double x, double y) this.y = y; } - public TypeCode GetTypeCode() - { - return TypeCode.Object; - } + public TypeCode GetTypeCode() => TypeCode.Object; bool IConvertible.ToBoolean(IFormatProvider provider) { - if( (x != 0.0) || (y != 0.0) ) + if ((x != 0.0) || (y != 0.0)) return true; else return false; } - double GetDoubleValue() - { - return Math.Sqrt(x*x + y*y); - } + double GetDoubleValue() => Math.Sqrt(x * x + y * y); - byte IConvertible.ToByte(IFormatProvider provider) - { - return Convert.ToByte(GetDoubleValue()); - } + byte IConvertible.ToByte(IFormatProvider provider) => Convert.ToByte(GetDoubleValue()); - char IConvertible.ToChar(IFormatProvider provider) - { - return Convert.ToChar(GetDoubleValue()); - } + char IConvertible.ToChar(IFormatProvider provider) => Convert.ToChar(GetDoubleValue()); - DateTime IConvertible.ToDateTime(IFormatProvider provider) - { - return Convert.ToDateTime(GetDoubleValue()); - } + DateTime IConvertible.ToDateTime(IFormatProvider provider) => Convert.ToDateTime(GetDoubleValue()); - decimal IConvertible.ToDecimal(IFormatProvider provider) - { - return Convert.ToDecimal(GetDoubleValue()); - } + decimal IConvertible.ToDecimal(IFormatProvider provider) => Convert.ToDecimal(GetDoubleValue()); - double IConvertible.ToDouble(IFormatProvider provider) - { - return GetDoubleValue(); - } + double IConvertible.ToDouble(IFormatProvider provider) => GetDoubleValue(); - short IConvertible.ToInt16(IFormatProvider provider) - { - return Convert.ToInt16(GetDoubleValue()); - } + short IConvertible.ToInt16(IFormatProvider provider) => Convert.ToInt16(GetDoubleValue()); - int IConvertible.ToInt32(IFormatProvider provider) - { - return Convert.ToInt32(GetDoubleValue()); - } + int IConvertible.ToInt32(IFormatProvider provider) => Convert.ToInt32(GetDoubleValue()); - long IConvertible.ToInt64(IFormatProvider provider) - { - return Convert.ToInt64(GetDoubleValue()); - } + long IConvertible.ToInt64(IFormatProvider provider) => Convert.ToInt64(GetDoubleValue()); - sbyte IConvertible.ToSByte(IFormatProvider provider) - { - return Convert.ToSByte(GetDoubleValue()); - } + sbyte IConvertible.ToSByte(IFormatProvider provider) => Convert.ToSByte(GetDoubleValue()); - float IConvertible.ToSingle(IFormatProvider provider) - { - return Convert.ToSingle(GetDoubleValue()); - } + float IConvertible.ToSingle(IFormatProvider provider) => Convert.ToSingle(GetDoubleValue()); - string IConvertible.ToString(IFormatProvider provider) - { - return "( " + x.ToString() + " , " + y.ToString() + " )"; - } + string IConvertible.ToString(IFormatProvider provider) => "( " + x + " , " + y + " )"; - object IConvertible.ToType(Type conversionType, IFormatProvider provider) - { - return Convert.ChangeType(GetDoubleValue(),conversionType); - } + object IConvertible.ToType(Type conversionType, IFormatProvider provider) => Convert.ChangeType(GetDoubleValue(), conversionType); - ushort IConvertible.ToUInt16(IFormatProvider provider) - { - return Convert.ToUInt16(GetDoubleValue()); - } + ushort IConvertible.ToUInt16(IFormatProvider provider) => Convert.ToUInt16(GetDoubleValue()); - uint IConvertible.ToUInt32(IFormatProvider provider) - { - return Convert.ToUInt32(GetDoubleValue()); - } + uint IConvertible.ToUInt32(IFormatProvider provider) => Convert.ToUInt32(GetDoubleValue()); - ulong IConvertible.ToUInt64(IFormatProvider provider) - { - return Convert.ToUInt64(GetDoubleValue()); - } + ulong IConvertible.ToUInt64(IFormatProvider provider) => Convert.ToUInt64(GetDoubleValue()); } /// @@ -118,34 +67,34 @@ class Class1 static void Main(string[] args) { - Complex testComplex = new Complex(4,7); + Complex testComplex = new(4, 7); WriteObjectInfo(testComplex); WriteObjectInfo(Convert.ToBoolean(testComplex)); WriteObjectInfo(Convert.ToDecimal(testComplex)); WriteObjectInfo(Convert.ToString(testComplex)); } -// + // static void WriteObjectInfo(object testObject) { - TypeCode typeCode = Type.GetTypeCode( testObject.GetType() ); + TypeCode typeCode = Type.GetTypeCode(testObject.GetType()); - switch( typeCode ) + switch (typeCode) { case TypeCode.Boolean: - Console.WriteLine("Boolean: {0}", testObject); + Console.WriteLine($"Boolean: {testObject}"); break; case TypeCode.Double: - Console.WriteLine("Double: {0}", testObject); + Console.WriteLine($"Double: {testObject}"); break; default: - Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject); + Console.WriteLine($"{typeCode}: {testObject}"); break; } } -// + // } } diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs new file mode 100644 index 00000000000..e5bc219e3f2 --- /dev/null +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs @@ -0,0 +1,5 @@ +GetTypeFromClsidExample1.Run(); +GetTypeFromClsidExample11.Run(); +GetTypeFromClsidExample2.Run(); +GetTypeFromClsidExample3.Run(); +GetTypeFromClsidExample4.Run(); diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj b/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs index ef6f4b99acd..af508f946cc 100644 --- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs @@ -1,26 +1,25 @@ // using System; using System.Reflection; -using System.Runtime.InteropServices; -public class Example + +public class GetTypeFromClsidExample1 { - private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; - - public static void Main() - { - // Start an instance of the Word application. - var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID)); - Console.WriteLine("Instantiated Type object from CLSID {0}", - WORD_CLSID); - Object wordObj = Activator.CreateInstance(word); - Console.WriteLine("Instantiated {0}", - wordObj.GetType().FullName); - - // Close Word. - word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, - wordObj, new object[] { 0, 0, false } ); - } + private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; + + public static void Run() + { + // Start an instance of the Word application. + var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID)); + Console.WriteLine("Instantiated Type object from CLSID {0}", + WORD_CLSID); + object wordObj = Activator.CreateInstance(word); + Console.WriteLine($"Instantiated {wordObj.GetType().FullName}"); + + // Close Word. + word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, + wordObj, [0, 0, false]); + } } // The example displays the following output: // Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046} diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs index f6b20ed2b01..cd4851d6a74 100644 --- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs @@ -2,7 +2,7 @@ using System; using System.Runtime.InteropServices; -[assembly:ComVisible(true)] +[assembly: ComVisible(true)] // Define two classes, and assign one an explicit GUID. [GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")] @@ -12,69 +12,67 @@ public class ExplicitGuid public class NoExplicitGuid { } -public class Example +public class GetTypeFromClsidExample11 { - public static void Main() - { - Type explicitType = typeof(ExplicitGuid); - Guid explicitGuid = explicitType.GUID; - - // Get type of ExplicitGuid from its GUID. - Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid); - Console.WriteLine("Created {0} type from CLSID {1}", - explicitCOM.Name, explicitGuid); - - // Compare the two type objects. - Console.WriteLine("{0} and {1} equal: {2}", - explicitType.Name, explicitCOM.Name, - explicitType.Equals(explicitCOM)); - - // Instantiate an ExplicitGuid object. - try { - Object obj = Activator.CreateInstance(explicitCOM); - Console.WriteLine("Instantiated a {0} object", obj.GetType().Name); - } - catch (COMException e) { - Console.WriteLine("COM Exception:\n{0}\n", e.Message); - } - - Type notExplicit = typeof(NoExplicitGuid); - Guid notExplicitGuid = notExplicit.GUID; - - // Get type of ExplicitGuid from its GUID. - Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid); - Console.WriteLine("Created {0} type from CLSID {1}", - notExplicitCOM.Name, notExplicitGuid); - - // Compare the two type objects. - Console.WriteLine("{0} and {1} equal: {2}", - notExplicit.Name, notExplicitCOM.Name, - notExplicit.Equals(notExplicitCOM)); - - // Instantiate an ExplicitGuid object. - try { - Object obj = Activator.CreateInstance(notExplicitCOM); - Console.WriteLine("Instantiated a {0} object", obj.GetType().Name); - } - catch (COMException e) { - Console.WriteLine("COM Exception:\n{0}\n", e.Message); - } - } + public static void Run() + { + Type explicitType = typeof(ExplicitGuid); + Guid explicitGuid = explicitType.GUID; + + // Get type of ExplicitGuid from its GUID. + Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid); + Console.WriteLine($"Created {explicitCOM.Name} type from CLSID {explicitGuid}"); + + // Compare the two type objects. + Console.WriteLine($"{explicitType.Name} and {explicitCOM.Name} equal: {explicitType.Equals(explicitCOM)}"); + + // Instantiate an ExplicitGuid object. + try + { + object obj = Activator.CreateInstance(explicitCOM); + Console.WriteLine($"Instantiated a {obj.GetType().Name} object"); + } + catch (COMException e) + { + Console.WriteLine($"COM Exception:\n{e.Message}\n"); + } + + Type notExplicit = typeof(NoExplicitGuid); + Guid notExplicitGuid = notExplicit.GUID; + + // Get type of ExplicitGuid from its GUID. + Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid); + Console.WriteLine($"Created {notExplicitCOM.Name} type from CLSID {notExplicitGuid}"); + + // Compare the two type objects. + Console.WriteLine($"{notExplicit.Name} and {notExplicitCOM.Name} equal: {notExplicit.Equals(notExplicitCOM)}"); + + // Instantiate an ExplicitGuid object. + try + { + object obj = Activator.CreateInstance(notExplicitCOM); + Console.WriteLine($"Instantiated a {obj.GetType().Name} object"); + } + catch (COMException e) + { + Console.WriteLine($"COM Exception:\n{e.Message}\n"); + } + } } // The example displays the following output: // Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4 // ExplicitGuid and __ComObject equal: False // COM Exception: -// Retrieving the COM class factory for component with CLSID -// {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: -// 80040154 Class not registered +// Retrieving the COM class factory for component with CLSID +// {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error: +// 80040154 Class not registered // (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). -// +// // Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb // NoExplicitGuid and __ComObject equal: False // COM Exception: -// Retrieving the COM class factory for component with CLSID -// {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: -// 80040154 Class not registered +// Retrieving the COM class factory for component with CLSID +// {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error: +// 80040154 Class not registered // (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). // diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs index 721c6fbd9a9..a1f9728aad0 100644 --- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs @@ -1,31 +1,33 @@ // using System; using System.Reflection; -using System.Runtime.InteropServices; -public class Example + +public class GetTypeFromClsidExample2 { - private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; - - public static void Main() - { - try { - // Start an instance of the Word application. - var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), true); - Console.WriteLine("Instantiated Type object from CLSID {0}", - WORD_CLSID); - Object wordObj = Activator.CreateInstance(word); - Console.WriteLine("Instantiated {0}", - wordObj.GetType().FullName, WORD_CLSID); - - // Close Word. - word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, - wordObj, new object[] { 0, 0, false } ); - } - catch (Exception) { - Console.WriteLine("Unable to instantiate an object for {0}", WORD_CLSID); - } - } + private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; + + public static void Run() + { + try + { + // Start an instance of the Word application. + var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), true); + Console.WriteLine("Instantiated Type object from CLSID {0}", + WORD_CLSID); + object wordObj = Activator.CreateInstance(word); + Console.WriteLine("Instantiated {0}", + wordObj.GetType().FullName, WORD_CLSID); + + // Close Word. + word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, + wordObj, [0, 0, false]); + } + catch (Exception) + { + Console.WriteLine("Unable to instantiate an object for {0}", WORD_CLSID); + } + } } // The example displays the following output: // Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046} diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs index 1f82da2f08e..f5f2672cb1d 100644 --- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs @@ -3,29 +3,31 @@ using System.Reflection; using System.Runtime.InteropServices; -public class Example +public class GetTypeFromClsidExample3 { - private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; - - public static void Main() - { - // Start an instance of the Word application. - var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), "computer17.central.contoso.com"); - Console.WriteLine("Instantiated Type object from CLSID {0}", - WORD_CLSID); - try { - Object wordObj = Activator.CreateInstance(word); - Console.WriteLine("Instantiated {0}", - wordObj.GetType().FullName, WORD_CLSID); - - // Close Word. - word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, - wordObj, new object[] { 0, 0, false } ); - } - catch (COMException) { - Console.WriteLine("Unable to instantiate object."); - } - } + private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; + + public static void Run() + { + // Start an instance of the Word application. + var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), "computer17.central.contoso.com"); + Console.WriteLine("Instantiated Type object from CLSID {0}", + WORD_CLSID); + try + { + object wordObj = Activator.CreateInstance(word); + Console.WriteLine("Instantiated {0}", + wordObj.GetType().FullName, WORD_CLSID); + + // Close Word. + word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, + wordObj, [0, 0, false]); + } + catch (COMException) + { + Console.WriteLine("Unable to instantiate object."); + } + } } // The example displays the following output: // Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046} diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs index ca61680bb07..2f5f32e40bf 100644 --- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs +++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs @@ -1,35 +1,37 @@ // using System; using System.Reflection; -using System.Runtime.InteropServices; -public class Example + +public class GetTypeFromClsidExample4 { - private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; - - public static void Main() - { - try { - // Start an instance of the Word application. - var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), - "computer17.central.contoso.com", - true); - Console.WriteLine("Instantiated Type object from CLSID {0}", - WORD_CLSID); - Object wordObj = Activator.CreateInstance(word); - Console.WriteLine("Instantiated {0}", - wordObj.GetType().FullName, WORD_CLSID); - - // Close Word. - word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, - wordObj, new object[] { 0, 0, false } ); - } - // The method can throw any of a variety of exceptions. - catch (Exception e) { - Console.WriteLine("{0}: Unable to instantiate an object for {1}", - e.GetType().Name, WORD_CLSID); - } - } + private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}"; + + public static void Run() + { + try + { + // Start an instance of the Word application. + var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), + "computer17.central.contoso.com", + true); + Console.WriteLine("Instantiated Type object from CLSID {0}", + WORD_CLSID); + object wordObj = Activator.CreateInstance(word); + Console.WriteLine("Instantiated {0}", + wordObj.GetType().FullName, WORD_CLSID); + + // Close Word. + word.InvokeMember("Quit", BindingFlags.InvokeMethod, null, + wordObj, [0, 0, false]); + } + // The method can throw any of a variety of exceptions. + catch (Exception e) + { + Console.WriteLine("{0}: Unable to instantiate an object for {1}", + e.GetType().Name, WORD_CLSID); + } + } } // The example displays the following output: // Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046} diff --git a/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs b/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs index 5cc5c7b802a..9912d73d65b 100644 --- a/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs +++ b/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs @@ -9,20 +9,20 @@ returns the type referenced by the specified type handle. */ using System; -using System.Reflection; + public class MyClass1 { } public class MyClass2 { - public static void Main() - { -// - MyClass1 myClass1 = new MyClass1(); - // Get the type referenced by the specified type handle. + public static void Main() + { + // + MyClass1 myClass1 = new(); + // Get the type referenced by the specified type handle. Type myClass1Type = Type.GetTypeFromHandle(Type.GetTypeHandle(myClass1)); - Console.WriteLine("The Names of the Attributes :"+myClass1Type.Attributes); -// - } + Console.WriteLine("The Names of the Attributes :" + myClass1Type.Attributes); + // + } } diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs b/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs new file mode 100644 index 00000000000..20ffc263a18 --- /dev/null +++ b/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs @@ -0,0 +1,3 @@ +ProgIdExample2.Run(); +ProgIdExample3.Run(); +ProgIdExample4.Run(); diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj b/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs index 79fae7f6198..d319b5442c5 100644 --- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs +++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs @@ -1,27 +1,27 @@ // using System; -class MainApp +class ProgIdExample2 { - public static void Main() + public static void Run() { try { // Use the ProgID HKEY_CLASSES_ROOT\DirControl.DirList.1. - string myString1 ="DIRECT.ddPalette.3"; + string myString1 = "DIRECT.ddPalette.3"; // Use a nonexistent ProgID WrongProgID. - string myString2 ="WrongProgID"; + string myString2 = "WrongProgID"; // Make a call to the method to get the type information of the given ProgID. - Type myType1 =Type.GetTypeFromProgID(myString1,true); - Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType1.GUID); + Type myType1 = Type.GetTypeFromProgID(myString1, true); + Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType1.GUID}."); // Throw an exception because the ProgID is invalid and the throwOnError // parameter is set to True. - Type myType2 =Type.GetTypeFromProgID(myString2,true); + Type myType2 = Type.GetTypeFromProgID(myString2, true); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Source: {0}", e.Source); - Console.WriteLine("Message: {0}", e.Message); + Console.WriteLine($"Source: {e.Source}"); + Console.WriteLine($"Message: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs index c393f182998..ee9e294fe37 100644 --- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs +++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs @@ -1,29 +1,29 @@ // using System; -class MainApp +class ProgIdExample3 { - public static void Main() + public static void Run() { try { // Use the ProgID localhost\HKEY_CLASSES_ROOT\DirControl.DirList.1. - string theProgramID ="DirControl.DirList.1"; + string theProgramID = "DirControl.DirList.1"; // Use the server name localhost. - string theServer="localhost"; + string theServer = "localhost"; // Make a call to the method to get the type information for the given ProgID. - Type myType =Type.GetTypeFromProgID(theProgramID,theServer); - if(myType==null) + Type myType = Type.GetTypeFromProgID(theProgramID, theServer); + if (myType == null) { throw new Exception("Invalid ProgID or Server."); } - Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType.GUID); + Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType.GUID}."); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Source: {0}" , e.Source); - Console.WriteLine("Message: {0}" , e.Message); - } + Console.WriteLine($"Source: {e.Source}"); + Console.WriteLine($"Message: {e.Message}"); + } } } // diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs index 614ad868a87..8f2b49274f7 100644 --- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs +++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs @@ -1,30 +1,30 @@ // using System; -class MainApp +class ProgIdExample4 { - public static void Main() + public static void Run() { try { // Use server localhost. - string theServer="localhost"; + string theServer = "localhost"; // Use ProgID HKEY_CLASSES_ROOT\DirControl.DirList.1. - string myString1 ="DirControl.DirList.1"; + string myString1 = "DirControl.DirList.1"; // Use a wrong ProgID WrongProgID. - string myString2 ="WrongProgID"; + string myString2 = "WrongProgID"; // Make a call to the method to get the type information for the given ProgID. - Type myType1 =Type.GetTypeFromProgID(myString1,theServer,true); - Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType1.GUID); + Type myType1 = Type.GetTypeFromProgID(myString1, theServer, true); + Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType1.GUID}."); // Throw an exception because the ProgID is invalid and the throwOnError // parameter is set to True. - Type myType2 =Type.GetTypeFromProgID(myString2, theServer, true); + Type myType2 = Type.GetTypeFromProgID(myString2, theServer, true); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("An exception occurred. The ProgID is wrong."); - Console.WriteLine("Source: {0}" , e.Source); - Console.WriteLine("Message: {0}" , e.Message); + Console.WriteLine($"Source: {e.Source}"); + Console.WriteLine($"Message: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/HasElementType/Project.csproj b/snippets/csharp/System/Type/HasElementType/Project.csproj new file mode 100644 index 00000000000..44b6b69ca6f --- /dev/null +++ b/snippets/csharp/System/Type/HasElementType/Project.csproj @@ -0,0 +1,7 @@ + + + Exe + net10.0 + true + + diff --git a/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs b/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs index 72580e41191..4217e994597 100644 --- a/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs +++ b/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs @@ -7,29 +7,26 @@ public class Example { // This method is for demonstration purposes. - unsafe public void Test(ref int x, out int y, int* z) - { - *z = x = y = 0; - } + unsafe public void Test(ref int x, out int y, int* z) => *z = x = y = 0; public static void Main() { // All of the following display 'True'. // Define an array, get its type, and display HasElementType. - int[] nums = {1, 1, 2, 3, 5, 8, 13}; + int[] nums = [1, 1, 2, 3, 5, 8, 13]; Type t = nums.GetType(); - Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types."); // Test an array type without defining an array. t = typeof(Example[]); - Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types."); // When you use Reflection Emit to emit dynamic methods and // assemblies, you can create array types using MakeArrayType. // The following creates the type 'array of Example'. t = typeof(Example).MakeArrayType(); - Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types."); // When you reflect over methods, HasElementType is true for // ref, out, and pointer parameter types. The following @@ -38,19 +35,19 @@ public static void Main() MethodInfo mi = typeof(Example).GetMethod("Test"); ParameterInfo[] parms = mi.GetParameters(); t = parms[0].ParameterType; - Console.WriteLine("HasElementType is '{0}' for ref parameter types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for ref parameter types."); t = parms[1].ParameterType; - Console.WriteLine("HasElementType is '{0}' for out parameter types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for out parameter types."); t = parms[2].ParameterType; - Console.WriteLine("HasElementType is '{0}' for pointer parameter types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for pointer parameter types."); // When you use Reflection Emit to emit dynamic methods and // assemblies, you can create pointer and ByRef types to use // when you define method parameters. t = typeof(Example).MakePointerType(); - Console.WriteLine("HasElementType is '{0}' for pointer types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for pointer types."); t = typeof(Example).MakeByRefType(); - Console.WriteLine("HasElementType is '{0}' for ByRef types.", t.HasElementType); + Console.WriteLine($"HasElementType is '{t.HasElementType}' for ByRef types."); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs b/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs index 18df3d3db3c..9dee37ed1ed 100644 --- a/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs +++ b/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs @@ -4,28 +4,25 @@ public class MyTypeDelegator : TypeDelegator { public string myElementType = null; - private Type myType = null ; - public MyTypeDelegator(Type myType) : base(myType) - { - this.myType = myType; - } + private Type myType = null; + public MyTypeDelegator(Type myType) : base(myType) => this.myType = myType; // Override Type.HasElementTypeImpl(). protected override bool HasElementTypeImpl() { // Determine whether the type is an array. - if(myType.IsArray) + if (myType.IsArray) { myElementType = "array"; return true; } // Determine whether the type is a reference. - if(myType.IsByRef) + if (myType.IsByRef) { myElementType = "reference"; return true; } // Determine whether the type is a pointer. - if(myType.IsPointer) + if (myType.IsPointer) { myElementType = "pointer"; return true; @@ -40,25 +37,25 @@ public static void Main() { try { - int myInt = 0 ; + int myInt = 0; int[] myArray = new int[5]; - MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType()); + MyTypeDelegator myType = new(myArray.GetType()); // Determine whether myType is an array, pointer, reference type. Console.WriteLine("\nDetermine whether a variable is an array, pointer, or reference type.\n"); - if( myType.HasElementType) - Console.WriteLine("The type of myArray is {0}.", myType.myElementType); + if (myType.HasElementType) + Console.WriteLine($"The type of myArray is {myType.myElementType}."); else Console.WriteLine("myArray is not an array, pointer, or reference type."); - myType = new MyTypeDelegator(myInt.GetType()); + myType = new(myInt.GetType()); // Determine whether myType is an array, pointer, reference type. - if( myType.HasElementType) - Console.WriteLine("The type of myInt is {0}.", myType.myElementType); + if (myType.HasElementType) + Console.WriteLine($"The type of myInt is {myType.myElementType}."); else Console.WriteLine("myInt is not an array, pointer, or reference type."); } - catch( Exception e ) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message); + Console.WriteLine($"Exception: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/InvokeMember/invokemem.cs b/snippets/csharp/System/Type/InvokeMember/invokemem.cs index 69618c33a7a..b9b9282fb9c 100644 --- a/snippets/csharp/System/Type/InvokeMember/invokemem.cs +++ b/snippets/csharp/System/Type/InvokeMember/invokemem.cs @@ -5,12 +5,12 @@ // This sample class has a field, constructor, method, and property. class MyType { - Int32 myField; - public MyType(ref Int32 x) {x *= 5;} - public override String ToString() {return myField.ToString();} - public Int32 MyProp + int myField; + public MyType(ref int x) => x *= 5; + public override string ToString() => myField.ToString(); + public int MyProp { - get {return myField;} + get => myField; set { if (value < 1) @@ -26,28 +26,28 @@ static void Main() { Type t = typeof(MyType); // Create an instance of a type. - Object[] args = new Object[] {8}; - Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]); - Object obj = t.InvokeMember(null, + object[] args = [8]; + Console.WriteLine($"The value of x before the constructor is called is {args[0]}."); + object obj = t.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args); - Console.WriteLine("Type: " + obj.GetType().ToString()); - Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]); + Console.WriteLine("Type: " + obj.GetType()); + Console.WriteLine($"The value of x after the constructor returns is {args[0]}."); // Read and write to a field. t.InvokeMember("myField", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5}); - Int32 v = (Int32) t.InvokeMember("myField", + BindingFlags.Instance | BindingFlags.SetField, null, obj, [5]); + int v = (int)t.InvokeMember("myField", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, obj, null); Console.WriteLine("myField: " + v); // Call a method. - String s = (String) t.InvokeMember("ToString", + string s = (string)t.InvokeMember("ToString", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null); @@ -67,7 +67,7 @@ static void Main() t.InvokeMember("MyProp", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0}); + BindingFlags.Instance | BindingFlags.SetProperty, null, obj, [0]); } catch (TargetInvocationException e) { @@ -81,12 +81,12 @@ static void Main() t.InvokeMember("MyProp", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | - BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2}); - v = (Int32) t.InvokeMember("MyProp", + BindingFlags.Instance | BindingFlags.SetProperty, null, obj, [2]); + v = (int)t.InvokeMember("MyProp", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null); Console.WriteLine("MyProp: " + v); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsAbstract/isabstract1.cs b/snippets/csharp/System/Type/IsAbstract/isabstract1.cs index e8fd4bc0b3b..795f13a3810 100644 --- a/snippets/csharp/System/Type/IsAbstract/isabstract1.cs +++ b/snippets/csharp/System/Type/IsAbstract/isabstract1.cs @@ -2,43 +2,39 @@ using System; public abstract class AbstractClass -{} +{ } public class DerivedClass : AbstractClass -{} +{ } public sealed class SingleClass -{} +{ } public interface ITypeInfo { - string GetName(); + string GetName(); } public class ImplementingClass : ITypeInfo { - public string GetName() - { - return this.GetType().FullName; - } + public string GetName() => this.GetType().FullName; } delegate string InputOutput(string inp); public class Example { - public static void Main() - { - Type[] types= { typeof(AbstractClass), - typeof(DerivedClass), - typeof(ITypeInfo), - typeof(SingleClass), - typeof(ImplementingClass), - typeof(InputOutput) }; - foreach (var type in types) - Console.WriteLine("{0} is abstract: {1}", - type.Name, type.IsAbstract); - } + public static void Main() + { + Type[] types = [typeof(AbstractClass), + typeof(DerivedClass), + typeof(ITypeInfo), + typeof(SingleClass), + typeof(ImplementingClass), + typeof(InputOutput)]; + foreach (var type in types) + Console.WriteLine($"{type.Name} is abstract: {type.IsAbstract}"); + } } // The example displays the following output: // AbstractClass is abstract: True diff --git a/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs b/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs index d42efe9efe2..e5b06e91157 100644 --- a/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs +++ b/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs @@ -3,7 +3,7 @@ using System.Reflection; public class MyClass { - protected string myField = "A sample protected field." ; + protected string myField = "A sample protected field."; } public class MyType_IsAnsiClass { @@ -11,19 +11,19 @@ public static void Main() { try { - MyClass myObject = new MyClass(); + MyClass myObject = new(); // Get the type of the 'MyClass'. Type myType = typeof(MyClass); // Get the field information and the attributes associated with MyClass. - FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.NonPublic|BindingFlags.Instance); - Console.WriteLine( "\nChecking for the AnsiClass attribute for a field.\n"); + FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.NonPublic | BindingFlags.Instance); + Console.WriteLine("\nChecking for the AnsiClass attribute for a field.\n"); // Get and display the name, field, and the AnsiClass attribute. - Console.WriteLine("Name of Class: {0} \nValue of Field: {1} \nIsAnsiClass = {2}", myType.FullName, myFieldInfo.GetValue(myObject), myType.IsAnsiClass); + Console.WriteLine($"Name of Class: {myType.FullName} \nValue of Field: {myFieldInfo.GetValue(myObject)} \nIsAnsiClass = {myType.IsAnsiClass}"); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("Exception: {0}",e.Message); + Console.WriteLine($"Exception: {e.Message}"); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsArray/isarray2.cs b/snippets/csharp/System/Type/IsArray/isarray2.cs index feed53d1423..66907266053 100644 --- a/snippets/csharp/System/Type/IsArray/isarray2.cs +++ b/snippets/csharp/System/Type/IsArray/isarray2.cs @@ -5,16 +5,15 @@ public class Example { - public static void Main() - { - Type[] types = { typeof(String), typeof(int[]), - typeof(ArrayList), typeof(Array), - typeof(List), - typeof(IEnumerable) }; - foreach (var t in types) - Console.WriteLine("{0,-15} IsArray = {1}", t.Name + ":", - t.IsArray); - } + public static void Main() + { + Type[] types = [typeof(string), typeof(int[]), + typeof(ArrayList), typeof(Array), + typeof(List), + typeof(IEnumerable)]; + foreach (var t in types) + Console.WriteLine($"{t.Name + ":",-15} IsArray = {t.IsArray}"); + } } // The example displays the following output: // String: IsArray = False diff --git a/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs b/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs index bf078734e26..4b52c4981fd 100644 --- a/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs +++ b/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs @@ -5,15 +5,12 @@ public class MyTypeDelegator : TypeDelegator { public string myElementType = null; public Type myType; - public MyTypeDelegator(Type myType) : base(myType) - { - this.myType = myType; - } + public MyTypeDelegator(Type myType) : base(myType) => this.myType = myType; // Override IsArrayImpl(). protected override bool IsArrayImpl() { // Determine whether the type is an array. - if(myType.IsArray) + if (myType.IsArray) { myElementType = "array"; return true; @@ -28,27 +25,27 @@ public static void Main() { try { - int myInt = 0 ; + int myInt = 0; // Create an instance of an array element. int[] myArray = new int[5]; - MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType()); + MyTypeDelegator myType = new(myArray.GetType()); Console.WriteLine("\nDetermine whether the variable is an array.\n"); // Determine whether myType is an array type. - if( myType.IsArray) - Console.WriteLine("The type of myArray is {0}.", myType.myElementType); + if (myType.IsArray) + Console.WriteLine($"The type of myArray is {myType.myElementType}."); else Console.WriteLine("myArray is not an array."); - myType = new MyTypeDelegator(myInt.GetType()); + myType = new(myInt.GetType()); // Determine whether myType is an array type. - if( myType.IsArray) - Console.WriteLine("The type of myInt is {0}.", myType.myElementType); + if (myType.IsArray) + Console.WriteLine($"The type of myInt is {myType.myElementType}."); else Console.WriteLine("myInt is not an array."); } - catch( Exception e ) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message ); + Console.WriteLine($"Exception: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs index aa1219c81c6..1571176e7ab 100644 --- a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs +++ b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs @@ -2,18 +2,18 @@ using System; using System.IO; -public class Example +public class IsAssignableFromExample2 { - public static void Main() - { - Type t = typeof(Stream); - Type genericT = typeof(GenericWithConstraint<>); - Type genericParam = genericT.GetGenericArguments()[0]; - Console.WriteLine(t.IsAssignableFrom(genericParam)); - // Displays True. - } + public static void Run() + { + Type t = typeof(Stream); + Type genericT = typeof(GenericWithConstraint<>); + Type genericParam = genericT.GetGenericArguments()[0]; + Console.WriteLine(t.IsAssignableFrom(genericParam)); + // Displays True. + } } public class GenericWithConstraint where T : Stream -{} +{ } // diff --git a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs index 15c10742cc7..8e946b32725 100644 --- a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs +++ b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs @@ -2,19 +2,19 @@ using System; using System.Collections; -public class Example +public class IsAssignableFromExample3 { - public static void Main() - { - Type t = typeof(IEnumerable); - Type c = typeof(Array); - - IEnumerable instanceOfT; - int[] instanceOfC = { 1, 2, 3, 4 }; - if (t.IsAssignableFrom(c)) - // - instanceOfT = instanceOfC; - // - } + public static void Run() + { + Type t = typeof(IEnumerable); + Type c = typeof(Array); + + IEnumerable instanceOfT; + int[] instanceOfC = [1, 2, 3, 4]; + if (t.IsAssignableFrom(c)) + // + instanceOfT = instanceOfC; + // + } } // diff --git a/snippets/csharp/System/Type/IsAssignableFrom/Program.cs b/snippets/csharp/System/Type/IsAssignableFrom/Program.cs new file mode 100644 index 00000000000..b26637a8463 --- /dev/null +++ b/snippets/csharp/System/Type/IsAssignableFrom/Program.cs @@ -0,0 +1,4 @@ +IsAssignableFromExample1.Run(); +IsAssignableFromExample2.Run(); +IsAssignableFromExample3.Run(); +IsAssignableFromTest.Run(); diff --git a/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj b/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs b/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs index 51246e4ac4e..a3bde43aec2 100644 --- a/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs +++ b/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs @@ -4,26 +4,27 @@ using System.Reflection.Emit; public class A -{} +{ } -public class Example +public class IsAssignableFromExample1 { - public static void Main() - { - AppDomain domain = AppDomain.CurrentDomain; - AssemblyName assemName = new AssemblyName(); - assemName.Name = "TempAssembly"; + public static void Run() + { + AssemblyName assemName = new() + { + Name = "TempAssembly" + }; - // Define a dynamic assembly in the current application domain. - AssemblyBuilder assemBuilder = domain.DefineDynamicAssembly(assemName, - AssemblyBuilderAccess.Run); + // Define a dynamic assembly. + AssemblyBuilder assemBuilder = AssemblyBuilder.DefineDynamicAssembly( + assemName, AssemblyBuilderAccess.Run); - // Define a dynamic module in this assembly. - ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("TempModule"); + // Define a dynamic module in this assembly. + ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("TempModule"); - TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A)); - Console.WriteLine(typeof(A).IsAssignableFrom(b1)); - } + TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A)); + Console.WriteLine(typeof(A).IsAssignableFrom(b1)); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs b/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs index eedfa2553f0..3c7161f9043 100644 --- a/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs +++ b/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs @@ -1,64 +1,64 @@ // using System; using System.Collections.Generic; -class Program +class IsAssignableFromTest { - public static void Main() + public static void Run() { - // Demonstrate classes: - Console.WriteLine("Defined Classes:"); - Room room1 = new Room(); - Kitchen kitchen1 = new Kitchen(); - Bedroom bedroom1 = new Bedroom(); - Guestroom guestroom1 = new Guestroom(); - MasterBedroom masterbedroom1 = new MasterBedroom(); - - Type room1Type = room1.GetType(); - Type kitchen1Type = kitchen1.GetType(); - Type bedroom1Type = bedroom1.GetType(); - Type guestroom1Type = guestroom1.GetType(); - Type masterbedroom1Type = masterbedroom1.GetType(); - - Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type)); - Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type)); - Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type)); - - // Demonstrate arrays: - Console.WriteLine(); - Console.WriteLine("Integer arrays:"); - - int[] array2 = new int[2]; - int[] array10 = new int[10]; - int[,] array22 = new int[2, 2]; - int[,] array24 = new int[2, 4]; - - Type array2Type = array2.GetType(); - Type array10Type = array10.GetType(); - Type array22Type = array22.GetType(); - Type array24Type = array24.GetType(); - - Console.WriteLine("int[2] assignable from int[10]: {0}", array2Type.IsAssignableFrom(array10Type)); - Console.WriteLine("int[2] assignable from int[2,4]: {0}", array2Type.IsAssignableFrom(array24Type)); - Console.WriteLine("int[2,4] assignable from int[2,2]: {0}", array24Type.IsAssignableFrom(array22Type)); - - // Demonstrate generics: - Console.WriteLine(); - Console.WriteLine("Generics:"); - - // Note that "int?[]" is the same as "Nullable[]" - int?[] arrayNull = new int?[10]; - List genIntList = new List(); - List genTList = new List(); - - Type arrayNullType = arrayNull.GetType(); - Type genIntListType = genIntList.GetType(); - Type genTListType = genTList.GetType(); - - Console.WriteLine("int[10] assignable from int?[10]: {0}", array10Type.IsAssignableFrom(arrayNullType)); - Console.WriteLine("List assignable from List: {0}", genIntListType.IsAssignableFrom(genTListType)); - Console.WriteLine("List assignable from List: {0}", genTListType.IsAssignableFrom(genIntListType)); - - Console.ReadLine(); + // Demonstrate classes: + Console.WriteLine("Defined Classes:"); + Room room1 = new(); + Kitchen kitchen1 = new(); + Bedroom bedroom1 = new(); + Guestroom guestroom1 = new(); + MasterBedroom masterbedroom1 = new(); + + Type room1Type = room1.GetType(); + Type kitchen1Type = kitchen1.GetType(); + Type bedroom1Type = bedroom1.GetType(); + Type guestroom1Type = guestroom1.GetType(); + Type masterbedroom1Type = masterbedroom1.GetType(); + + Console.WriteLine($"room assignable from kitchen: {room1Type.IsAssignableFrom(kitchen1Type)}"); + Console.WriteLine($"bedroom assignable from guestroom: {bedroom1Type.IsAssignableFrom(guestroom1Type)}"); + Console.WriteLine($"kitchen assignable from masterbedroom: {kitchen1Type.IsAssignableFrom(masterbedroom1Type)}"); + + // Demonstrate arrays: + Console.WriteLine(); + Console.WriteLine("Integer arrays:"); + + int[] array2 = new int[2]; + int[] array10 = new int[10]; + int[,] array22 = new int[2, 2]; + int[,] array24 = new int[2, 4]; + + Type array2Type = array2.GetType(); + Type array10Type = array10.GetType(); + Type array22Type = array22.GetType(); + Type array24Type = array24.GetType(); + + Console.WriteLine($"int[2] assignable from int[10]: {array2Type.IsAssignableFrom(array10Type)}"); + Console.WriteLine($"int[2] assignable from int[2,4]: {array2Type.IsAssignableFrom(array24Type)}"); + Console.WriteLine($"int[2,4] assignable from int[2,2]: {array24Type.IsAssignableFrom(array22Type)}"); + + // Demonstrate generics: + Console.WriteLine(); + Console.WriteLine("Generics:"); + + // Note that "int?[]" is the same as "Nullable[]" + int?[] arrayNull = new int?[10]; + List genIntList = new(); + List genTList = new(); + + Type arrayNullType = arrayNull.GetType(); + Type genIntListType = genIntList.GetType(); + Type genTListType = genTList.GetType(); + + Console.WriteLine($"int[10] assignable from int?[10]: {array10Type.IsAssignableFrom(arrayNullType)}"); + Console.WriteLine($"List assignable from List: {genIntListType.IsAssignableFrom(genTListType)}"); + Console.WriteLine($"List assignable from List: {genTListType.IsAssignableFrom(genIntListType)}"); + + Console.ReadLine(); } } class Room @@ -97,4 +97,4 @@ class MasterBedroom : Bedroom // int[10] assignable from int?[10]: False // List assignable from List: False // List assignable from List: False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs b/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs index 184d4e2dadc..906dbd9bd12 100644 --- a/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs +++ b/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs @@ -13,11 +13,10 @@ public class Example public static void Main() { // Create an instance of the Type class using the GetType method. - Type myType=typeof(Demo); + Type myType = typeof(Demo); // Get and display the IsAutoLayout property of the // Demoinstance. - Console.WriteLine("\nThe AutoLayout property for the Demo class is {0}.", - myType.IsAutoLayout); + Console.WriteLine($"\nThe AutoLayout property for the Demo class is {myType.IsAutoLayout}."); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsClass/type_isclass.cs b/snippets/csharp/System/Type/IsClass/type_isclass.cs index 9898d0a5235..5140bcbb8fc 100644 --- a/snippets/csharp/System/Type/IsClass/type_isclass.cs +++ b/snippets/csharp/System/Type/IsClass/type_isclass.cs @@ -1,8 +1,8 @@ // using System; -using System.Reflection; -public class MyDemoClass + +public class MyDemoClass { } @@ -12,13 +12,13 @@ public static void Main(string[] args) { try { - Type myType = typeof(MyDemoClass); + Type myType = typeof(MyDemoClass); // Get and display the 'IsClass' property of the 'MyDemoClass' instance. - Console.WriteLine("\nIs the specified type a class? {0}.", myType.IsClass); + Console.WriteLine($"\nIs the specified type a class? {myType.IsClass}."); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("\nAn exception occurred: {0}." ,e.Message); + Console.WriteLine($"\nAn exception occurred: {e.Message}."); } } } diff --git a/snippets/csharp/System/Type/IsContextful/Project.csproj b/snippets/csharp/System/Type/IsContextful/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/IsContextful/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs b/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs index 08ebbbb8854..c88c6521f04 100644 --- a/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs +++ b/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs @@ -1,8 +1,8 @@ // using System; -using System.Runtime.Remoting.Contexts; -public class ContextBoundClass: ContextBoundObject + +public class ContextBoundClass : ContextBoundObject { public string Value = "The Value property."; } @@ -11,23 +11,17 @@ public class Example { public static void Main() { - // Determine whether the types can be hosted in a Context. - Console.WriteLine("The IsContextful property for the {0} type is {1}.", - typeof(Example).Name, typeof(Example).IsContextful); - Console.WriteLine("The IsContextful property for the {0} type is {1}.", - typeof(ContextBoundClass).Name, typeof(ContextBoundClass).IsContextful); + // Determine whether the types can be hosted in a Context. + Console.WriteLine($"The IsContextful property for the {typeof(Example).Name} type is {typeof(Example).IsContextful}."); + Console.WriteLine($"The IsContextful property for the {typeof(ContextBoundClass).Name} type is {typeof(ContextBoundClass).IsContextful}."); - // Determine whether the types are marshalled by reference. - Console.WriteLine("The IsMarshalByRef property of {0} is {1}.", - typeof(Example).Name, typeof(Example).IsMarshalByRef); - Console.WriteLine("The IsMarshalByRef property of {0} is {1}.", - typeof(ContextBoundClass).Name, typeof(ContextBoundClass).IsMarshalByRef); + // Determine whether the types are marshalled by reference. + Console.WriteLine($"The IsMarshalByRef property of {typeof(Example).Name} is {typeof(Example).IsMarshalByRef}."); + Console.WriteLine($"The IsMarshalByRef property of {typeof(ContextBoundClass).Name} is {typeof(ContextBoundClass).IsMarshalByRef}."); - // Determine whether the types are primitive datatypes. - Console.WriteLine("{0} is a primitive data type: {1}.", - typeof(int).Name, typeof(int).IsPrimitive); - Console.WriteLine("{0} is a primitive data type: {1}.", - typeof(string).Name, typeof(string).IsPrimitive); + // Determine whether the types are primitive datatypes. + Console.WriteLine($"{typeof(int).Name} is a primitive data type: {typeof(int).IsPrimitive}."); + Console.WriteLine($"{typeof(string).Name} is a primitive data type: {typeof(string).IsPrimitive}."); } } // The example displays the following output: diff --git a/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs b/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs index fc0890ba3af..1e1e69c06ee 100644 --- a/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs +++ b/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs @@ -4,17 +4,14 @@ public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; - private Type myType = null ; + private Type myType = null; - public MyTypeDelegatorClass(Type myType) : base(myType) - { - this.myType = myType; - } + public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType; // Override IsContextfulImpl. protected override bool IsContextfulImpl() { // Check whether the type is contextful. - if(myType.IsContextful) + if (myType.IsContextful) { myElementType = " is contextful "; return true; @@ -29,10 +26,10 @@ public static void Main() try { MyTypeDelegatorClass myType; - Console.WriteLine ("Check whether MyContextBoundClass can be hosted in a context."); + Console.WriteLine("Check whether MyContextBoundClass can be hosted in a context."); // Check whether MyContextBoundClass is contextful. - myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass)); - if( myType.IsContextful) + myType = new(typeof(MyContextBoundClass)); + if (myType.IsContextful) { Console.WriteLine(typeof(MyContextBoundClass) + " can be hosted in a context."); } @@ -41,9 +38,9 @@ public static void Main() Console.WriteLine(typeof(MyContextBoundClass) + " cannot be hosted in a context."); } // Check whether the int type is contextful. - myType = new MyTypeDelegatorClass(typeof(MyTypeDemoClass)); - Console.WriteLine ("\nCheck whether MyTypeDemoClass can be hosted in a context."); - if( myType.IsContextful) + myType = new(typeof(MyTypeDemoClass)); + Console.WriteLine("\nCheck whether MyTypeDemoClass can be hosted in a context."); + if (myType.IsContextful) { Console.WriteLine(typeof(MyTypeDemoClass) + " can be hosted in a context."); } @@ -52,9 +49,9 @@ public static void Main() Console.WriteLine(typeof(MyTypeDemoClass) + " cannot be hosted in a context."); } } - catch( Exception e ) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message); + Console.WriteLine($"Exception: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/IsEnum/testisenum.cs b/snippets/csharp/System/Type/IsEnum/testisenum.cs index e084641434e..9881e6d3d21 100644 --- a/snippets/csharp/System/Type/IsEnum/testisenum.cs +++ b/snippets/csharp/System/Type/IsEnum/testisenum.cs @@ -7,13 +7,13 @@ class TestIsEnum { public static void Main() { - Type colorType = typeof(Color); - Type enumType = typeof(Enum); - Console.WriteLine("Is Color an enum? {0}.", colorType.IsEnum); - Console.WriteLine("Is Color a value type? {0}.", colorType.IsValueType); - Console.WriteLine("Is Enum an enum Type? {0}.", enumType.IsEnum); - Console.WriteLine("Is Enum a value type? {0}.", enumType.IsValueType); - } + Type colorType = typeof(Color); + Type enumType = typeof(Enum); + Console.WriteLine($"Is Color an enum? {colorType.IsEnum}."); + Console.WriteLine($"Is Color a value type? {colorType.IsValueType}."); + Console.WriteLine($"Is Enum an enum Type? {enumType.IsEnum}."); + Console.WriteLine($"Is Enum a value type? {enumType.IsValueType}."); + } } // The example displays the following output: // Is Color an enum? True. diff --git a/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs b/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs index 7993cb6d7b3..2ba10268f88 100644 --- a/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs +++ b/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs @@ -1,21 +1,21 @@ // using System; -using System.Reflection; -using System.ComponentModel; + + using System.Runtime.InteropServices; // Class to test for the ExplicitLayout property. -[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)] +[StructLayout(LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi)] public class MySystemTime { - [FieldOffset(0)]public ushort wYear; - [FieldOffset(2)]public ushort wMonth; - [FieldOffset(4)]public ushort wDayOfWeek; - [FieldOffset(6)]public ushort wDay; - [FieldOffset(8)]public ushort wHour; - [FieldOffset(10)]public ushort wMinute; - [FieldOffset(12)]public ushort wSecond; - [FieldOffset(14)]public ushort wMilliseconds; + [FieldOffset(0)] public ushort wYear; + [FieldOffset(2)] public ushort wMonth; + [FieldOffset(4)] public ushort wDayOfWeek; + [FieldOffset(6)] public ushort wDay; + [FieldOffset(8)] public ushort wHour; + [FieldOffset(10)] public ushort wMinute; + [FieldOffset(12)] public ushort wSecond; + [FieldOffset(14)] public ushort wMilliseconds; } public class Program @@ -23,10 +23,9 @@ public class Program public static void Main(string[] args) { // Create an instance of the type using the GetType method. - Type t = typeof(MySystemTime); + Type t = typeof(MySystemTime); // Get and display the IsExplicitLayout property. - Console.WriteLine("\nIsExplicitLayout for MySystemTime is {0}.", - t.IsExplicitLayout); + Console.WriteLine($"\nIsExplicitLayout for MySystemTime is {t.IsExplicitLayout}."); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsGenericParameter/source.cs b/snippets/csharp/System/Type/IsGenericParameter/source.cs index aff8b688c19..b129230bb08 100644 --- a/snippets/csharp/System/Type/IsGenericParameter/source.cs +++ b/snippets/csharp/System/Type/IsGenericParameter/source.cs @@ -1,19 +1,17 @@ // using System; -using System.Reflection; + using System.Collections.Generic; public class Test { private static void DisplayGenericTypeInfo(Type t) { - Console.WriteLine("\r\n{0}", t); + Console.WriteLine($"\r\n{t}"); - Console.WriteLine("\tIs this a generic type definition? {0}", - t.IsGenericTypeDefinition); + Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"); - Console.WriteLine("\tIs it a generic type? {0}", - t.IsGenericType); + Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}"); // if (t.IsGenericType) @@ -22,8 +20,7 @@ private static void DisplayGenericTypeInfo(Type t) // Type[] typeArguments = t.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", - typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { @@ -32,13 +29,11 @@ private static void DisplayGenericTypeInfo(Type t) // if (tParam.IsGenericParameter) { - Console.WriteLine("\t\t{0}\t(unassigned - parameter position {1})", - tParam, - tParam.GenericParameterPosition); + Console.WriteLine($"\t\t{tParam}\t(unassigned - parameter position {tParam.GenericParameterPosition})"); } else { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } @@ -51,8 +46,8 @@ public static void Main() Console.WriteLine(" generic type definition, and an ordinary type."); // Create a Dictionary of Test objects, using strings for the - // keys. - Dictionary d = new Dictionary(); + // keys. + Dictionary d = new(); // Display information for the constructed type and its generic // type definition. diff --git a/snippets/csharp/System/Type/IsGenericType/Program.cs b/snippets/csharp/System/Type/IsGenericType/Program.cs new file mode 100644 index 00000000000..dd1327fdd6d --- /dev/null +++ b/snippets/csharp/System/Type/IsGenericType/Program.cs @@ -0,0 +1,2 @@ +IsGenericTypeRemarksExample.Run(); +IsGenericTypeSourceExample.Run(); diff --git a/snippets/csharp/System/Type/IsGenericType/Project.csproj b/snippets/csharp/System/Type/IsGenericType/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Type/IsGenericType/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Type/IsGenericType/remarks.cs b/snippets/csharp/System/Type/IsGenericType/remarks.cs index bfa44897d58..ec533145f53 100644 --- a/snippets/csharp/System/Type/IsGenericType/remarks.cs +++ b/snippets/csharp/System/Type/IsGenericType/remarks.cs @@ -1,22 +1,22 @@ -using System; -using System.Reflection; + + // -public class Base {} +public class RemarksBase { } -public class Derived : Base +public class RemarksDerived : RemarksBase { - public G> F; + public RemarksG> F; - public class Nested {} + public class Nested { } } -public class G {} +public class RemarksG { } // -class Example +class IsGenericTypeRemarksExample { - public static void Main() + public static void Run() { } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Type/IsGenericType/source.cs b/snippets/csharp/System/Type/IsGenericType/source.cs index da802f2948b..a2b5dc7a56f 100644 --- a/snippets/csharp/System/Type/IsGenericType/source.cs +++ b/snippets/csharp/System/Type/IsGenericType/source.cs @@ -1,21 +1,21 @@ // using System; -using System.Reflection; -public class Base {} + +public class Base { } public class Derived : Base { - public G> F; + public G> F; - public class Nested {} + public class Nested { } } -public class G {} +public class G { } -class Example +class IsGenericTypeSourceExample { - public static void Main() + public static void Run() { // Get the generic type definition for Derived, and the base // type for Derived. @@ -48,17 +48,13 @@ public static void Main() public static void DisplayGenericType(Type t, string caption) { - Console.WriteLine("\n{0}", caption); - Console.WriteLine(" Type: {0}", t); - - Console.WriteLine("\t IsGenericType: {0}", - t.IsGenericType); - Console.WriteLine("\t IsGenericTypeDefinition: {0}", - t.IsGenericTypeDefinition); - Console.WriteLine("\tContainsGenericParameters: {0}", - t.ContainsGenericParameters); - Console.WriteLine("\t IsGenericParameter: {0}", - t.IsGenericParameter); + Console.WriteLine($"\n{caption}"); + Console.WriteLine($" Type: {t}"); + + Console.WriteLine($"\t IsGenericType: {t.IsGenericType}"); + Console.WriteLine($"\t IsGenericTypeDefinition: {t.IsGenericTypeDefinition}"); + Console.WriteLine($"\tContainsGenericParameters: {t.ContainsGenericParameters}"); + Console.WriteLine($"\t IsGenericParameter: {t.IsGenericParameter}"); } } diff --git a/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs b/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs index 580f0dd5afa..04423ff0798 100644 --- a/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs +++ b/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs @@ -1,11 +1,11 @@ // using System; -public interface IExample {} +public interface IExample { } -public class BaseClass : IExample {} +public class BaseClass : IExample { } -public class DerivedClass : BaseClass {} +public class DerivedClass : BaseClass { } public class Example { @@ -18,16 +18,11 @@ public static void Main() var derived1Type = derived1.GetType(); int[] arr = new int[11]; - Console.WriteLine("Is int[] an instance of the Array class? {0}.", - typeof(Array).IsInstanceOfType(arr)); - Console.WriteLine("Is base1 an instance of BaseClass? {0}.", - base1Type.IsInstanceOfType(base1)); - Console.WriteLine("Is derived1 an instance of BaseClass? {0}.", - base1Type.IsInstanceOfType(derived1)); - Console.WriteLine("Is base1 an instance of IExample? {0}.", - interfaceType.IsInstanceOfType(base1)); - Console.WriteLine("Is derived1 an instance of IExample? {0}.", - interfaceType.IsInstanceOfType(derived1)); + Console.WriteLine($"Is int[] an instance of the Array class? {typeof(Array).IsInstanceOfType(arr)}."); + Console.WriteLine($"Is base1 an instance of BaseClass? {base1Type.IsInstanceOfType(base1)}."); + Console.WriteLine($"Is derived1 an instance of BaseClass? {base1Type.IsInstanceOfType(derived1)}."); + Console.WriteLine($"Is base1 an instance of IExample? {interfaceType.IsInstanceOfType(base1)}."); + Console.WriteLine($"Is derived1 an instance of IExample? {interfaceType.IsInstanceOfType(derived1)}."); } } // The example displays the following output: @@ -36,4 +31,4 @@ public static void Main() // Is derived1 an instance of BaseClass? True. // Is base1 an instance of IExample? True. // Is derived1 an instance of IExample? True. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsInterface/type_isinterface.cs b/snippets/csharp/System/Type/IsInterface/type_isinterface.cs index 555886437f5..da7ae8eca29 100644 --- a/snippets/csharp/System/Type/IsInterface/type_isinterface.cs +++ b/snippets/csharp/System/Type/IsInterface/type_isinterface.cs @@ -6,22 +6,22 @@ interface myIFace } class MyIsInterface { - public static void Main(string []args) + public static void Main(string[] args) { try { // Get the IsInterface attribute for myIFace. bool myBool1 = typeof(myIFace).IsInterface; //Display the IsInterface attribute for myIFace. - Console.WriteLine("Is the specified type an interface? {0}.", myBool1); + Console.WriteLine($"Is the specified type an interface? {myBool1}."); // Get the attribute IsInterface for MyIsInterface. bool myBool2 = typeof(MyIsInterface).IsInterface; //Display the IsInterface attribute for MyIsInterface. - Console.WriteLine("Is the specified type an interface? {0}.", myBool2); + Console.WriteLine($"Is the specified type an interface? {myBool2}."); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("\nAn exception occurred: {0}.", e.Message); + Console.WriteLine($"\nAn exception occurred: {e.Message}."); } } } @@ -30,4 +30,4 @@ public static void Main(string []args) Is the specified type an interface? True. Is the specified type an interface? False. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs b/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs index 1b37af41198..efb0c46cf9f 100644 --- a/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs +++ b/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs @@ -1,7 +1,7 @@ // using System; -using System.Reflection; -using System.ComponentModel; + + using System.Runtime.InteropServices; class MyTypeSequential1 { @@ -9,24 +9,24 @@ class MyTypeSequential1 [StructLayoutAttribute(LayoutKind.Sequential)] class MyTypeSequential2 { - public static void Main(string []args) + public static void Main(string[] args) { try { // Create an instance of myTypeSeq1. - MyTypeSequential1 myObj1 = new MyTypeSequential1(); + MyTypeSequential1 myObj1 = new(); Type myTypeObj1 = myObj1.GetType(); // Check for and display the SequentialLayout attribute. - Console.WriteLine("\nThe object myObj1 has IsLayoutSequential: {0}.", myObj1.GetType().IsLayoutSequential); + Console.WriteLine($"\nThe object myObj1 has IsLayoutSequential: {myObj1.GetType().IsLayoutSequential}."); // Create an instance of 'myTypeSeq2' class. - MyTypeSequential2 myObj2 = new MyTypeSequential2(); + MyTypeSequential2 myObj2 = new(); Type myTypeObj2 = myObj2.GetType(); // Check for and display the SequentialLayout attribute. - Console.WriteLine("\nThe object myObj2 has IsLayoutSequential: {0}.", myObj2.GetType().IsLayoutSequential); + Console.WriteLine($"\nThe object myObj2 has IsLayoutSequential: {myObj2.GetType().IsLayoutSequential}."); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("\nAn exception occurred: {0}", e.Message); + Console.WriteLine($"\nAn exception occurred: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs b/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs index 02eb5237740..1a46e14a2a4 100644 --- a/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs +++ b/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs @@ -4,16 +4,13 @@ public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; - private Type myType = null ; - public MyTypeDelegatorClass(Type myType) : base(myType) - { - this.myType = myType; - } + private Type myType = null; + public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType; // Override IsMarshalByRefImpl. protected override bool IsMarshalByRefImpl() { // Determine whether the type is marshalled by reference. - if(myType.IsMarshalByRef) + if (myType.IsMarshalByRef) { myElementType = " marshalled by reference"; return true; @@ -28,10 +25,10 @@ public static void Main() try { MyTypeDelegatorClass myType; - Console.WriteLine ("Determine whether MyContextBoundClass is marshalled by reference."); + Console.WriteLine("Determine whether MyContextBoundClass is marshalled by reference."); // Determine whether MyContextBoundClass type is marshalled by reference. - myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass)); - if( myType.IsMarshalByRef ) + myType = new(typeof(MyContextBoundClass)); + if (myType.IsMarshalByRef) { Console.WriteLine(typeof(MyContextBoundClass) + " is marshalled by reference."); } @@ -41,9 +38,9 @@ public static void Main() } // Determine whether int type is marshalled by reference. - myType = new MyTypeDelegatorClass(typeof(int)); - Console.WriteLine ("\nDetermine whether int is marshalled by reference."); - if( myType.IsMarshalByRef) + myType = new(typeof(int)); + Console.WriteLine("\nDetermine whether int is marshalled by reference."); + if (myType.IsMarshalByRef) { Console.WriteLine(typeof(int) + " is marshalled by reference."); } @@ -52,9 +49,9 @@ public static void Main() Console.WriteLine(typeof(int) + " is not marshalled by reference."); } } - catch( Exception e ) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message); + Console.WriteLine($"Exception: {e.Message}"); } } } diff --git a/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs b/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs index 46513f3d2d6..ef1cedea827 100644 --- a/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs +++ b/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs @@ -5,41 +5,42 @@ public class OuterClass { private class PrivateClass - {} + { } protected class ProtectedClass - {} + { } internal class InternalClass - {} + { } protected internal class ProtectedInternalClass - {} + { } public class PublicClass - {} + { } public static void Main() { // Create an array of Type objects for all the classes. - Type[] types = { typeof(OuterClass), - typeof(OuterClass.PublicClass), - typeof(OuterClass.PrivateClass), - typeof(OuterClass.ProtectedClass), - typeof(OuterClass.InternalClass), - typeof(OuterClass.ProtectedInternalClass) }; + Type[] types = [typeof(OuterClass), + typeof(OuterClass.PublicClass), + typeof(OuterClass.PrivateClass), + typeof(OuterClass.ProtectedClass), + typeof(OuterClass.InternalClass), + typeof(OuterClass.ProtectedInternalClass)]; // Display the property values of each nested class. - foreach (var type in types) { - Console.WriteLine("\n{0} property values:", type.Name); - Console.WriteLine(" Public Class: {0}", type.IsPublic); - Console.WriteLine(" Not a Public Class: {0}", type.IsNotPublic); - Console.WriteLine(" Nested Class: {0}", type.IsNested); - Console.WriteLine(" Nested Private Class: {0}", type.IsNestedPrivate); - Console.WriteLine(" Nested Internal Class: {0}", type.IsNestedAssembly); - Console.WriteLine(" Nested Protected Class: {0}", type.IsNestedFamily); - Console.WriteLine(" Nested Family Or Assembly Class: {0}", type.IsNestedFamORAssem); - Console.WriteLine(" Nested Family And Assembly Class: {0}", type.IsNestedFamANDAssem); - Console.WriteLine(" Nested Public Class: {0}", type.IsNestedPublic); + foreach (var type in types) + { + Console.WriteLine($"\n{type.Name} property values:"); + Console.WriteLine($" Public Class: {type.IsPublic}"); + Console.WriteLine($" Not a Public Class: {type.IsNotPublic}"); + Console.WriteLine($" Nested Class: {type.IsNested}"); + Console.WriteLine($" Nested Private Class: {type.IsNestedPrivate}"); + Console.WriteLine($" Nested Internal Class: {type.IsNestedAssembly}"); + Console.WriteLine($" Nested Protected Class: {type.IsNestedFamily}"); + Console.WriteLine($" Nested Family Or Assembly Class: {type.IsNestedFamORAssem}"); + Console.WriteLine($" Nested Family And Assembly Class: {type.IsNestedFamANDAssem}"); + Console.WriteLine($" Nested Public Class: {type.IsNestedPublic}"); } } } @@ -109,4 +110,4 @@ public static void Main() // Nested Family Or Assembly Class: True // Nested Family And Assembly Class: False // Nested Public Class: False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsNotPublic/source.cs b/snippets/csharp/System/Type/IsNotPublic/source.cs index 2076d9f9ff1..7f12663f242 100644 --- a/snippets/csharp/System/Type/IsNotPublic/source.cs +++ b/snippets/csharp/System/Type/IsNotPublic/source.cs @@ -1,6 +1,6 @@ // using System; -using System.IO; + using System.Reflection; class Example @@ -11,10 +11,8 @@ public static void Main() Type t = Type.GetType("System.IO.File"); MemberInfo[] members = t.GetMembers(); // Get and display the DeclaringType method. - Console.WriteLine("\nThere are {0} members in {1}.", - members.Length, t.FullName); - Console.WriteLine("Is {0} non-public? {1}", - t.FullName, t.IsNotPublic); + Console.WriteLine($"\nThere are {members.Length} members in {t.FullName}."); + Console.WriteLine($"Is {t.FullName} non-public? {t.IsNotPublic}"); } } // The example displays output like the following: diff --git a/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs b/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs index 9dd4c38e560..9d4072cffe3 100644 --- a/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs +++ b/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs @@ -4,16 +4,13 @@ public class MyTypeDelegatorClass : TypeDelegator { public string myElementType = null; - private Type myType = null ; - public MyTypeDelegatorClass(Type myType) : base(myType) - { - this.myType = myType; - } + private Type myType = null; + public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType; // Override the IsPrimitiveImpl. protected override bool IsPrimitiveImpl() { // Determine whether the type is a primitive type. - if(myType.IsPrimitive) + if (myType.IsPrimitive) { myElementType = "primitive"; return true; @@ -27,11 +24,11 @@ public static void Main() { try { - Console.WriteLine ("Determine whether int is a primitive type."); + Console.WriteLine("Determine whether int is a primitive type."); MyTypeDelegatorClass myType; - myType = new MyTypeDelegatorClass(typeof(int)); + myType = new(typeof(int)); // Determine whether int is a primitive type. - if( myType.IsPrimitive) + if (myType.IsPrimitive) { Console.WriteLine(typeof(int) + " is a primitive type."); } @@ -39,10 +36,10 @@ public static void Main() { Console.WriteLine(typeof(int) + " is not a primitive type."); } - Console.WriteLine ("\nDetermine whether string is a primitive type."); - myType = new MyTypeDelegatorClass(typeof(string)); + Console.WriteLine("\nDetermine whether string is a primitive type."); + myType = new(typeof(string)); // Determine if string is a primitive type. - if( myType.IsPrimitive) + if (myType.IsPrimitive) { Console.WriteLine(typeof(string) + " is a primitive type."); } @@ -51,10 +48,10 @@ public static void Main() Console.WriteLine(typeof(string) + " is not a primitive type."); } } - catch( Exception e ) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message); + Console.WriteLine($"Exception: {e.Message}"); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsPublic/type_ispublic.cs b/snippets/csharp/System/Type/IsPublic/type_ispublic.cs index 40c87ffc257..ad92c0f08e9 100644 --- a/snippets/csharp/System/Type/IsPublic/type_ispublic.cs +++ b/snippets/csharp/System/Type/IsPublic/type_ispublic.cs @@ -7,15 +7,15 @@ public class TestClass public class Example { - public static void Main() - { - TestClass testClassInstance = new TestClass(); - // Get the type of myTestClassInstance. - Type testType = testClassInstance.GetType(); - // Get the IsPublic property of testClassInstance. - bool isPublic = testType.IsPublic; - Console.WriteLine("Is {0} public? {1}", testType.FullName, isPublic); - } + public static void Main() + { + TestClass testClassInstance = new(); + // Get the type of myTestClassInstance. + Type testType = testClassInstance.GetType(); + // Get the IsPublic property of testClassInstance. + bool isPublic = testType.IsPublic; + Console.WriteLine($"Is {testType.FullName} public? {isPublic}"); + } } // The example displays the following output: // Is TestClass public? True diff --git a/snippets/csharp/System/Type/IsSealed/type_issealed.cs b/snippets/csharp/System/Type/IsSealed/type_issealed.cs index 90ddf688fc3..587338a1280 100644 --- a/snippets/csharp/System/Type/IsSealed/type_issealed.cs +++ b/snippets/csharp/System/Type/IsSealed/type_issealed.cs @@ -1,23 +1,23 @@ // using System; - public class Example - { - // Declare InnerClass as sealed. - sealed public class InnerClass - { - } +public class Example +{ + // Declare InnerClass as sealed. + sealed public class InnerClass + { + } - public static void Main() - { - InnerClass inner = new InnerClass(); - // Get the type of InnerClass. - Type innerType = inner.GetType(); - // Get the IsSealed property of innerClass. - bool isSealed = innerType.IsSealed; - Console.WriteLine("{0} is sealed: {1}.", innerType.FullName, isSealed); - } + public static void Main() + { + InnerClass inner = new(); + // Get the type of InnerClass. + Type innerType = inner.GetType(); + // Get the IsSealed property of innerClass. + bool isSealed = innerType.IsSealed; + Console.WriteLine($"{innerType.FullName} is sealed: {isSealed}."); + } } // The example displays the following output: // Example+InnerClass is sealed: True. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs b/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs index 37ff4c1c38c..eecfa854b24 100644 --- a/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs +++ b/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs @@ -3,28 +3,23 @@ public interface IInterface { - void Display(); + void Display(); } public class Implementation : IInterface { - public void Display() - { - Console.WriteLine("The implementation..."); - } + public void Display() => Console.WriteLine("The implementation..."); } public class Example { - public static void Main() - { - Console.WriteLine("Implementation is a subclass of IInterface: {0}", - typeof(Implementation).IsSubclassOf(typeof(IInterface))); - Console.WriteLine("IInterface is assignable from Implementation: {0}", - typeof(IInterface).IsAssignableFrom(typeof(Implementation))); - } + public static void Main() + { + Console.WriteLine($"Implementation is a subclass of IInterface: {typeof(Implementation).IsSubclassOf(typeof(IInterface))}"); + Console.WriteLine($"IInterface is assignable from Implementation: {typeof(IInterface).IsAssignableFrom(typeof(Implementation))}"); + } } // The example displays the following output: // Implementation is a subclass of IInterface: False // IInterface is assignable from Implementation: True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs b/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs index 24d67175f8c..45b923c27ac 100644 --- a/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs +++ b/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs @@ -6,12 +6,8 @@ public class DerivedC1 : Class1 { } class IsSubclassTest { - public static void Main() - { - Console.WriteLine("DerivedC1 subclass of Class1: {0}", - typeof(DerivedC1).IsSubclassOf(typeof(Class1))); - } + public static void Main() => Console.WriteLine($"DerivedC1 subclass of Class1: {typeof(DerivedC1).IsSubclassOf(typeof(Class1))}"); } // The example displays the following output: // DerivedC1 subclass of Class1: True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs b/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs index 79ba552d617..07c9ff64260 100644 --- a/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs +++ b/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs @@ -7,7 +7,7 @@ enum NumEnum { One, Two } public class Example { - public static void Main(string []args) + public static void Main(string[] args) { bool flag = false; NumEnum testEnum = NumEnum.One; @@ -15,7 +15,7 @@ public static void Main(string []args) Type t = testEnum.GetType(); // Get the IsValueType property of the testEnum variable. flag = t.IsValueType; - Console.WriteLine("{0} is a value type: {1}", t.FullName, flag); + Console.WriteLine($"{t.FullName} is a value type: {flag}"); } } // The example displays the following output: diff --git a/snippets/csharp/System/Type/IsVisible/source.cs b/snippets/csharp/System/Type/IsVisible/source.cs index 66278859ddc..39fc211220f 100644 --- a/snippets/csharp/System/Type/IsVisible/source.cs +++ b/snippets/csharp/System/Type/IsVisible/source.cs @@ -1,30 +1,22 @@ // using System; -internal class InternalOnly +internal class InternalOnly { - public class Nested {} + public class Nested { } } public class Example { - public class Nested {} + public class Nested { } public static void Main() { Type t = typeof(InternalOnly.Nested); - Console.WriteLine( - "Is the {0} class visible outside the assembly? {1}", - t.FullName, - t.IsVisible - ); + Console.WriteLine($"Is the {t.FullName} class visible outside the assembly? {t.IsVisible}"); t = typeof(Example.Nested); - Console.WriteLine( - "Is the {0} class visible outside the assembly? {1}", - t.FullName, - t.IsVisible - ); + Console.WriteLine($"Is the {t.FullName} class visible outside the assembly? {t.IsVisible}"); } } diff --git a/snippets/csharp/System/Type/MakeByRefType/source.cs b/snippets/csharp/System/Type/MakeByRefType/source.cs index 7a9ee920685..d58029186c5 100644 --- a/snippets/csharp/System/Type/MakeByRefType/source.cs +++ b/snippets/csharp/System/Type/MakeByRefType/source.cs @@ -9,12 +9,12 @@ public static void Main() // Create a Type object that represents a one-dimensional // array of Example objects. Type t = typeof(Example).MakeArrayType(); - Console.WriteLine("\r\nArray of Example: {0}", t); + Console.WriteLine($"\r\nArray of Example: {t}"); // Create a Type object that represents a two-dimensional // array of Example objects. t = typeof(Example).MakeArrayType(2); - Console.WriteLine("\r\nTwo-dimensional array of Example: {0}", t); + Console.WriteLine($"\r\nTwo-dimensional array of Example: {t}"); // Demonstrate an exception when an invalid array rank is // specified. @@ -22,15 +22,15 @@ public static void Main() { t = typeof(Example).MakeArrayType(-1); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("\r\n{0}", ex); + Console.WriteLine($"\r\n{ex}"); } // Create a Type object that represents a ByRef parameter // of type Example. t = typeof(Example).MakeByRefType(); - Console.WriteLine("\r\nByRef Example: {0}", t); + Console.WriteLine($"\r\nByRef Example: {t}"); // Get a Type object representing the Example class, a // MethodInfo representing the "Test" method, a ParameterInfo @@ -42,12 +42,12 @@ public static void Main() MethodInfo mi = t2.GetMethod("Test"); ParameterInfo pi = mi.GetParameters()[0]; Type pt = pi.ParameterType; - Console.WriteLine("Are the ByRef types equal? {0}", (t == pt)); + Console.WriteLine($"Are the ByRef types equal? {(t == pt)}"); // Create a Type object that represents a pointer to an // Example object. t = typeof(Example).MakePointerType(); - Console.WriteLine("\r\nPointer to Example: {0}", t); + Console.WriteLine($"\r\nPointer to Example: {t}"); } // A sample method with a ByRef parameter. diff --git a/snippets/csharp/System/Type/MakeGenericType/remarks.cs b/snippets/csharp/System/Type/MakeGenericType/remarks.cs index a9f8c04adb2..a6e7734a444 100644 --- a/snippets/csharp/System/Type/MakeGenericType/remarks.cs +++ b/snippets/csharp/System/Type/MakeGenericType/remarks.cs @@ -1,4 +1,4 @@ -using System; + // public class Base { } @@ -10,13 +10,13 @@ public class Outermost { public class Inner { - public class Innermost1 {} - public class Innermost2 {} + public class Innermost1 { } + public class Innermost2 { } } } // class ProgStubClass { - public static void Main() {} -} \ No newline at end of file + public static void Main() { } +} diff --git a/snippets/csharp/System/Type/MakeGenericType/source.cs b/snippets/csharp/System/Type/MakeGenericType/source.cs index 38ecc20de1c..357c5c9b176 100644 --- a/snippets/csharp/System/Type/MakeGenericType/source.cs +++ b/snippets/csharp/System/Type/MakeGenericType/source.cs @@ -1,6 +1,6 @@ // using System; -using System.Reflection; + using System.Collections.Generic; public class Test @@ -9,17 +9,17 @@ public static void Main() { Console.WriteLine("\r\n--- Create a constructed type from the generic Dictionary type."); - // Create a type object representing the generic Dictionary - // type, by omitting the type arguments (but keeping the + // Create a type object representing the generic Dictionary + // type, by omitting the type arguments (but keeping the // comma that separates them, so the compiler can infer the - // number of type parameters). + // number of type parameters). Type generic = typeof(Dictionary<,>); DisplayTypeInfo(generic); // Create an array of types to substitute for the type // parameters of Dictionary. The key is of type string, and // the type to be contained in the Dictionary is Test. - Type[] typeArgs = { typeof(string), typeof(Test) }; + Type[] typeArgs = [typeof(string), typeof(Test)]; // Create a Type object representing the constructed generic // type. @@ -30,27 +30,24 @@ public static void Main() // obtained using typeof() and GetGenericTypeDefinition(). Console.WriteLine("\r\n--- Compare types obtained by different methods:"); - Type t = typeof(Dictionary); - Console.WriteLine("\tAre the constructed types equal? {0}", t == constructed); - Console.WriteLine("\tAre the generic types equal? {0}", - t.GetGenericTypeDefinition() == generic); + Type t = typeof(Dictionary); + Console.WriteLine($"\tAre the constructed types equal? {t == constructed}"); + Console.WriteLine($"\tAre the generic types equal? {t.GetGenericTypeDefinition() == generic}"); } private static void DisplayTypeInfo(Type t) { - Console.WriteLine("\r\n{0}", t); + Console.WriteLine($"\r\n{t}"); - Console.WriteLine("\tIs this a generic type definition? {0}", - t.IsGenericTypeDefinition); + Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"); - Console.WriteLine("\tIs it a generic type? {0}", - t.IsGenericType); + Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}"); Type[] typeArguments = t.GetGenericArguments(); - Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length); + Console.WriteLine($"\tList type arguments ({typeArguments.Length}):"); foreach (Type tParam in typeArguments) { - Console.WriteLine("\t\t{0}", tParam); + Console.WriteLine($"\t\t{tParam}"); } } } diff --git a/snippets/csharp/System/Type/Missing/Project.csproj b/snippets/csharp/System/Type/Missing/Project.csproj new file mode 100644 index 00000000000..fca009c3149 --- /dev/null +++ b/snippets/csharp/System/Type/Missing/Project.csproj @@ -0,0 +1,9 @@ + + + Exe + net10.0 + + + + + diff --git a/snippets/csharp/System/Type/Missing/source.cs b/snippets/csharp/System/Type/Missing/source.cs index 76b60861815..4f718aac1fd 100644 --- a/snippets/csharp/System/Type/Missing/source.cs +++ b/snippets/csharp/System/Type/Missing/source.cs @@ -27,9 +27,9 @@ public static void Main() BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding; - t.InvokeMember("MyMethod", bf, null, o, new object[] {10, 55.3, 12}); - t.InvokeMember("MyMethod", bf, null, o, new object[] {10, 1.3, Type.Missing}); - t.InvokeMember("MyMethod", bf, null, o, new object[] {10, Type.Missing, Type.Missing}); + t.InvokeMember("MyMethod", bf, null, o, [10, 55.3, 12]); + t.InvokeMember("MyMethod", bf, null, o, [10, 1.3, Type.Missing]); + t.InvokeMember("MyMethod", bf, null, o, [10, Type.Missing, Type.Missing]); } private static object GenerateObjectFromSource(string objectName, @@ -37,10 +37,11 @@ private static object GenerateObjectFromSource(string objectName, { object genObject = null; CodeDomProvider codeProvider = CodeDomProvider.CreateProvider(providerName); - CompilerParameters cp = new CompilerParameters(); - - cp.GenerateExecutable = false; - cp.GenerateInMemory = true; + CompilerParameters cp = new() + { + GenerateExecutable = false, + GenerateInMemory = true + }; CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, sourceLines); @@ -52,4 +53,4 @@ private static object GenerateObjectFromSource(string objectName, return genObject; } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/Module/type_tostring.cs b/snippets/csharp/System/Type/Module/type_tostring.cs index fe2b9678d35..842d6a8883c 100644 --- a/snippets/csharp/System/Type/Module/type_tostring.cs +++ b/snippets/csharp/System/Type/Module/type_tostring.cs @@ -1,4 +1,4 @@ -// +// using System; namespace MyNamespace @@ -12,14 +12,14 @@ public class Example { public static void Main() { - Type myType = typeof(MyNamespace.MyClass); - Console.WriteLine("Displaying information about {0}:", myType); - // Get the namespace of the myClass class. - Console.WriteLine(" Namespace: {0}.", myType.Namespace); - // Get the name of the module. - Console.WriteLine(" Module: {0}.", myType.Module); - // Get the fully qualified type name. - Console.WriteLine(" Fully qualified name: {0}.", myType.ToString()); + Type myType = typeof(MyNamespace.MyClass); + Console.WriteLine($"Displaying information about {myType}:"); + // Get the namespace of the myClass class. + Console.WriteLine($" Namespace: {myType.Namespace}."); + // Get the name of the module. + Console.WriteLine($" Module: {myType.Module}."); + // Get the fully qualified type name. + Console.WriteLine($" Fully qualified name: {myType}."); } } // The example displays the following output: @@ -27,4 +27,4 @@ public static void Main() // Namespace: MyNamespace. // Module: type_tostring.exe. // Fully qualified name: MyNamespace.MyClass. -// +// diff --git a/snippets/csharp/System/Type/Overview/Equals1.cs b/snippets/csharp/System/Type/Overview/Equals1.cs index e3a44d20d3f..ea5f7fc2644 100644 --- a/snippets/csharp/System/Type/Overview/Equals1.cs +++ b/snippets/csharp/System/Type/Overview/Equals1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -14,9 +14,9 @@ public static void Main() Type t = number1.GetType(); // Compare types of all objects with number1. - Console.WriteLine($"Type of number1 and number2 are equal: {Object.ReferenceEquals(t, number2.GetType())}"); - Console.WriteLine($"Type of number1 and number3 are equal: {Object.ReferenceEquals(t, number3.GetType())}"); - Console.WriteLine($"Type of number1 and number4 are equal: {Object.ReferenceEquals(t, number4.GetType())}"); + Console.WriteLine($"Type of number1 and number2 are equal: {object.ReferenceEquals(t, number2.GetType())}"); + Console.WriteLine($"Type of number1 and number3 are equal: {object.ReferenceEquals(t, number3.GetType())}"); + Console.WriteLine($"Type of number1 and number4 are equal: {object.ReferenceEquals(t, number4.GetType())}"); // The example displays the following output: // Type of number1 and number2 are equal: False diff --git a/snippets/csharp/System/Type/Overview/GetType1.cs b/snippets/csharp/System/Type/Overview/GetType1.cs index ecf2365b6d1..9bb0daa8f7e 100644 --- a/snippets/csharp/System/Type/Overview/GetType1.cs +++ b/snippets/csharp/System/Type/Overview/GetType1.cs @@ -1,12 +1,12 @@ -using System; +using System; public class Example2 { public static void Main() { // - object[] values = { "word", true, 120, 136.34, 'a' }; - foreach (var value in values) + object[] values = ["word", true, 120, 136.34, 'a']; + foreach (object value in values) Console.WriteLine($"{value} - type {value.GetType().Name}"); // The example displays the following output: diff --git a/snippets/csharp/System/Type/Overview/source.cs b/snippets/csharp/System/Type/Overview/source.cs index 2e479978b80..303403b32fd 100644 --- a/snippets/csharp/System/Type/Overview/source.cs +++ b/snippets/csharp/System/Type/Overview/source.cs @@ -9,14 +9,14 @@ class Example3 { static void Main() { - Type t = typeof(String); + Type t = typeof(string); MethodInfo substr = t.GetMethod("Substring", - new Type[] { typeof(int), typeof(int) }); + [typeof(int), typeof(int)]); - Object result = - substr.Invoke("Hello, World!", new Object[] { 7, 5 }); - Console.WriteLine("{0} returned \"{1}\".", substr, result); + object result = + substr.Invoke("Hello, World!", [7, 5]); + Console.WriteLine($"{substr} returned \"{result}\"."); } } diff --git a/snippets/csharp/System/Type/ReflectedType/source.cs b/snippets/csharp/System/Type/ReflectedType/source.cs index bf060d9a664..fb57e57ee7a 100644 --- a/snippets/csharp/System/Type/ReflectedType/source.cs +++ b/snippets/csharp/System/Type/ReflectedType/source.cs @@ -1,6 +1,6 @@ // using System; -using System.Reflection; + public abstract class MyClassA { @@ -11,8 +11,7 @@ public abstract class MyClassB public static void Main(string[] args) { - Console.WriteLine("Reflected type of MyClassB is {0}", - typeof(MyClassB).ReflectedType); //outputs MyClassA, the enclosing class + Console.WriteLine($"Reflected type of MyClassB is {typeof(MyClassB).ReflectedType}"); //outputs MyClassA, the enclosing class } } // diff --git a/snippets/csharp/System/Type/StructLayoutAttribute/source.cs b/snippets/csharp/System/Type/StructLayoutAttribute/source.cs index 6d97f7ca5cc..66a8afe89b8 100644 --- a/snippets/csharp/System/Type/StructLayoutAttribute/source.cs +++ b/snippets/csharp/System/Type/StructLayoutAttribute/source.cs @@ -11,17 +11,15 @@ public static void Main() DisplayLayoutAttribute(typeof(Test2).StructLayoutAttribute); } - private static void DisplayLayoutAttribute(StructLayoutAttribute sla) - { - Console.WriteLine("\r\nCharSet: "+sla.CharSet.ToString()+"\r\n Pack: "+sla.Pack.ToString()+"\r\n Size: "+sla.Size.ToString()+"\r\n Value: "+sla.Value.ToString()); - } + private static void DisplayLayoutAttribute(StructLayoutAttribute sla) => Console.WriteLine("\r\nCharSet: " + sla.CharSet + "\r\n Pack: " + sla.Pack + "\r\n Size: " + sla.Size + "\r\n Value: " + sla.Value); public struct Test1 { public byte B1; public short S; public byte B2; } - [StructLayout(LayoutKind.Explicit, Pack=1)] public struct Test2 + [StructLayout(LayoutKind.Explicit, Pack = 1)] + public struct Test2 { [FieldOffset(0)] public byte B1; [FieldOffset(1)] public short S; diff --git a/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs b/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs index b734d2c81a9..3c3fcad33a9 100644 --- a/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs +++ b/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs @@ -1,6 +1,6 @@ -// +// using System; -using System.Reflection; + class MyClass { public int myField = 10; @@ -12,7 +12,7 @@ public static void Main() { try { - MyClass myClass = new MyClass(); + MyClass myClass = new(); // Get the type of MyClass. Type myClassType = myClass.GetType(); @@ -22,9 +22,9 @@ public static void Main() DisplayTypeHandle(myClassHandle); } - catch(Exception e) + catch (Exception e) { - Console.WriteLine("Exception: {0}", e.Message ); + Console.WriteLine($"Exception: {e.Message}"); } } @@ -34,7 +34,7 @@ public static void DisplayTypeHandle(RuntimeTypeHandle myTypeHandle) Type myType = Type.GetTypeFromHandle(myTypeHandle); // Display the type. Console.WriteLine("\nDisplaying the type from the handle:\n"); - Console.WriteLine("The type is {0}.", myType.ToString()); + Console.WriteLine($"The type is {myType}."); } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs b/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs index b6d72e3e237..dd617df1297 100644 --- a/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs +++ b/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs @@ -5,7 +5,7 @@ public class MissingEx1 { public static void Main() { - Person p = new Person("John", "Doe"); + Person p = new("John", "Doe"); Console.WriteLine(p); } } @@ -17,10 +17,7 @@ public class Person readonly string _fName; readonly string _lName; - static Person() - { - s_infoModule = new InfoModule(DateTime.UtcNow); - } + static Person() => s_infoModule = new(DateTime.UtcNow); public Person(string fName, string lName) { @@ -29,16 +26,13 @@ public Person(string fName, string lName) s_infoModule.Increment(); } - public override string ToString() - { - return string.Format("{0} {1}", _fName, _lName); - } + public override string ToString() => $"{_fName} {_lName}"; } // The example displays the following output if missing1a.dll is renamed or removed: -// Unhandled Exception: System.TypeInitializationException: -// The type initializer for 'Person' threw an exception. ---> -// System.IO.FileNotFoundException: Could not load file or assembly -// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'Person' threw an exception. ---> +// System.IO.FileNotFoundException: Could not load file or assembly +// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // or one of its dependencies. The system cannot find the file specified. // at Person..cctor() // --- End of inner exception stack trace --- diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs b/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs index 56903779fba..cbefba5bd3b 100644 --- a/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs +++ b/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs @@ -3,22 +3,13 @@ public class InfoModule { - private DateTime firstUse; - private int ctr = 0; + private DateTime firstUse; + private int ctr = 0; - public InfoModule(DateTime dat) - { - firstUse = dat; - } - - public int Increment() - { - return ++ctr; - } - - public DateTime GetInitializationTime() - { - return firstUse; - } + public InfoModule(DateTime dat) => firstUse = dat; + + public int Increment() => ++ctr; + + public DateTime GetInitializationTime() => firstUse; } // diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs b/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs index dfeda845b44..0a82b45d2ec 100644 --- a/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs +++ b/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs @@ -1,7 +1,7 @@ // using System; using System.Text.RegularExpressions; -using static System.Net.Mime.MediaTypeNames; + public class RegexEx1 { @@ -11,8 +11,8 @@ public static void Run() // Set a timeout interval of -2 seconds. domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2)); - Regex rgx = new Regex("[aeiouy]"); - Console.WriteLine($"Regular expression pattern: {rgx.ToString()}"); + Regex rgx = new("[aeiouy]"); + Console.WriteLine($"Regular expression pattern: {rgx}"); Console.WriteLine($"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds"); } } diff --git a/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs b/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs index ac866e10443..4a0392148a4 100644 --- a/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs +++ b/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs @@ -3,28 +3,28 @@ public class Example { - private static TestClass test = new TestClass(3); - - public static void Main() - { - Example ex = new Example(); - Console.WriteLine(test.Value); - } + private static TestClass test = new(3); + + public static void Main() + { + Example ex = new(); + Console.WriteLine(test.Value); + } } public class TestClass { - public readonly int Value; - - public TestClass(int value) - { - if (value < 0 || value > 1) throw new ArgumentOutOfRangeException(nameof(value)); - Value = value; - } + public readonly int Value; + + public TestClass(int value) + { + if (value < 0 || value > 1) throw new ArgumentOutOfRangeException(nameof(value)); + Value = value; + } } // The example displays the following output: -// Unhandled Exception: System.TypeInitializationException: -// The type initializer for 'Example' threw an exception. ---> +// Unhandled Exception: System.TypeInitializationException: +// The type initializer for 'Example' threw an exception. ---> // System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. // at TestClass..ctor(Int32 value) // at Example..cctor() diff --git a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs index b8b4effd96b..1cbe390c379 100644 --- a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs +++ b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs @@ -3,25 +3,27 @@ public class Example { - public static void Main() - { - try { - // Call a method that throws an exception. - TypeLoadExceptionDemoClass.GenerateException(); - } - catch (TypeLoadException e) { - Console.WriteLine("TypeLoadException:\n {0}", e.Message); - } - } + public static void Main() + { + try + { + // Call a method that throws an exception. + TypeLoadExceptionDemoClass.GenerateException(); + } + catch (TypeLoadException e) + { + Console.WriteLine($"TypeLoadException:\n {e.Message}"); + } + } } class TypeLoadExceptionDemoClass { - public static bool GenerateException() - { - // Throw a TypeLoadException with a custom defined message. - throw new TypeLoadException("This is a custom TypeLoadException error message."); - } + public static bool GenerateException() + { + // Throw a TypeLoadException with a custom defined message. + throw new TypeLoadException("This is a custom TypeLoadException error message."); + } } // The example displays the following output: // TypeLoadException: diff --git a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs index 51589e8ee66..5bb423a9c2d 100644 --- a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs +++ b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs @@ -12,42 +12,42 @@ as an inner exception.*/ public class TypeLoadException_Constructor3 { - public static void Main() - { - Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException."); - try - { - TypeLoadExceptionDemoClass3.GenerateException(); - } - catch (TypeLoadException e) - { - Console.WriteLine ("TypeLoadException: \n\tError Message = " + e.Message); - Console.WriteLine ("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message ); - } - catch (Exception e) - { - Console.WriteLine ("Exception: \n\tError Message = " + e.Message); - } - } + public static void Main() + { + Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException."); + try + { + TypeLoadExceptionDemoClass3.GenerateException(); + } + catch (TypeLoadException e) + { + Console.WriteLine("TypeLoadException: \n\tError Message = " + e.Message); + Console.WriteLine("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message); + } + catch (Exception e) + { + Console.WriteLine("Exception: \n\tError Message = " + e.Message); + } + } } class TypeLoadExceptionDemoClass3 { - // A call to this method will raise a TypeLoadException. - [DllImport("NonExistentDLL.DLL", EntryPoint="MethodNotExists")] - public static extern void NonExistentMethod(); + // A call to this method will raise a TypeLoadException. + [DllImport("NonExistentDLL.DLL", EntryPoint = "MethodNotExists")] + public static extern void NonExistentMethod(); - public static void GenerateException() - { - try - { - NonExistentMethod(); - } - catch (TypeLoadException e) - { - // Rethrow exception with the exception as inner exception - throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e); - } - } + public static void GenerateException() + { + try + { + NonExistentMethod(); + } + catch (TypeLoadException e) + { + // Rethrow exception with the exception as inner exception + throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e); + } + } } // diff --git a/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs b/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs index 0a4080a9a92..bc3ff020e9e 100644 --- a/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs +++ b/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs @@ -14,28 +14,27 @@ values are displayed. public class TypeLoadException_TypeName { - public static void Main() - { - // Get a reference to the assembly mscorlib.dll, which is always - // loaded. (System.String is defined in mscorlib.) - Assembly mscorlib = typeof(string).Assembly; + public static void Main() + { + // Get a reference to the assembly mscorlib.dll, which is always + // loaded. (System.String is defined in mscorlib.) + Assembly mscorlib = typeof(string).Assembly; - try - { - Console.WriteLine("Attempting to load a type that does not exist in mscorlib."); - // The boolean parameter causes an exception to be thrown if the - // type is not found. - Type myType = mscorlib.GetType("System.NonExistentType", true); - } - catch (TypeLoadException ex) - { - // Display the name of the type that was not found, and the - // exception message. - Console.WriteLine("TypeLoadException was caught. Type = '{0}'.", - ex.TypeName); - Console.WriteLine("Error Message = '{0}'", ex.Message); - } - } + try + { + Console.WriteLine("Attempting to load a type that does not exist in mscorlib."); + // The boolean parameter causes an exception to be thrown if the + // type is not found. + Type myType = mscorlib.GetType("System.NonExistentType", true); + } + catch (TypeLoadException ex) + { + // Display the name of the type that was not found, and the + // exception message. + Console.WriteLine($"TypeLoadException was caught. Type = '{ex.TypeName}'."); + Console.WriteLine($"Error Message = '{ex.Message}'"); + } + } } /* This code example produces output similar to the following: diff --git a/snippets/csharp/System/TypedReference/Overview/source.cs b/snippets/csharp/System/TypedReference/Overview/source.cs index 412e3377f61..70684dc3408 100644 --- a/snippets/csharp/System/TypedReference/Overview/source.cs +++ b/snippets/csharp/System/TypedReference/Overview/source.cs @@ -3,18 +3,18 @@ class TypedReferenceArray { - public static void Main() + public static void Main() + { + try { - try - { -// - Assembly.Load("mscorlib.dll").GetType("System.TypedReference[]"); -// - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - Console.WriteLine(ex.StackTrace); - } - } -} \ No newline at end of file + // + Assembly.Load("mscorlib.dll").GetType("System.TypedReference[]"); + // + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + Console.WriteLine(ex.StackTrace); + } + } +} From 529ac6d2f65d6e7645f494bc672c56c1f4fcb969 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:55:55 -0700 Subject: [PATCH 5/9] Modernize C# code snippets - System/T* (#12972) --- .../Overview/threadsafe2a.cs | 10 +- .../csharp/System/TimeSpan/.ctor/ctoriii.cs | 40 +- .../csharp/System/TimeSpan/.ctor/ctoriiii.cs | 40 +- .../csharp/System/TimeSpan/.ctor/ctoriiiii.cs | 44 +- .../csharp/System/TimeSpan/.ctor/ctorl.cs | 46 +- snippets/csharp/System/TimeSpan/Add/add1.cs | 52 +- .../System/TimeSpan/Compare/compare1.cs | 28 +- .../System/TimeSpan/CompareTo/comp_equal.cs | 56 +- .../System/TimeSpan/CompareTo/cto_eq_obj.cs | 59 +- .../csharp/System/TimeSpan/Days/properties.cs | 38 +- .../System/TimeSpan/Duration/dura_nega_una.cs | 46 +- .../FromDays/System.TimeSpan.FromMinutes.cs | 90 +-- .../System/TimeSpan/FromDays/fromdays.cs | 56 +- .../System/TimeSpan/FromDays/fromhours.cs | 56 +- .../System/TimeSpan/FromDays/frommillisec.cs | 54 +- .../System/TimeSpan/FromDays/fromminutes.cs | 56 +- .../System/TimeSpan/FromDays/fromseconds.cs | 56 +- .../System/TimeSpan/FromDays/fromticks.cs | 54 +- .../System/TimeSpan/GetHashCode/hashcode.cs | 68 +- .../csharp/System/TimeSpan/MaxValue/fields.cs | 64 +- .../System/TimeSpan/Overview/instantiate1.cs | 141 ++-- .../System/TimeSpan/Overview/structure1.cs | 74 +- .../csharp/System/TimeSpan/Overview/zero1.cs | 12 +- .../csharp/System/TimeSpan/Parse/parse1.cs | 56 +- .../csharp/System/TimeSpan/Parse/parse2.cs | 67 +- .../System/TimeSpan/ParseExact/Program.cs | 4 + .../System/TimeSpan/ParseExact/Project.csproj | 6 + .../TimeSpan/ParseExact/parseexactexample1.cs | 304 ++++---- .../TimeSpan/ParseExact/parseexactexample2.cs | 319 +++++---- .../TimeSpan/ParseExact/parseexactexample3.cs | 50 +- .../TimeSpan/ParseExact/parseexactexample4.cs | 52 +- .../System/TimeSpan/Subtract/subtract1.cs | 54 +- .../System/TimeSpan/ToString/Program.cs | 3 + .../System/TimeSpan/ToString/Project.csproj | 6 + .../System/TimeSpan/ToString/ToString1.cs | 88 +-- .../System/TimeSpan/ToString/tostring3.cs | 124 ++-- .../System/TimeSpan/ToString/tostring4.cs | 39 +- .../System/TimeSpan/TotalDays/totaldays.cs | 46 +- .../System/TimeSpan/TotalHours/totalhours.cs | 43 +- .../TotalMilliseconds/totalmilliseconds.cs | 45 +- .../TimeSpan/TotalMinutes/totalminutes.cs | 42 +- .../TimeSpan/TotalSeconds/totalseconds.cs | 40 +- .../System/TimeSpan/TryParse/TryParse1.cs | 64 +- .../System/TimeSpan/TryParse/tryparse2.cs | 64 +- .../System/TimeSpan/TryParseExact/Program.cs | 4 + .../TimeSpan/TryParseExact/Project.csproj | 6 + .../TryParseExact/tryparseexactexample1.cs | 168 ++--- .../TryParseExact/tryparseexactexample2.cs | 193 +++-- .../TryParseExact/tryparseexactexample3.cs | 35 +- .../TryParseExact/tryparseexactexample4.cs | 37 +- .../TimeSpan/op_Addition/Subtraction1.cs | 32 +- .../System/TimeSpan/op_Addition/operators1.cs | 32 +- .../TimeSpan/op_Equality/relationalops.cs | 54 +- .../DateEnd/DateStart1.cs | 121 ++-- .../System.TimeZone2.AdjustmentRule.Class.cs | 424 ++++++----- .../CreateFixedDateRule/Program.cs | 2 + .../CreateFixedDateRule/Project.csproj | 6 + .../System.TimeZone2.TransitionTime.Class.cs | 544 +++++++-------- .../CreateFixedDateRule/example1.cs | 192 +++-- .../TimeZoneInfo/BaseUtcOffset/Program.cs | 3 + .../TimeZoneInfo/BaseUtcOffset/Project.csproj | 8 + .../BaseUtcOffset/ShowTimeZoneNames1.cs | 18 +- .../BaseUtcOffset/TimeZone2_Examples.cs | 272 ++++---- .../BaseUtcOffset/getsystemtimezones1.cs | 108 ++- .../System.TimeZone2.BestPractices.cs | 44 +- .../TimeZoneInfo/ConvertTime/Program.cs | 3 + .../TimeZoneInfo/ConvertTime/Project.csproj | 8 + .../ConvertTime/TimeZone2Concepts.cs | 658 +++++++++--------- .../TimeZoneInfo/ConvertTime/converttime1.cs | 70 +- .../TimeZoneInfo/ConvertTime/converttime2.cs | 69 +- .../System.TimeZone2.Conversions.cs | 190 +++-- .../convertdt2.cs | 28 +- .../System.TimeZone2.CreateTimeZone.cs | 476 ++++++------- .../DaylightName/IsDaylightSavingTime.cs | 84 +-- .../System/TimeZoneInfo/Equals/equals1.cs | 22 +- ...ystem.TimeZone2.GetAmbiguousTimeOffsets.cs | 183 +++-- .../System.TimeZone2.GetUtcOffset.cs | 165 +++-- .../TimeZoneInfo/HasSameRules/HasSameRules.cs | 52 +- .../TimeoutException/Overview/Project.csproj | 9 + .../System/TimeoutException/Overview/to.cs | 44 +- .../csharp/System/Tuple/Overview/Program.cs | 5 + .../System/Tuple/Overview/Project.csproj | 6 + .../csharp/System/Tuple/Overview/create1.cs | 84 +-- .../System/Tuple/Overview/createntuple.cs | 30 +- .../csharp/System/Tuple/Overview/ctor8.cs | 20 +- .../csharp/System/Tuple/Overview/example.cs | 23 +- .../csharp/System/Tuple/Overview/example1.cs | 62 +- .../Equals/equals1.cs | 48 +- .../Item1/item1.cs | 21 +- .../Overview/octuple1.cs | 16 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 46 +- .../compareto2.cs | 137 ++-- .../ToString/tostring1.cs | 17 +- .../Equals/Program.cs | 2 + .../Equals/Project.csproj | 6 + .../Equals/equals1.cs | 41 +- .../Equals/equals2.cs | 87 ++- .../TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs | 38 +- .../Overview/example1.cs | 64 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 50 +- .../compareto2.cs | 130 ++-- .../ToString/tostring1.cs | 14 +- .../TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs | 2 + .../Equals/Project.csproj | 6 + .../TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs | 41 +- .../TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs | 89 ++- .../TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs | 40 +- .../Overview/example1.cs | 58 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 50 +- .../compareto2.cs | 127 ++-- .../ToString/tostring1.cs | 14 +- .../TupleT1,T2,T3,T4,T5/Equals/equals1.cs | 41 +- .../TupleT1,T2,T3,T4,T5/Equals/equals2.cs | 100 ++- .../System/TupleT1,T2,T3,T4,T5/Item1/item1.cs | 32 +- .../TupleT1,T2,T3,T4,T5/Overview/example1.cs | 109 ++- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 64 +- .../compareto2.cs | 88 +-- .../TupleT1,T2,T3,T4,T5/ToString/tostring1.cs | 24 +- .../System/TupleT1,T2,T3,T4/Equals/equals1.cs | 41 +- .../System/TupleT1,T2,T3,T4/Equals/equals2.cs | 92 ++- .../System/TupleT1,T2,T3,T4/Item1/item1.cs | 32 +- .../TupleT1,T2,T3,T4/Overview/example1.cs | 69 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 50 +- .../compareto2.cs | 62 +- .../TupleT1,T2,T3,T4/ToString/tostring1.cs | 22 +- .../System/TupleT1,T2,T3/Equals/Program.cs | 2 + .../TupleT1,T2,T3/Equals/Project.csproj | 6 + .../System/TupleT1,T2,T3/Equals/equals1.cs | 49 +- .../System/TupleT1,T2,T3/Equals/equals2.cs | 84 ++- .../System/TupleT1,T2,T3/Overview/example1.cs | 75 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 36 +- .../compareto2.cs | 62 +- .../TupleT1,T2,T3/ToString/tostring1.cs | 22 +- .../System/TupleT1,T2/Equals/Program.cs | 2 + .../System/TupleT1,T2/Equals/Project.csproj | 6 + .../System/TupleT1,T2/Equals/equals1.cs | 46 +- .../System/TupleT1,T2/Equals/equals2.cs | 82 ++- .../System/TupleT1,T2/Overview/example1.cs | 58 +- .../System/TupleT1,T2/Overview/item1.cs | 66 +- .../Program.cs | 2 + .../Project.csproj | 6 + .../compareto1.cs | 36 +- .../compareto2.cs | 62 +- .../System/TupleT1,T2/ToString/tostring1.cs | 20 +- .../csharp/System/TupleT1/Equals/Program.cs | 2 + .../System/TupleT1/Equals/Project.csproj | 6 + .../csharp/System/TupleT1/Equals/equals1.cs | 45 +- .../csharp/System/TupleT1/Equals/equals2.cs | 76 +- snippets/csharp/System/TupleT1/Item1/item1.cs | 50 +- .../compareto1.cs | 46 +- .../compareto2.cs | 49 +- .../System/TupleT1/ToString/tostring1.cs | 35 +- 164 files changed, 5128 insertions(+), 5271 deletions(-) create mode 100644 snippets/csharp/System/TimeSpan/ParseExact/Program.cs create mode 100644 snippets/csharp/System/TimeSpan/ParseExact/Project.csproj create mode 100644 snippets/csharp/System/TimeSpan/ToString/Program.cs create mode 100644 snippets/csharp/System/TimeSpan/ToString/Project.csproj create mode 100644 snippets/csharp/System/TimeSpan/TryParseExact/Program.cs create mode 100644 snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj create mode 100644 snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs create mode 100644 snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj create mode 100644 snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs create mode 100644 snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj create mode 100644 snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs create mode 100644 snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj create mode 100644 snippets/csharp/System/TimeoutException/Overview/Project.csproj create mode 100644 snippets/csharp/System/Tuple/Overview/Program.cs create mode 100644 snippets/csharp/System/Tuple/Overview/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2/Equals/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2/Equals/Project.csproj create mode 100644 snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs create mode 100644 snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj create mode 100644 snippets/csharp/System/TupleT1/Equals/Program.cs create mode 100644 snippets/csharp/System/TupleT1/Equals/Project.csproj diff --git a/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs b/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs index 5f7e07d328a..0fa5de8cd47 100644 --- a/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs +++ b/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs @@ -31,14 +31,8 @@ static void ProcessRequest(object? requestId) PerformLogging(); } - static void PerformDatabaseOperation() - { - Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}"); - } + static void PerformDatabaseOperation() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}"); - static void PerformLogging() - { - Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}"); - } + static void PerformLogging() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}"); } // diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs index ce9c21fbf34..d52d30cdff5 100644 --- a/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs +++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs @@ -5,37 +5,35 @@ class TimeSpanCtorIIIDemo { // Create a TimeSpan object and display its value. - static void CreateTimeSpan( int hours, int minutes, - int seconds ) + static void CreateTimeSpan(int hours, int minutes, + int seconds) { - TimeSpan elapsedTime = - new TimeSpan( hours, minutes, seconds ); + TimeSpan elapsedTime = + new(hours, minutes, seconds); // Format the constructor for display. - string ctor = String.Format( "TimeSpan( {0}, {1}, {2} )", - hours, minutes, seconds); + string ctor = $"TimeSpan( {hours}, {minutes}, {seconds} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-37}{1,16}", - ctor, elapsedTime.ToString( ) ); + Console.WriteLine($"{ctor,-37}{elapsedTime,16}"); } - - static void Main( ) + + static void Main() { Console.WriteLine( "This example of the TimeSpan( int, int, int ) " + - "\nconstructor generates the following output.\n" ); - Console.WriteLine( "{0,-37}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-37}{1,16}", "-----------", "-----" ); + "\nconstructor generates the following output.\n"); + Console.WriteLine($"{"Constructor",-37}{"Value",16}"); + Console.WriteLine($"{"-----------",-37}{"-----",16}"); - CreateTimeSpan( 10, 20, 30 ); - CreateTimeSpan( -10, 20, 30 ); - CreateTimeSpan( 0, 0, 37230 ); - CreateTimeSpan( 1000, 2000, 3000 ); - CreateTimeSpan( 1000, -2000, -3000 ); - CreateTimeSpan( 999999, 999999, 999999 ); - } -} + CreateTimeSpan(10, 20, 30); + CreateTimeSpan(-10, 20, 30); + CreateTimeSpan(0, 0, 37230); + CreateTimeSpan(1000, 2000, 3000); + CreateTimeSpan(1000, -2000, -3000); + CreateTimeSpan(999999, 999999, 999999); + } +} /* This example of the TimeSpan( int, int, int ) diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs index f3f6773488f..414722046f1 100644 --- a/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs +++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs @@ -4,35 +4,33 @@ class Example { // Create a TimeSpan object and display its value. - static void CreateTimeSpan( int days, int hours, - int minutes, int seconds ) + static void CreateTimeSpan(int days, int hours, + int minutes, int seconds) { - TimeSpan elapsedTime = - new TimeSpan( days, hours, minutes, seconds ); + TimeSpan elapsedTime = + new(days, hours, minutes, seconds); // Format the constructor for display. - string ctor = - String.Format( "TimeSpan( {0}, {1}, {2}, {3} )", - days, hours, minutes, seconds); + string ctor = + $"TimeSpan( {days}, {hours}, {minutes}, {seconds} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-44}{1,16}", - ctor, elapsedTime.ToString( ) ); + Console.WriteLine($"{ctor,-44}{elapsedTime,16}"); } - - static void Main( ) + + static void Main() { - Console.WriteLine( "{0,-44}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-44}{1,16}", "-----------", "-----" ); + Console.WriteLine($"{"Constructor",-44}{"Value",16}"); + Console.WriteLine($"{"-----------",-44}{"-----",16}"); - CreateTimeSpan( 10, 20, 30, 40 ); - CreateTimeSpan( -10, 20, 30, 40 ); - CreateTimeSpan( 0, 0, 0, 937840 ); - CreateTimeSpan( 1000, 2000, 3000, 4000 ); - CreateTimeSpan( 1000, -2000, -3000, -4000 ); - CreateTimeSpan( 999999, 999999, 999999, 999999 ); - } -} + CreateTimeSpan(10, 20, 30, 40); + CreateTimeSpan(-10, 20, 30, 40); + CreateTimeSpan(0, 0, 0, 937840); + CreateTimeSpan(1000, 2000, 3000, 4000); + CreateTimeSpan(1000, -2000, -3000, -4000); + CreateTimeSpan(999999, 999999, 999999, 999999); + } +} // The example displays the following output: // Constructor Value // ----------- ----- diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs index 6b9b823404c..f02ea710383 100644 --- a/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs +++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs @@ -1,43 +1,41 @@ // -// Example of the TimeSpan( int, int, int, int, int ) constructor. +// Example of the TimeSpan( int, int, int, int, int ) constructor. using System; class TimeSpanCtorIIIIIDemo { // Create a TimeSpan object and display its value. - static void CreateTimeSpan( int days, int hours, - int minutes, int seconds, int millisec ) + static void CreateTimeSpan(int days, int hours, + int minutes, int seconds, int millisec) { - TimeSpan elapsedTime = new TimeSpan( - days, hours, minutes, seconds, millisec ); + TimeSpan elapsedTime = new( + days, hours, minutes, seconds, millisec); // Format the constructor for display. - string ctor = - String.Format( "TimeSpan( {0}, {1}, {2}, {3}, {4} )", - days, hours, minutes, seconds, millisec); + string ctor = + $"TimeSpan( {days}, {hours}, {minutes}, {seconds}, {millisec} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-48}{1,24}", - ctor, elapsedTime.ToString( ) ); + Console.WriteLine($"{ctor,-48}{elapsedTime,24}"); } - static void Main( ) + static void Main() { - Console.WriteLine( + Console.WriteLine( "This example of the " + "TimeSpan( int, int, int, int, int ) " + - "\nconstructor generates the following output.\n" ); - Console.WriteLine( "{0,-48}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-48}{1,16}", "-----------", "-----" ); + "\nconstructor generates the following output.\n"); + Console.WriteLine($"{"Constructor",-48}{"Value",16}"); + Console.WriteLine($"{"-----------",-48}{"-----",16}"); - CreateTimeSpan( 10, 20, 30, 40, 50 ); - CreateTimeSpan( -10, 20, 30, 40, 50 ); - CreateTimeSpan( 0, 0, 0, 0, 937840050 ); - CreateTimeSpan( 1111, 2222, 3333, 4444, 5555 ); - CreateTimeSpan( 1111, -2222, -3333, -4444, -5555 ); - CreateTimeSpan( 99999, 99999, 99999, 99999, 99999 ); - } -} + CreateTimeSpan(10, 20, 30, 40, 50); + CreateTimeSpan(-10, 20, 30, 40, 50); + CreateTimeSpan(0, 0, 0, 0, 937840050); + CreateTimeSpan(1111, 2222, 3333, 4444, 5555); + CreateTimeSpan(1111, -2222, -3333, -4444, -5555); + CreateTimeSpan(99999, 99999, 99999, 99999, 99999); + } +} /* This example of the TimeSpan( int, int, int, int, int ) diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs b/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs index acea73f41cf..cae8d36226d 100644 --- a/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs +++ b/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs @@ -5,41 +5,41 @@ class TimeSpanCtorLDemo { // Create a TimeSpan object and display its value. - static void CreateTimeSpan( long ticks ) + static void CreateTimeSpan(long ticks) { - TimeSpan elapsedTime = new TimeSpan( ticks ); + TimeSpan elapsedTime = new(ticks); // Format the constructor for display. - string ctor = String.Format( "TimeSpan( {0} )", ticks ); + string ctor = $"TimeSpan( {ticks} )"; // Pad the end of a TimeSpan string with spaces if // it does not contain milliseconds. - string elapsedStr = elapsedTime.ToString( ); - int pointIndex = elapsedStr.IndexOf( ':' ); + string elapsedStr = elapsedTime.ToString(); + int pointIndex = elapsedStr.IndexOf(':'); - pointIndex = elapsedStr.IndexOf( '.', pointIndex ); - if( pointIndex < 0 ) elapsedStr += " "; + pointIndex = elapsedStr.IndexOf('.', pointIndex); + if (pointIndex < 0) elapsedStr += " "; // Display the constructor and its value. - Console.WriteLine( "{0,-33}{1,24}", ctor, elapsedStr ); + Console.WriteLine($"{ctor,-33}{elapsedStr,24}"); } - - static void Main( ) + + static void Main() { - Console.WriteLine( + Console.WriteLine( "This example of the TimeSpan( long ) constructor " + - "\ngenerates the following output.\n" ); - Console.WriteLine( "{0,-33}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-33}{1,16}", "-----------", "-----" ); - - CreateTimeSpan( 1 ); - CreateTimeSpan( 999999 ); - CreateTimeSpan( -1000000000000 ); - CreateTimeSpan( 18012202000000 ); - CreateTimeSpan( 999999999999999999 ); - CreateTimeSpan( 1000000000000000000 ); - } -} + "\ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-33}{"Value",16}"); + Console.WriteLine($"{"-----------",-33}{"-----",16}"); + + CreateTimeSpan(1); + CreateTimeSpan(999999); + CreateTimeSpan(-1000000000000); + CreateTimeSpan(18012202000000); + CreateTimeSpan(999999999999999999); + CreateTimeSpan(1000000000000000000); + } +} /* This example of the TimeSpan( long ) constructor diff --git a/snippets/csharp/System/TimeSpan/Add/add1.cs b/snippets/csharp/System/TimeSpan/Add/add1.cs index 4d8254b602f..6a30030219b 100644 --- a/snippets/csharp/System/TimeSpan/Add/add1.cs +++ b/snippets/csharp/System/TimeSpan/Add/add1.cs @@ -2,34 +2,34 @@ public class Example { - public static void Main() - { - // - TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16); + public static void Main() + { + // + TimeSpan baseTimeSpan = new(1, 12, 15, 16); - // Create an array of timespan intervals. - TimeSpan[] intervals = { - TimeSpan.FromDays(1.5), - TimeSpan.FromHours(1.5), - TimeSpan.FromMinutes(45), + // Create an array of timespan intervals. + TimeSpan[] intervals = [ + TimeSpan.FromDays(1.5), + TimeSpan.FromHours(1.5), + TimeSpan.FromMinutes(45), TimeSpan.FromMilliseconds(505), - new TimeSpan(1, 17, 32, 20), - new TimeSpan(-8, 30, 0) - }; + new TimeSpan(1, 17, 32, 20), + new TimeSpan(-8, 30, 0) + ]; - // Calculate a new time interval by adding each element to the base interval. - foreach (var interval in intervals) - Console.WriteLine(@"{0,-10:g} {3} {1,15:%d\:hh\:mm\:ss\.ffff} = {2:%d\:hh\:mm\:ss\.ffff}", - baseTimeSpan, interval, baseTimeSpan.Add(interval), - interval < TimeSpan.Zero ? "-" : "+"); + // Calculate a new time interval by adding each element to the base interval. + foreach (var interval in intervals) + Console.WriteLine(@"{0,-10:g} {3} {1,15:%d\:hh\:mm\:ss\.ffff} = {2:%d\:hh\:mm\:ss\.ffff}", + baseTimeSpan, interval, baseTimeSpan.Add(interval), + interval < TimeSpan.Zero ? "-" : "+"); - // The example displays the following output: - // 1:12:15:16 + 1:12:00:00.0000 = 3:00:15:16.0000 - // 1:12:15:16 + 0:01:30:00.0000 = 1:13:45:16.0000 - // 1:12:15:16 + 0:00:45:00.0000 = 1:13:00:16.0000 - // 1:12:15:16 + 0:00:00:00.5050 = 1:12:15:16.5050 - // 1:12:15:16 + 1:17:32:20.0000 = 3:05:47:36.0000 - // 1:12:15:16 - 0:07:30:00.0000 = 1:04:45:16.0000 - // - } + // The example displays the following output: + // 1:12:15:16 + 1:12:00:00.0000 = 3:00:15:16.0000 + // 1:12:15:16 + 0:01:30:00.0000 = 1:13:45:16.0000 + // 1:12:15:16 + 0:00:45:00.0000 = 1:13:00:16.0000 + // 1:12:15:16 + 0:00:00:00.5050 = 1:12:15:16.5050 + // 1:12:15:16 + 1:17:32:20.0000 = 3:05:47:36.0000 + // 1:12:15:16 - 0:07:30:00.0000 = 1:04:45:16.0000 + // + } } diff --git a/snippets/csharp/System/TimeSpan/Compare/compare1.cs b/snippets/csharp/System/TimeSpan/Compare/compare1.cs index 14e10e51a83..0a25d8d21c9 100644 --- a/snippets/csharp/System/TimeSpan/Compare/compare1.cs +++ b/snippets/csharp/System/TimeSpan/Compare/compare1.cs @@ -6,27 +6,25 @@ static void Main() { // // Define a time interval equal to two hours. - TimeSpan baseInterval = new TimeSpan( 2, 0, 0); + TimeSpan baseInterval = new(2, 0, 0); // Define an array of time intervals to compare with // the base interval. - TimeSpan[] spans = { + TimeSpan[] spans = [ TimeSpan.FromSeconds(-2.5), TimeSpan.FromMinutes(20), - TimeSpan.FromHours(1), + TimeSpan.FromHours(1), TimeSpan.FromMinutes(90), - baseInterval, - TimeSpan.FromDays(.5), - TimeSpan.FromDays(1) - }; + baseInterval, + TimeSpan.FromDays(.5), + TimeSpan.FromDays(1) + ]; // Compare the time intervals. - foreach (var span in spans) { - int result = TimeSpan.Compare(baseInterval, span); - Console.WriteLine("{0} {1} {2} (Compare returns {3})", - baseInterval, - result == 1 ? ">" : result == 0 ? "=" : "<", - span, result); + foreach (var span in spans) + { + int result = TimeSpan.Compare(baseInterval, span); + Console.WriteLine($"{baseInterval} {(result == 1 ? ">" : result == 0 ? "=" : "<")} {span} (Compare returns {result})"); } // The example displays the following output: @@ -38,5 +36,5 @@ static void Main() // 02:00:00 < 12:00:00 (Compare returns -1) // 02:00:00 < 1.00:00:00 (Compare returns -1) // - } -} + } +} diff --git a/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs b/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs index 608e000cca8..3bea5a23db7 100644 --- a/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs +++ b/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs @@ -1,51 +1,51 @@ // -// Example of the TimeSpan.Compare( TimeSpan, TimeSpan ) and +// Example of the TimeSpan.Compare( TimeSpan, TimeSpan ) and // TimeSpan.Equals( TimeSpan, TimeSpan ) methods. using System; class TSCompareEqualsDemo { - const string dataFmt = "{0,-38}{1}" ; + const string dataFmt = "{0,-38}{1}"; // Compare TimeSpan parameters, and display them with the results. - static void CompareTimeSpans( TimeSpan Left, TimeSpan Right, - string RightText ) + static void CompareTimeSpans(TimeSpan Left, TimeSpan Right, + string RightText) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "Right: " + RightText, Right ); - Console.WriteLine( dataFmt, "TimeSpan.Equals( Left, Right )", - TimeSpan.Equals( Left, Right ) ); - Console.WriteLine( dataFmt, - "TimeSpan.Compare( Left, Right )", - TimeSpan.Compare( Left, Right ) ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "Right: " + RightText, Right); + Console.WriteLine(dataFmt, "TimeSpan.Equals( Left, Right )", + TimeSpan.Equals(Left, Right)); + Console.WriteLine(dataFmt, + "TimeSpan.Compare( Left, Right )", + TimeSpan.Compare(Left, Right)); } - static void Main( ) + static void Main() { - TimeSpan Left = new TimeSpan( 2, 0, 0 ); + TimeSpan Left = new(2, 0, 0); Console.WriteLine( "This example of the TimeSpan.Equals( TimeSpan, Time" + "Span ) and \nTimeSpan.Compare( TimeSpan, TimeSpan ) " + "methods generates the \nfollowing output by creating " + "several different TimeSpan \nobjects and comparing " + - "them with a 2-hour TimeSpan.\n" ); - Console.WriteLine( dataFmt, "Left: TimeSpan( 2, 0, 0 )", - Left ); + "them with a 2-hour TimeSpan.\n"); + Console.WriteLine(dataFmt, "Left: TimeSpan( 2, 0, 0 )", + Left); // Create objects to compare with a 2-hour TimeSpan. - CompareTimeSpans( Left, new TimeSpan( 0, 120, 0 ), - "TimeSpan( 0, 120, 0 )" ); - CompareTimeSpans( Left, new TimeSpan( 2, 0, 1 ), - "TimeSpan( 2, 0, 1 )" ); - CompareTimeSpans( Left, new TimeSpan( 2, 0, -1 ), + CompareTimeSpans(Left, new TimeSpan(0, 120, 0), + "TimeSpan( 0, 120, 0 )"); + CompareTimeSpans(Left, new TimeSpan(2, 0, 1), + "TimeSpan( 2, 0, 1 )"); + CompareTimeSpans(Left, new TimeSpan(2, 0, -1), "TimeSpan( 2, 0, -1 )"); - CompareTimeSpans( Left, new TimeSpan( 72000000000 ), - "TimeSpan( 72000000000 )" ); - CompareTimeSpans( Left, TimeSpan.FromDays( 1.0 / 12D ), - "TimeSpan.FromDays( 1 / 12 )" ); - } -} + CompareTimeSpans(Left, new TimeSpan(72000000000), + "TimeSpan( 72000000000 )"); + CompareTimeSpans(Left, TimeSpan.FromDays(1.0 / 12D), + "TimeSpan.FromDays( 1 / 12 )"); + } +} /* This example of the TimeSpan.Equals( TimeSpan, TimeSpan ) and @@ -74,5 +74,5 @@ objects and comparing them with a 2-hour TimeSpan. Right: TimeSpan.FromDays( 1 / 12 ) 02:00:00 TimeSpan.Equals( Left, Right ) True TimeSpan.Compare( Left, Right ) 0 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs b/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs index 81a4f8acf57..0bbf8e67e6e 100644 --- a/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs +++ b/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs @@ -1,60 +1,57 @@ // -// Example of the TimeSpan.CompareTo( Object ) and +// Example of the TimeSpan.CompareTo( Object ) and // TimeSpan.Equals( Object ) methods. using System; class TSCompToEqualsObjDemo { - // Compare the TimeSpan to the Object parameters, + // Compare the TimeSpan to the Object parameters, // and display the Object parameters with the results. - static void CompTimeSpanToObject( TimeSpan Left, object Right, - string RightText ) + static void CompTimeSpanToObject(TimeSpan Left, object Right, + string RightText) { - Console.WriteLine( "{0,-33}{1}", "Object: " + RightText, - Right ); - Console.WriteLine( "{0,-33}{1}", "Left.Equals( Object )", - Left.Equals( Right ) ); - Console.Write( "{0,-33}", "Left.CompareTo( Object )" ); + Console.WriteLine($"{"Object: " + RightText,-33}{Right}"); + Console.WriteLine($"{"Left.Equals( Object )",-33}{Left.Equals(Right)}"); + Console.Write($"{"Left.CompareTo( Object )",-33}"); // Catch the exception if CompareTo( ) throws one. try { - Console.WriteLine( "{0}\n", Left.CompareTo( Right ) ); + Console.WriteLine($"{Left.CompareTo(Right)}\n"); } - catch( Exception ex ) + catch (Exception ex) { - Console.WriteLine( "Error: {0}\n", ex.Message ); + Console.WriteLine($"Error: {ex.Message}\n"); } } - static void Main( ) + static void Main() { - TimeSpan Left = new TimeSpan( 0, 5, 0 ); + TimeSpan Left = new(0, 5, 0); Console.WriteLine( "This example of the TimeSpan.Equals( Object ) " + "and \nTimeSpan.CompareTo( Object ) methods generates " + "the \nfollowing output by creating several different " + "TimeSpan \nobjects and comparing them with a " + - "5-minute TimeSpan.\n" ); - Console.WriteLine( "{0,-33}{1}\n", - "Left: TimeSpan( 0, 5, 0 )", Left ); + "5-minute TimeSpan.\n"); + Console.WriteLine($"{"Left: TimeSpan( 0, 5, 0 )",-33}{Left}\n"); // Create objects to compare with a 5-minute TimeSpan. - CompTimeSpanToObject( Left, new TimeSpan( 0, 0, 300 ), - "TimeSpan( 0, 0, 300 )" ); - CompTimeSpanToObject( Left, new TimeSpan( 0, 5, 1 ), - "TimeSpan( 0, 5, 1 )" ); - CompTimeSpanToObject( Left, new TimeSpan( 0, 5, -1 ), - "TimeSpan( 0, 5, -1 )" ); - CompTimeSpanToObject( Left, new TimeSpan( 3000000000 ), - "TimeSpan( 3000000000 )" ); - CompTimeSpanToObject( Left, 3000000000L, - "long 3000000000L" ); - CompTimeSpanToObject( Left, "00:05:00", - "string \"00:05:00\"" ); - } -} + CompTimeSpanToObject(Left, new TimeSpan(0, 0, 300), + "TimeSpan( 0, 0, 300 )"); + CompTimeSpanToObject(Left, new TimeSpan(0, 5, 1), + "TimeSpan( 0, 5, 1 )"); + CompTimeSpanToObject(Left, new TimeSpan(0, 5, -1), + "TimeSpan( 0, 5, -1 )"); + CompTimeSpanToObject(Left, new TimeSpan(3000000000), + "TimeSpan( 3000000000 )"); + CompTimeSpanToObject(Left, 3000000000L, + "long 3000000000L"); + CompTimeSpanToObject(Left, "00:05:00", + "string \"00:05:00\""); + } +} /* This example of the TimeSpan.Equals( Object ) and diff --git a/snippets/csharp/System/TimeSpan/Days/properties.cs b/snippets/csharp/System/TimeSpan/Days/properties.cs index 15bf2ff4daa..350b7e65123 100644 --- a/snippets/csharp/System/TimeSpan/Days/properties.cs +++ b/snippets/csharp/System/TimeSpan/Days/properties.cs @@ -6,45 +6,37 @@ class Example static void Main() { // Create and display a TimeSpan value of 1 tick. - Console.Write("\n{0,-45}", "TimeSpan( 1 )"); + Console.Write($"\n{"TimeSpan( 1 )",-45}"); ShowTimeSpanProperties(new TimeSpan(1)); // Create a TimeSpan value with a large number of ticks. - Console.Write("\n{0,-45}", "TimeSpan( 111222333444555 )"); + Console.Write($"\n{"TimeSpan( 111222333444555 )",-45}"); ShowTimeSpanProperties(new TimeSpan(111222333444555)); // This TimeSpan has all fields specified. - Console.Write("\n{0,-45}", "TimeSpan( 10, 20, 30, 40, 50 )"); + Console.Write($"\n{"TimeSpan( 10, 20, 30, 40, 50 )",-45}"); ShowTimeSpanProperties(new TimeSpan(10, 20, 30, 40, 50)); // This TimeSpan has all fields overflowing. - Console.Write("\n{0,-45}", - "TimeSpan( 1111, 2222, 3333, 4444, 5555 )"); + Console.Write($"\n{"TimeSpan( 1111, 2222, 3333, 4444, 5555 )",-45}"); ShowTimeSpanProperties( new TimeSpan(1111, 2222, 3333, 4444, 5555)); // This TimeSpan is based on a number of days. - Console.Write("\n{0,-45}", "FromDays( 20.84745602 )"); - ShowTimeSpanProperties(TimeSpan.FromDays( 20.84745602)); + Console.Write($"\n{"FromDays( 20.84745602 )",-45}"); + ShowTimeSpanProperties(TimeSpan.FromDays(20.84745602)); } - static void ShowTimeSpanProperties( TimeSpan interval ) + static void ShowTimeSpanProperties(TimeSpan interval) { - Console.WriteLine("{0,21}", interval); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Days", - interval.Days, "TotalDays", interval.TotalDays); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Hours", - interval.Hours, "TotalHours", interval.TotalHours); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Minutes", - interval.Minutes, "TotalMinutes", interval.TotalMinutes); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Seconds", - interval.Seconds, "TotalSeconds", interval.TotalSeconds); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Milliseconds", - interval.Milliseconds, "TotalMilliseconds", - interval.TotalMilliseconds); - Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N0}", null, null, - "Ticks", interval.Ticks); - } + Console.WriteLine($"{interval,21}"); + Console.WriteLine($"{"Days",-12}{interval.Days,8} {"TotalDays",-18}{interval.TotalDays,21:N3}"); + Console.WriteLine($"{"Hours",-12}{interval.Hours,8} {"TotalHours",-18}{interval.TotalHours,21:N3}"); + Console.WriteLine($"{"Minutes",-12}{interval.Minutes,8} {"TotalMinutes",-18}{interval.TotalMinutes,21:N3}"); + Console.WriteLine($"{"Seconds",-12}{interval.Seconds,8} {"TotalSeconds",-18}{interval.TotalSeconds,21:N3}"); + Console.WriteLine($"{"Milliseconds",-12}{interval.Milliseconds,8} {"TotalMilliseconds",-18}{interval.TotalMilliseconds,21:N3}"); + Console.WriteLine($"{null,-12}{null,8} {"Ticks",-18}{interval.Ticks,21:N0}"); + } } // The example displays the following output if the current culture is en-US: // TimeSpan( 1 ) 00:00:00.0000001 diff --git a/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs b/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs index 4e15130925d..2cb69588d73 100644 --- a/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs +++ b/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs @@ -5,14 +5,14 @@ class DuraNegaUnaryDemo { - const string dataFmt = "{0,22}{1,22}{2,22}" ; + const string dataFmt = "{0,22}{1,22}{2,22}"; - static void ShowDurationNegate( TimeSpan interval ) + static void ShowDurationNegate(TimeSpan interval) { - // Display the TimeSpan value and the results of the + // Display the TimeSpan value and the results of the // Duration and Negate methods. - Console.WriteLine( dataFmt, - interval, interval.Duration( ), interval.Negate( ) ); + Console.WriteLine(dataFmt, + interval, interval.Duration(), interval.Negate()); } static void Main() @@ -21,26 +21,26 @@ static void Main() "This example of TimeSpan.Duration( ), " + "TimeSpan.Negate( ), \nand the TimeSpan Unary " + "Negation and Unary Plus operators \n" + - "generates the following output.\n" ); - Console.WriteLine( dataFmt, - "TimeSpan", "Duration( )", "Negate( )" ); - Console.WriteLine( dataFmt, - "--------", "-----------", "---------" ); + "generates the following output.\n"); + Console.WriteLine(dataFmt, + "TimeSpan", "Duration( )", "Negate( )"); + Console.WriteLine(dataFmt, + "--------", "-----------", "---------"); // Create TimeSpan objects and apply the Unary Negation // and Unary Plus operators to them. - ShowDurationNegate( new TimeSpan( 1 ) ); - ShowDurationNegate( new TimeSpan( -1234567 ) ); - ShowDurationNegate( - + new TimeSpan( 0, 0, 10, -20, -30 ) ); - ShowDurationNegate( - + new TimeSpan( 0, -10, 20, -30, 40 ) ); - ShowDurationNegate( - - new TimeSpan( 1, 10, 20, 40, 160 ) ); - ShowDurationNegate( - - new TimeSpan( -10, -20, -30, -40, -50 ) ); - } -} + ShowDurationNegate(new TimeSpan(1)); + ShowDurationNegate(new TimeSpan(-1234567)); + ShowDurationNegate( + +new TimeSpan(0, 0, 10, -20, -30)); + ShowDurationNegate( + +new TimeSpan(0, -10, 20, -30, 40)); + ShowDurationNegate( + -new TimeSpan(1, 10, 20, 40, 160)); + ShowDurationNegate( + -new TimeSpan(-10, -20, -30, -40, -50)); + } +} /* This example of TimeSpan.Duration( ), TimeSpan.Negate( ), @@ -55,5 +55,5 @@ TimeSpan Duration( ) Negate( ) -09:40:29.9600000 09:40:29.9600000 09:40:29.9600000 -1.10:20:40.1600000 1.10:20:40.1600000 1.10:20:40.1600000 10.20:30:40.0500000 10.20:30:40.0500000 -10.20:30:40.0500000 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs b/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs index 977271ac7f6..d20af5e45e3 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs @@ -2,53 +2,53 @@ public class Class1 { - public static void Main() - { - Class1 cl1 = new Class1(); - cl1.InstantiateMinutes(); - cl1.InstantiateDays(); - cl1.InstantiateHours(); - cl1.InstantiateMilliseconds(); - cl1.InstantiateSeconds(); - } + public static void Main() + { + Class1 cl1 = new(); + cl1.InstantiateMinutes(); + cl1.InstantiateDays(); + cl1.InstantiateHours(); + cl1.InstantiateMilliseconds(); + cl1.InstantiateSeconds(); + } - private void InstantiateMinutes() - { - // - // The following throws an OverflowException at runtime - TimeSpan maxSpan = TimeSpan.FromMinutes(TimeSpan.MaxValue.TotalMinutes); - // - } + private void InstantiateMinutes() + { + // + // The following throws an OverflowException at runtime + TimeSpan maxSpan = TimeSpan.FromMinutes(TimeSpan.MaxValue.TotalMinutes); + // + } - private void InstantiateDays() - { - // - // The following throws an OverflowException at runtime - TimeSpan maxSpan = TimeSpan.FromDays(TimeSpan.MaxValue.TotalDays); - // - } - - private void InstantiateHours() - { - // - // The following throws an OverflowException at runtime - TimeSpan maxSpan = TimeSpan.FromHours(TimeSpan.MaxValue.TotalHours); - // - } + private void InstantiateDays() + { + // + // The following throws an OverflowException at runtime + TimeSpan maxSpan = TimeSpan.FromDays(TimeSpan.MaxValue.TotalDays); + // + } - private void InstantiateMilliseconds() - { - // - // The following throws an OverflowException at runtime - TimeSpan maxSpan = TimeSpan.FromMilliseconds(TimeSpan.MaxValue.TotalMilliseconds); - // - } + private void InstantiateHours() + { + // + // The following throws an OverflowException at runtime + TimeSpan maxSpan = TimeSpan.FromHours(TimeSpan.MaxValue.TotalHours); + // + } - private void InstantiateSeconds() - { - // - // The following throws an OverflowException at runtime - TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds); - // - } + private void InstantiateMilliseconds() + { + // + // The following throws an OverflowException at runtime + TimeSpan maxSpan = TimeSpan.FromMilliseconds(TimeSpan.MaxValue.TotalMilliseconds); + // + } + + private void InstantiateSeconds() + { + // + // The following throws an OverflowException at runtime + TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds); + // + } } diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs b/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs index 11c3697cb30..f275ead79cb 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs @@ -4,44 +4,42 @@ class FromDaysDemo { - static void GenTimeSpanFromDays( double days ) + static void GenTimeSpanFromDays(double days) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of days. - TimeSpan interval = TimeSpan.FromDays( days ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromDays(days); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", days, timeInterval ); - } + Console.WriteLine($"{days,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromDays( double )\n" + - "generates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromDays", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "--------", "--------" ); + "generates the following output.\n"); + Console.WriteLine($"{"FromDays",21}{"TimeSpan",18}"); + Console.WriteLine($"{"--------",21}{"--------",18}"); - GenTimeSpanFromDays( 0.000000006 ); - GenTimeSpanFromDays( 0.000000017 ); - GenTimeSpanFromDays( 0.000123456 ); - GenTimeSpanFromDays( 1.234567898 ); - GenTimeSpanFromDays( 12345.678987654 ); - GenTimeSpanFromDays( 0.000011574 ); - GenTimeSpanFromDays( 0.000694444 ); - GenTimeSpanFromDays( 0.041666666 ); - GenTimeSpanFromDays( 1 ); - GenTimeSpanFromDays( 20.84745602 ); - } -} + GenTimeSpanFromDays(0.000000006); + GenTimeSpanFromDays(0.000000017); + GenTimeSpanFromDays(0.000123456); + GenTimeSpanFromDays(1.234567898); + GenTimeSpanFromDays(12345.678987654); + GenTimeSpanFromDays(0.000011574); + GenTimeSpanFromDays(0.000694444); + GenTimeSpanFromDays(0.041666666); + GenTimeSpanFromDays(1); + GenTimeSpanFromDays(20.84745602); + } +} /* This example of TimeSpan.FromDays( double ) @@ -59,5 +57,5 @@ FromDays TimeSpan 0.041666666 01:00:00 1 1.00:00:00 20.84745602 20.20:20:20.2000000 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs b/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs index ab7476e372f..9b49c4355d2 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs @@ -4,44 +4,42 @@ class FromHoursDemo { - static void GenTimeSpanFromHours( double hours ) + static void GenTimeSpanFromHours(double hours) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of hours. - TimeSpan interval = TimeSpan.FromHours( hours ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromHours(hours); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", hours, timeInterval ); - } + Console.WriteLine($"{hours,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromHours( double )\n" + - "generates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromHours", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "---------", "--------" ); + "generates the following output.\n"); + Console.WriteLine($"{"FromHours",21}{"TimeSpan",18}"); + Console.WriteLine($"{"---------",21}{"--------",18}"); - GenTimeSpanFromHours( 0.0000002 ); - GenTimeSpanFromHours( 0.0000003 ); - GenTimeSpanFromHours( 0.0012345 ); - GenTimeSpanFromHours( 12.3456789 ); - GenTimeSpanFromHours( 123456.7898765 ); - GenTimeSpanFromHours( 0.0002777 ); - GenTimeSpanFromHours( 0.0166666 ); - GenTimeSpanFromHours( 1 ); - GenTimeSpanFromHours( 24 ); - GenTimeSpanFromHours( 500.3389445 ); - } -} + GenTimeSpanFromHours(0.0000002); + GenTimeSpanFromHours(0.0000003); + GenTimeSpanFromHours(0.0012345); + GenTimeSpanFromHours(12.3456789); + GenTimeSpanFromHours(123456.7898765); + GenTimeSpanFromHours(0.0002777); + GenTimeSpanFromHours(0.0166666); + GenTimeSpanFromHours(1); + GenTimeSpanFromHours(24); + GenTimeSpanFromHours(500.3389445); + } +} /* This example of TimeSpan.FromHours( double ) @@ -59,5 +57,5 @@ FromHours TimeSpan 1 01:00:00 24 1.00:00:00 500.3389445 20.20:20:20.2000000 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs b/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs index 4c41285c1c0..74c2d5fba34 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs @@ -4,44 +4,42 @@ class FromMillisecDemo { - static void GenTimeSpanFromMillisec( Double millisec ) + static void GenTimeSpanFromMillisec(double millisec) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of milliseconds. - TimeSpan interval = TimeSpan.FromMilliseconds( millisec ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromMilliseconds(millisec); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", millisec, timeInterval ); - } + Console.WriteLine($"{millisec,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromMilliseconds( " + - "double )\ngenerates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromMilliseconds", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "----------------", "--------" ); + "double )\ngenerates the following output.\n"); + Console.WriteLine($"{"FromMilliseconds",21}{"TimeSpan",18}"); + Console.WriteLine($"{"----------------",21}{"--------",18}"); - GenTimeSpanFromMillisec( 1 ); - GenTimeSpanFromMillisec( 1.5 ); - GenTimeSpanFromMillisec( 12345.6 ); - GenTimeSpanFromMillisec( 123456789.8 ); - GenTimeSpanFromMillisec( 1234567898765.4 ); - GenTimeSpanFromMillisec( 1000 ); - GenTimeSpanFromMillisec( 60000 ); - GenTimeSpanFromMillisec( 3600000 ); - GenTimeSpanFromMillisec( 86400000 ); - GenTimeSpanFromMillisec( 1801220200 ); - } -} + GenTimeSpanFromMillisec(1); + GenTimeSpanFromMillisec(1.5); + GenTimeSpanFromMillisec(12345.6); + GenTimeSpanFromMillisec(123456789.8); + GenTimeSpanFromMillisec(1234567898765.4); + GenTimeSpanFromMillisec(1000); + GenTimeSpanFromMillisec(60000); + GenTimeSpanFromMillisec(3600000); + GenTimeSpanFromMillisec(86400000); + GenTimeSpanFromMillisec(1801220200); + } +} /* This example of TimeSpan.FromMilliseconds( double ) diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs b/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs index c60b80fa9e9..091b935590a 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs @@ -4,44 +4,42 @@ class FromMinutesDemo { - static void GenTimeSpanFromMinutes( double minutes ) + static void GenTimeSpanFromMinutes(double minutes) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of minutes. - TimeSpan interval = TimeSpan.FromMinutes( minutes ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromMinutes(minutes); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", minutes, timeInterval ); - } + Console.WriteLine($"{minutes,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromMinutes( double )\n" + - "generates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromMinutes", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "-----------", "--------" ); + "generates the following output.\n"); + Console.WriteLine($"{"FromMinutes",21}{"TimeSpan",18}"); + Console.WriteLine($"{"-----------",21}{"--------",18}"); - GenTimeSpanFromMinutes( 0.00001 ); - GenTimeSpanFromMinutes( 0.00002 ); - GenTimeSpanFromMinutes( 0.12345 ); - GenTimeSpanFromMinutes( 1234.56789 ); - GenTimeSpanFromMinutes( 12345678.98765 ); - GenTimeSpanFromMinutes( 0.01666 ); - GenTimeSpanFromMinutes( 1 ); - GenTimeSpanFromMinutes( 60 ); - GenTimeSpanFromMinutes( 1440 ); - GenTimeSpanFromMinutes( 30020.33667 ); - } -} + GenTimeSpanFromMinutes(0.00001); + GenTimeSpanFromMinutes(0.00002); + GenTimeSpanFromMinutes(0.12345); + GenTimeSpanFromMinutes(1234.56789); + GenTimeSpanFromMinutes(12345678.98765); + GenTimeSpanFromMinutes(0.01666); + GenTimeSpanFromMinutes(1); + GenTimeSpanFromMinutes(60); + GenTimeSpanFromMinutes(1440); + GenTimeSpanFromMinutes(30020.33667); + } +} /* This example of TimeSpan.FromMinutes( double ) @@ -59,5 +57,5 @@ FromMinutes TimeSpan 60 01:00:00 1440 1.00:00:00 30020.33667 20.20:20:20.2000000 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs b/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs index 9fbd25c99f6..db0b9746b25 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs @@ -4,44 +4,42 @@ class FromSecondsDemo { - static void GenTimeSpanFromSeconds( double seconds ) + static void GenTimeSpanFromSeconds(double seconds) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of seconds. - TimeSpan interval = TimeSpan.FromSeconds( seconds ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromSeconds(seconds); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", seconds, timeInterval ); - } + Console.WriteLine($"{seconds,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromSeconds( double )\n" + - "generates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromSeconds", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "-----------", "--------" ); + "generates the following output.\n"); + Console.WriteLine($"{"FromSeconds",21}{"TimeSpan",18}"); + Console.WriteLine($"{"-----------",21}{"--------",18}"); - GenTimeSpanFromSeconds( 0.001 ); - GenTimeSpanFromSeconds( 0.0015 ); - GenTimeSpanFromSeconds( 12.3456 ); - GenTimeSpanFromSeconds( 123456.7898 ); - GenTimeSpanFromSeconds( 1234567898.7654 ); - GenTimeSpanFromSeconds( 1 ); - GenTimeSpanFromSeconds( 60 ); - GenTimeSpanFromSeconds( 3600 ); - GenTimeSpanFromSeconds( 86400 ); - GenTimeSpanFromSeconds( 1801220.2 ); - } -} + GenTimeSpanFromSeconds(0.001); + GenTimeSpanFromSeconds(0.0015); + GenTimeSpanFromSeconds(12.3456); + GenTimeSpanFromSeconds(123456.7898); + GenTimeSpanFromSeconds(1234567898.7654); + GenTimeSpanFromSeconds(1); + GenTimeSpanFromSeconds(60); + GenTimeSpanFromSeconds(3600); + GenTimeSpanFromSeconds(86400); + GenTimeSpanFromSeconds(1801220.2); + } +} /* This example of TimeSpan.FromSeconds( double ) @@ -59,5 +57,5 @@ FromSeconds TimeSpan 3600 01:00:00 86400 1.00:00:00 1801220.2 20.20:20:20.2000000 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs b/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs index 51361c5034e..d12342c7df3 100644 --- a/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs +++ b/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs @@ -4,44 +4,42 @@ class FromTicksDemo { - static void GenTimeSpanFromTicks( long ticks ) + static void GenTimeSpanFromTicks(long ticks) { - // Create a TimeSpan object and TimeSpan string from + // Create a TimeSpan object and TimeSpan string from // a number of ticks. - TimeSpan interval = TimeSpan.FromTicks( ticks ); - string timeInterval = interval.ToString( ); + TimeSpan interval = TimeSpan.FromTicks(ticks); + string timeInterval = interval.ToString(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,21}{1,26}", ticks, timeInterval ); - } + Console.WriteLine($"{ticks,21}{timeInterval,26}"); + } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.FromTicks( long )\n" + - "generates the following output.\n" ); - Console.WriteLine( "{0,21}{1,18}", - "FromTicks", "TimeSpan" ); - Console.WriteLine( "{0,21}{1,18}", - "---------", "--------" ); + "generates the following output.\n"); + Console.WriteLine($"{"FromTicks",21}{"TimeSpan",18}"); + Console.WriteLine($"{"---------",21}{"--------",18}"); - GenTimeSpanFromTicks( 1 ); - GenTimeSpanFromTicks( 12345 ); - GenTimeSpanFromTicks( 123456789 ); - GenTimeSpanFromTicks( 1234567898765 ); - GenTimeSpanFromTicks( 12345678987654321 ); - GenTimeSpanFromTicks( 10000000 ); - GenTimeSpanFromTicks( 600000000 ); - GenTimeSpanFromTicks( 36000000000 ); - GenTimeSpanFromTicks( 864000000000 ); - GenTimeSpanFromTicks( 18012202000000 ); - } -} + GenTimeSpanFromTicks(1); + GenTimeSpanFromTicks(12345); + GenTimeSpanFromTicks(123456789); + GenTimeSpanFromTicks(1234567898765); + GenTimeSpanFromTicks(12345678987654321); + GenTimeSpanFromTicks(10000000); + GenTimeSpanFromTicks(600000000); + GenTimeSpanFromTicks(36000000000); + GenTimeSpanFromTicks(864000000000); + GenTimeSpanFromTicks(18012202000000); + } +} /* This example of TimeSpan.FromTicks( long ) diff --git a/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs b/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs index 09bbdfd2983..d801da32c6c 100644 --- a/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs +++ b/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs @@ -4,53 +4,51 @@ class GetHashCode { - static void DisplayHashCode( TimeSpan interval ) + static void DisplayHashCode(TimeSpan interval) { - // Create a hash code and a string representation of + // Create a hash code and a string representation of // the TimeSpan parameter. - string timeInterval = interval.ToString( ); - int hashCode = interval.GetHashCode( ); + string timeInterval = interval.ToString(); + int hashCode = interval.GetHashCode(); - // Pad the end of the TimeSpan string with spaces if it + // Pad the end of the TimeSpan string with spaces if it // does not contain milliseconds. - int pIndex = timeInterval.IndexOf( ':' ); - pIndex = timeInterval.IndexOf( '.', pIndex ); - if( pIndex < 0 ) timeInterval += " "; + int pIndex = timeInterval.IndexOf(':'); + pIndex = timeInterval.IndexOf('.', pIndex); + if (pIndex < 0) timeInterval += " "; - Console.WriteLine( "{0,22} 0x{1:X8}, {1}", - timeInterval, hashCode ); + Console.WriteLine("{0,22} 0x{1:X8}, {1}", + timeInterval, hashCode); } - static void Main( ) + static void Main() { Console.WriteLine( "This example of TimeSpan.GetHashCode( ) generates " + "the following \noutput, which displays " + "the hash codes of representative TimeSpan \n" + - "objects in hexadecimal and decimal formats.\n" ); - Console.WriteLine( "{0,22} {1,10}", - "TimeSpan ", "Hash Code" ); - Console.WriteLine( "{0,22} {1,10}", - "-------- ", "---------" ); + "objects in hexadecimal and decimal formats.\n"); + Console.WriteLine($"{"TimeSpan ",22} {"Hash Code",10}"); + Console.WriteLine($"{"-------- ",22} {"---------",10}"); - DisplayHashCode( new TimeSpan( 0 ) ); - DisplayHashCode( new TimeSpan( 1 ) ); - DisplayHashCode( new TimeSpan( 0, 0, 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 0, 1, 0 ) ); - DisplayHashCode( new TimeSpan( 1, 0, 0 ) ); - DisplayHashCode( new TimeSpan( 36000000001 ) ); - DisplayHashCode( new TimeSpan( 0, 1, 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 1, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 1, 0, 0, 0 ) ); - DisplayHashCode( new TimeSpan( 864000000001 ) ); - DisplayHashCode( new TimeSpan( 1, 0, 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 1, 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 100, 0, 0, 0 ) ); - DisplayHashCode( new TimeSpan( 100, 0, 0, 0, 1 ) ); - DisplayHashCode( new TimeSpan( 100, 0, 0, 1 ) ); - } -} + DisplayHashCode(new TimeSpan(0)); + DisplayHashCode(new TimeSpan(1)); + DisplayHashCode(new TimeSpan(0, 0, 0, 0, 1)); + DisplayHashCode(new TimeSpan(0, 0, 1)); + DisplayHashCode(new TimeSpan(0, 1, 0)); + DisplayHashCode(new TimeSpan(1, 0, 0)); + DisplayHashCode(new TimeSpan(36000000001)); + DisplayHashCode(new TimeSpan(0, 1, 0, 0, 1)); + DisplayHashCode(new TimeSpan(1, 0, 1)); + DisplayHashCode(new TimeSpan(1, 0, 0, 0)); + DisplayHashCode(new TimeSpan(864000000001)); + DisplayHashCode(new TimeSpan(1, 0, 0, 0, 1)); + DisplayHashCode(new TimeSpan(1, 0, 0, 1)); + DisplayHashCode(new TimeSpan(100, 0, 0, 0)); + DisplayHashCode(new TimeSpan(100, 0, 0, 0, 1)); + DisplayHashCode(new TimeSpan(100, 0, 0, 1)); + } +} /* This example of TimeSpan.GetHashCode( ) generates the following @@ -75,5 +73,5 @@ TimeSpan Hash Code 100.00:00:00 0x914F4E94, -1857073516 100.00:00:00.0010000 0x914F6984, -1857066620 100.00:00:01 0x91E7D814, -1847076844 -*/ +*/ // diff --git a/snippets/csharp/System/TimeSpan/MaxValue/fields.cs b/snippets/csharp/System/TimeSpan/MaxValue/fields.cs index 4005b3ed569..7a1ebfad4a0 100644 --- a/snippets/csharp/System/TimeSpan/MaxValue/fields.cs +++ b/snippets/csharp/System/TimeSpan/MaxValue/fields.cs @@ -4,51 +4,51 @@ class TimeSpanFieldsDemo { - // Pad the end of a TimeSpan string with spaces if it does not + // Pad the end of a TimeSpan string with spaces if it does not // contain milliseconds. - static string Align( TimeSpan interval ) + static string Align(TimeSpan interval) { - string intervalStr = interval.ToString( ); - int pointIndex = intervalStr.IndexOf( ':' ); + string intervalStr = interval.ToString(); + int pointIndex = intervalStr.IndexOf(':'); - pointIndex = intervalStr.IndexOf( '.', pointIndex ); - if( pointIndex < 0 ) intervalStr += " "; + pointIndex = intervalStr.IndexOf('.', pointIndex); + if (pointIndex < 0) intervalStr += " "; return intervalStr; - } + } - static void Main( ) + static void Main() { - const string numberFmt = "{0,-22}{1,18:N0}" ; - const string timeFmt = "{0,-22}{1,26}" ; + const string numberFmt = "{0,-22}{1,18:N0}"; + const string timeFmt = "{0,-22}{1,26}"; - Console.WriteLine( + Console.WriteLine( "This example of the fields of the TimeSpan class" + - "\ngenerates the following output.\n" ); - Console.WriteLine( numberFmt, "Field", "Value" ); - Console.WriteLine( numberFmt, "-----", "-----" ); + "\ngenerates the following output.\n"); + Console.WriteLine(numberFmt, "Field", "Value"); + Console.WriteLine(numberFmt, "-----", "-----"); // Display the maximum, minimum, and zero TimeSpan values. - Console.WriteLine( timeFmt, "Maximum TimeSpan", - Align( TimeSpan.MaxValue ) ); - Console.WriteLine( timeFmt, "Minimum TimeSpan", - Align( TimeSpan.MinValue ) ); - Console.WriteLine( timeFmt, "Zero TimeSpan", - Align( TimeSpan.Zero ) ); - Console.WriteLine( ); + Console.WriteLine(timeFmt, "Maximum TimeSpan", + Align(TimeSpan.MaxValue)); + Console.WriteLine(timeFmt, "Minimum TimeSpan", + Align(TimeSpan.MinValue)); + Console.WriteLine(timeFmt, "Zero TimeSpan", + Align(TimeSpan.Zero)); + Console.WriteLine(); // Display the ticks-per-time-unit fields. - Console.WriteLine( numberFmt, "Ticks per day", - TimeSpan.TicksPerDay ); - Console.WriteLine( numberFmt, "Ticks per hour", - TimeSpan.TicksPerHour ); - Console.WriteLine( numberFmt, "Ticks per minute", - TimeSpan.TicksPerMinute ); - Console.WriteLine( numberFmt, "Ticks per second", - TimeSpan.TicksPerSecond ); - Console.WriteLine( numberFmt, "Ticks per millisecond", - TimeSpan.TicksPerMillisecond ); + Console.WriteLine(numberFmt, "Ticks per day", + TimeSpan.TicksPerDay); + Console.WriteLine(numberFmt, "Ticks per hour", + TimeSpan.TicksPerHour); + Console.WriteLine(numberFmt, "Ticks per minute", + TimeSpan.TicksPerMinute); + Console.WriteLine(numberFmt, "Ticks per second", + TimeSpan.TicksPerSecond); + Console.WriteLine(numberFmt, "Ticks per millisecond", + TimeSpan.TicksPerMillisecond); } -} +} /* This example of the fields of the TimeSpan class diff --git a/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs b/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs index c93d7f01285..a890a098afa 100644 --- a/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs +++ b/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs @@ -1,74 +1,77 @@ -using System; +using System; public class Example { - public static void Main() - { - Implicit(); - Console.WriteLine(); - Explicit(); - Console.WriteLine(); - TimeSpanOperation(); - Console.WriteLine(); - Parse(); - Console.WriteLine(); - } + public static void Main() + { + Implicit(); + Console.WriteLine(); + Explicit(); + Console.WriteLine(); + TimeSpanOperation(); + Console.WriteLine(); + Parse(); + Console.WriteLine(); + } - private static void Implicit() - { - // - TimeSpan interval = new TimeSpan(); - Console.WriteLine(interval.Equals(TimeSpan.Zero)); // Displays "True". - // - } - - private static void Explicit() - { - // - TimeSpan interval = new TimeSpan(2, 14, 18); - Console.WriteLine(interval.ToString()); - - // Displays "02:14:18". - // - } - - private static void TimeSpanOperation() - { - // - DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0); - DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0); - TimeSpan travelTime = arrival - departure; - Console.WriteLine($"{arrival} - {departure} = {travelTime}"); - - // The example displays the following output: - // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00 - // - } - - private static void Parse() - { - // - string[] values = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"}; - foreach (string value in values) - { - try { - TimeSpan ts = TimeSpan.Parse(value); - Console.WriteLine($"'{value}' --> {ts}"); - } - catch (FormatException) { - Console.WriteLine($"Unable to parse '{value}'"); - } - catch (OverflowException) { - Console.WriteLine($"'{value}' is outside the range of a TimeSpan."); - } - } - - // The example displays the following output: - // '12' --> 12.00:00:00 - // Unable to parse '31.' - // '5.8:32:16' --> 5.08:32:16 - // '12:12:15.95' --> 12:12:15.9500000 - // Unable to parse '.12' - // - } + private static void Implicit() + { + // + TimeSpan interval = new(); + Console.WriteLine(interval.Equals(TimeSpan.Zero)); // Displays "True". + // + } + + private static void Explicit() + { + // + TimeSpan interval = new(2, 14, 18); + Console.WriteLine(interval); + + // Displays "02:14:18". + // + } + + private static void TimeSpanOperation() + { + // + DateTime departure = new(2010, 6, 12, 18, 32, 0); + DateTime arrival = new(2010, 6, 13, 22, 47, 0); + TimeSpan travelTime = arrival - departure; + Console.WriteLine($"{arrival} - {departure} = {travelTime}"); + + // The example displays the following output: + // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00 + // + } + + private static void Parse() + { + // + string[] values = [ "12", "31.", "5.8:32:16", "12:12:15.95", ".12" ]; + foreach (string value in values) + { + try + { + TimeSpan ts = TimeSpan.Parse(value); + Console.WriteLine($"'{value}' --> {ts}"); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{value}' is outside the range of a TimeSpan."); + } + } + + // The example displays the following output: + // '12' --> 12.00:00:00 + // Unable to parse '31.' + // '5.8:32:16' --> 5.08:32:16 + // '12:12:15.95' --> 12:12:15.9500000 + // Unable to parse '.12' + // + } } diff --git a/snippets/csharp/System/TimeSpan/Overview/structure1.cs b/snippets/csharp/System/TimeSpan/Overview/structure1.cs index f034ea01cd4..fa7e112f27c 100644 --- a/snippets/csharp/System/TimeSpan/Overview/structure1.cs +++ b/snippets/csharp/System/TimeSpan/Overview/structure1.cs @@ -2,43 +2,43 @@ public class StructureExample1 { - public static void Main() - { - // - // Define two dates. - DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15); - DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30); + public static void Main() + { + // + // Define two dates. + DateTime date1 = new(2010, 1, 1, 8, 0, 15); + DateTime date2 = new(2010, 8, 18, 13, 30, 30); - // Calculate the interval between the two dates. - TimeSpan interval = date2 - date1; - Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString()); + // Calculate the interval between the two dates. + TimeSpan interval = date2 - date1; + Console.WriteLine($"{date2} - {date1} = {interval}"); - // Display individual properties of the resulting TimeSpan object. - Console.WriteLine(" {0,-35} {1,20}", "Value of Days Component:", interval.Days); - Console.WriteLine(" {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays); - Console.WriteLine(" {0,-35} {1,20}", "Value of Hours Component:", interval.Hours); - Console.WriteLine(" {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours); - Console.WriteLine(" {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes); - Console.WriteLine(" {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes); - Console.WriteLine(" {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds); - Console.WriteLine(" {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds); - Console.WriteLine(" {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds); - Console.WriteLine(" {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds); - Console.WriteLine(" {0,-35} {1,20:N0}", "Ticks:", interval.Ticks); - - // This example displays the following output: - // 8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15 - // Value of Days Component: 229 - // Total Number of Days: 229.229340277778 - // Value of Hours Component: 5 - // Total Number of Hours: 5501.50416666667 - // Value of Minutes Component: 30 - // Total Number of Minutes: 330090.25 - // Value of Seconds Component: 15 - // Total Number of Seconds: 19,805,415 - // Value of Milliseconds Component: 0 - // Total Number of Milliseconds: 19,805,415,000 - // Ticks: 198,054,150,000,000 - // - } + // Display individual properties of the resulting TimeSpan object. + Console.WriteLine($" {"Value of Days Component:",-35} {interval.Days,20}"); + Console.WriteLine($" {"Total Number of Days:",-35} {interval.TotalDays,20}"); + Console.WriteLine($" {"Value of Hours Component:",-35} {interval.Hours,20}"); + Console.WriteLine($" {"Total Number of Hours:",-35} {interval.TotalHours,20}"); + Console.WriteLine($" {"Value of Minutes Component:",-35} {interval.Minutes,20}"); + Console.WriteLine($" {"Total Number of Minutes:",-35} {interval.TotalMinutes,20}"); + Console.WriteLine($" {"Value of Seconds Component:",-35} {interval.Seconds,20:N0}"); + Console.WriteLine($" {"Total Number of Seconds:",-35} {interval.TotalSeconds,20:N0}"); + Console.WriteLine($" {"Value of Milliseconds Component:",-35} {interval.Milliseconds,20:N0}"); + Console.WriteLine($" {"Total Number of Milliseconds:",-35} {interval.TotalMilliseconds,20:N0}"); + Console.WriteLine($" {"Ticks:",-35} {interval.Ticks,20:N0}"); + + // This example displays the following output: + // 8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15 + // Value of Days Component: 229 + // Total Number of Days: 229.229340277778 + // Value of Hours Component: 5 + // Total Number of Hours: 5501.50416666667 + // Value of Minutes Component: 30 + // Total Number of Minutes: 330090.25 + // Value of Seconds Component: 15 + // Total Number of Seconds: 19,805,415 + // Value of Milliseconds Component: 0 + // Total Number of Milliseconds: 19,805,415,000 + // Ticks: 198,054,150,000,000 + // + } } diff --git a/snippets/csharp/System/TimeSpan/Overview/zero1.cs b/snippets/csharp/System/TimeSpan/Overview/zero1.cs index 3ac36200ed2..89a1a293615 100644 --- a/snippets/csharp/System/TimeSpan/Overview/zero1.cs +++ b/snippets/csharp/System/TimeSpan/Overview/zero1.cs @@ -5,7 +5,7 @@ public class Example4 public static void Run() { // - Random rnd = new Random(); + Random rnd = new(); TimeSpan timeSpent = TimeSpan.Zero; @@ -14,15 +14,9 @@ public static void Run() Console.WriteLine($"Total time: {timeSpent}"); - TimeSpan GetTimeBeforeLunch() - { - return new TimeSpan(rnd.Next(3, 6), 0, 0); - } + TimeSpan GetTimeBeforeLunch() => new TimeSpan(rnd.Next(3, 6), 0, 0); - TimeSpan GetTimeAfterLunch() - { - return new TimeSpan(rnd.Next(3, 6), 0, 0); - } + TimeSpan GetTimeAfterLunch() => new TimeSpan(rnd.Next(3, 6), 0, 0); // The example displays output like the following: // Total time: 08:00:00 diff --git a/snippets/csharp/System/TimeSpan/Parse/parse1.cs b/snippets/csharp/System/TimeSpan/Parse/parse1.cs index 0604062b069..15b17ed39e4 100644 --- a/snippets/csharp/System/TimeSpan/Parse/parse1.cs +++ b/snippets/csharp/System/TimeSpan/Parse/parse1.cs @@ -1,39 +1,41 @@ // using System; -using System.Globalization; + using System.Threading; public class Example1 { - public static void Main() - { - string[] values = { "6", "6:12", "6:12:14", "6:12:14:45", + public static void Main() + { + string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45", "6.12:14:45", "6:12:14:45.3448", - "6:12:14:45,3448", "6:34:14:45" }; - string[] cultureNames = { "hr-HR", "en-US"}; + "6:12:14:45,3448", "6:34:14:45" ]; + string[] cultureNames = [ "hr-HR", "en-US" ]; - // Change the current culture. - foreach (string cultureName in cultureNames) - { - Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName); - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.Name); - foreach (string value in values) - { - try { - TimeSpan ts = TimeSpan.Parse(value); - Console.WriteLine("{0} --> {1}", value, ts.ToString("c")); - } - catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); + // Change the current culture. + foreach (string cultureName in cultureNames) + { + Thread.CurrentThread.CurrentCulture = new(cultureName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.Name}"); + foreach (string value in values) + { + try + { + TimeSpan ts = TimeSpan.Parse(value); + Console.WriteLine($"{value} --> {ts.ToString("c")}"); + } + catch (FormatException) + { + Console.WriteLine($"{value}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{value}: Overflow"); + } } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output: // Current Culture: hr-HR diff --git a/snippets/csharp/System/TimeSpan/Parse/parse2.cs b/snippets/csharp/System/TimeSpan/Parse/parse2.cs index fe7eb0fef9a..f73c82f9cab 100644 --- a/snippets/csharp/System/TimeSpan/Parse/parse2.cs +++ b/snippets/csharp/System/TimeSpan/Parse/parse2.cs @@ -1,46 +1,49 @@ // using System; using System.Globalization; -using System.Text.RegularExpressions; + public class Example2 { - public static void Main() - { - string[] values = { "6", "6:12", "6:12:14", "6:12:14:45", + public static void Main() + { + string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45", "6.12:14:45", "6:12:14:45.3448", - "6:12:14:45,3448", "6:34:14:45" }; - CultureInfo[] cultures = { new CultureInfo("en-US"), + "6:12:14:45,3448", "6:34:14:45" ]; + CultureInfo[] cultures = [ new CultureInfo("en-US"), new CultureInfo("ru-RU"), - CultureInfo.InvariantCulture }; + CultureInfo.InvariantCulture ]; - string header = String.Format("{0,-17}", "String"); - foreach (CultureInfo culture in cultures) - header += culture.Equals(CultureInfo.InvariantCulture) ? - String.Format("{0,20}", "Invariant") : - String.Format("{0,20}", culture.Name); - Console.WriteLine(header); - Console.WriteLine(); + string header = $"{"String",-17}"; + foreach (CultureInfo culture in cultures) + header += culture.Equals(CultureInfo.InvariantCulture) ? + $"{"Invariant",20}" : + $"{culture.Name,20}"; + Console.WriteLine(header); + Console.WriteLine(); - foreach (string value in values) - { - Console.Write("{0,-17}", value); - foreach (CultureInfo culture in cultures) - { - try { - TimeSpan ts = TimeSpan.Parse(value, culture); - Console.Write("{0,20}", ts.ToString("c")); - } - catch (FormatException) { - Console.Write("{0,20}", "Bad Format"); - } - catch (OverflowException) { - Console.Write("{0,20}", "Overflow"); + foreach (string value in values) + { + Console.Write($"{value,-17}"); + foreach (CultureInfo culture in cultures) + { + try + { + TimeSpan ts = TimeSpan.Parse(value, culture); + Console.Write($"{ts.ToString("c"),20}"); + } + catch (FormatException) + { + Console.Write($"{"Bad Format",20}"); + } + catch (OverflowException) + { + Console.Write($"{"Overflow",20}"); + } } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output: // String en-US ru-RU Invariant diff --git a/snippets/csharp/System/TimeSpan/ParseExact/Program.cs b/snippets/csharp/System/TimeSpan/ParseExact/Program.cs new file mode 100644 index 00000000000..fa847f92faa --- /dev/null +++ b/snippets/csharp/System/TimeSpan/ParseExact/Program.cs @@ -0,0 +1,4 @@ +ParseExactExample1.Run(); +ParseExactExample2.Run(); +ParseExactExample3.Run(); +ParseExactExample4.Run(); diff --git a/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj b/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs index 58e5bae7e8f..5fa76cf250c 100644 --- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs +++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs @@ -2,148 +2,174 @@ using System; using System.Globalization; -public class Example +public class ParseExactExample1 { - public static void Main() - { - string intervalString, format; - TimeSpan interval; - CultureInfo culture; - - // Parse hour:minute value with "g" specifier current culture. - intervalString = "17:14"; - format = "g"; - culture = CultureInfo.CurrentCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", - intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse hour:minute:second value with "G" specifier. - intervalString = "17:14:48"; - format = "G"; - culture = CultureInfo.InvariantCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } + public static void Run() + { + string intervalString, format; + TimeSpan interval; + CultureInfo culture; - // Parse days:hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = new CultureInfo("fr-FR"); - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48,153"; - format = "G"; - try { - interval = TimeSpan.ParseExact(intervalString, format, culture); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } + // Parse hour:minute value with "g" specifier current culture. + intervalString = "17:14"; + format = "g"; + culture = CultureInfo.CurrentCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } - // Parse a single number using the "c" standard format string. - intervalString = "12"; - format = "c"; - try { - interval = TimeSpan.ParseExact(intervalString, format, null); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse a single number using the "%h" custom format string. - format = "%h"; - try { - interval = TimeSpan.ParseExact(intervalString, format, null); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse a single number using the "%s" custom format string. - format = "%s"; - try { - interval = TimeSpan.ParseExact(intervalString, format, null); - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - } + // Parse hour:minute:second value with "G" specifier. + intervalString = "17:14:48"; + format = "G"; + culture = CultureInfo.InvariantCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = new("fr-FR"); + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48,153"; + format = "G"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, culture); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "c" standard format string. + intervalString = "12"; + format = "c"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, null); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "%h" custom format string. + format = "%h"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, null); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "%s" custom format string. + format = "%s"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, null); + Console.WriteLine($"'{intervalString}' --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + } } // The example displays the following output: // '17:14' --> 17:14:00 diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs index 23e8499b04e..ca705832f63 100644 --- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs +++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs @@ -2,155 +2,182 @@ using System; using System.Globalization; -public class Example +public class ParseExactExample2 { - public static void Main() - { - string intervalString, format; - TimeSpan interval; - CultureInfo culture = null; - - // Parse hour:minute value with custom format specifier. - intervalString = "17:14"; - format = "h\\:mm"; - culture = CultureInfo.CurrentCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse hour:minute:second value with "g" specifier. - intervalString = "17:14:48"; - format = "g"; - culture = CultureInfo.InvariantCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse hours:minute.second value with custom format specifier. - intervalString = "17:14:48.153"; - format = @"h\:mm\:ss\.fff"; - culture = null; - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } + public static void Run() + { + string intervalString, format; + TimeSpan interval; + CultureInfo culture = null; - // Parse days:hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse days:hours:minute.second value with a custom format specifier. - intervalString = "3:17:14:48.153"; - format = @"d\:hh\:mm\:ss\.fff"; - culture = null; - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48,153"; - format = "G"; - culture = new CultureInfo("fr-FR"); - try { - interval = TimeSpan.ParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } + // Parse hour:minute value with custom format specifier. + intervalString = "17:14"; + format = "h\\:mm"; + culture = CultureInfo.CurrentCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } - // Parse a single number using the "c" standard format string. - intervalString = "12"; - format = "c"; - try { - interval = TimeSpan.ParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse a single number using the "%h" custom format string. - format = "%h"; - try { - interval = TimeSpan.ParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - - // Parse a single number using the "%s" custom format string. - format = "%s"; - try { - interval = TimeSpan.ParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative); - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - } - catch (FormatException) { - Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format); - } - catch (OverflowException) { - Console.WriteLine("'{0}': Overflow", intervalString); - } - } + // Parse hour:minute:second value with "g" specifier. + intervalString = "17:14:48"; + format = "g"; + culture = CultureInfo.InvariantCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse hours:minute.second value with custom format specifier. + intervalString = "17:14:48.153"; + format = @"h\:mm\:ss\.fff"; + culture = null; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with a custom format specifier. + intervalString = "3:17:14:48.153"; + format = @"d\:hh\:mm\:ss\.fff"; + culture = null; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48,153"; + format = "G"; + culture = new("fr-FR"); + try + { + interval = TimeSpan.ParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "c" standard format string. + intervalString = "12"; + format = "c"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "%h" custom format string. + format = "%h"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + + // Parse a single number using the "%s" custom format string. + format = "%s"; + try + { + interval = TimeSpan.ParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative); + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + } + catch (FormatException) + { + Console.WriteLine($"'{intervalString}': Bad Format for '{format}'"); + } + catch (OverflowException) + { + Console.WriteLine($"'{intervalString}': Overflow"); + } + } } // The example displays the following output: // '17:14' (h\:mm) --> -17:14:00 diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs index 1aabe8a2dc4..a24d6a68a67 100644 --- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs +++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs @@ -2,30 +2,34 @@ using System; using System.Globalization; -public class Example +public class ParseExactExample3 { - public static void Main() - { - string[] inputs = { "3", "16:42", "1:6:52:35.0625", - "1:6:52:35,0625" }; - string[] formats = { "g", "G", "%h"}; - TimeSpan interval; - CultureInfo culture = new CultureInfo("fr-FR"); - - // Parse each string in inputs using formats and the fr-FR culture. - foreach (string input in inputs) { - try { - interval = TimeSpan.ParseExact(input, formats, culture); - Console.WriteLine("{0} --> {1:c}", input, interval); - } - catch (FormatException) { - Console.WriteLine("{0} --> Bad Format", input); - } - catch (OverflowException) { - Console.WriteLine("{0} --> Overflow", input); - } - } - } + public static void Run() + { + string[] inputs = [ "3", "16:42", "1:6:52:35.0625", + "1:6:52:35,0625" ]; + string[] formats = [ "g", "G", "%h" ]; + TimeSpan interval; + CultureInfo culture = new("fr-FR"); + + // Parse each string in inputs using formats and the fr-FR culture. + foreach (string input in inputs) + { + try + { + interval = TimeSpan.ParseExact(input, formats, culture); + Console.WriteLine($"{input} --> {interval:c}"); + } + catch (FormatException) + { + Console.WriteLine($"{input} --> Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{input} --> Overflow"); + } + } + } } // The example displays the following output: // 3 --> 03:00:00 diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs index 95adf76f4e6..4b77efe4d6b 100644 --- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs +++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs @@ -2,31 +2,35 @@ using System; using System.Globalization; -public class Example +public class ParseExactExample4 { - public static void Main() - { - string[] inputs = { "3", "16:42", "1:6:52:35.0625", - "1:6:52:35,0625" }; - string[] formats = { "%h", "g", "G" }; - TimeSpan interval; - CultureInfo culture = new CultureInfo("de-DE"); - - // Parse each string in inputs using formats and the de-DE culture. - foreach (string input in inputs) { - try { - interval = TimeSpan.ParseExact(input, formats, culture, - TimeSpanStyles.AssumeNegative); - Console.WriteLine("{0} --> {1:c}", input, interval); - } - catch (FormatException) { - Console.WriteLine("{0} --> Bad Format", input); - } - catch (OverflowException) { - Console.WriteLine("{0} --> Overflow", input); - } - } - } + public static void Run() + { + string[] inputs = [ "3", "16:42", "1:6:52:35.0625", + "1:6:52:35,0625" ]; + string[] formats = [ "%h", "g", "G" ]; + TimeSpan interval; + CultureInfo culture = new("de-DE"); + + // Parse each string in inputs using formats and the de-DE culture. + foreach (string input in inputs) + { + try + { + interval = TimeSpan.ParseExact(input, formats, culture, + TimeSpanStyles.AssumeNegative); + Console.WriteLine($"{input} --> {interval:c}"); + } + catch (FormatException) + { + Console.WriteLine($"{input} --> Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{input} --> Overflow"); + } + } + } } // The example displays the following output: // 3 --> -03:00:00 diff --git a/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs b/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs index ee6fac4a079..772922fe295 100644 --- a/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs +++ b/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs @@ -2,35 +2,35 @@ public class Example { - public static void Main() - { - // - TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16); + public static void Main() + { + // + TimeSpan baseTimeSpan = new(1, 12, 15, 16); - // Create an array of timespan intervals. - TimeSpan[] intervals = { - TimeSpan.FromDays(1.5), - TimeSpan.FromHours(1.5), - TimeSpan.FromMinutes(45), + // Create an array of timespan intervals. + TimeSpan[] intervals = [ + TimeSpan.FromDays(1.5), + TimeSpan.FromHours(1.5), + TimeSpan.FromMinutes(45), TimeSpan.FromMilliseconds(505), - new TimeSpan(1, 17, 32, 20), - new TimeSpan(-8, 30, 0) - }; + new TimeSpan(1, 17, 32, 20), + new TimeSpan(-8, 30, 0) + ]; - // Calculate a new time interval by adding each element to the base interval. - foreach (var interval in intervals) - Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}", - baseTimeSpan, interval, baseTimeSpan.Subtract(interval), - interval < TimeSpan.Zero ? "-" : "", - baseTimeSpan < interval.Duration() ? "-" : ""); + // Calculate a new time interval by adding each element to the base interval. + foreach (var interval in intervals) + Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}", + baseTimeSpan, interval, baseTimeSpan.Subtract(interval), + interval < TimeSpan.Zero ? "-" : "", + baseTimeSpan < interval.Duration() ? "-" : ""); - // The example displays the following output: - // 1:12:15:16 - 1:12:00:00.0000 = 0:00:15:16.0000 - // 1:12:15:16 - 0:01:30:00.0000 = 1:10:45:16.0000 - // 1:12:15:16 - 0:00:45:00.0000 = 1:11:30:16.0000 - // 1:12:15:16 - 0:00:00:00.5050 = 1:12:15:15.4950 - // 1:12:15:16 - 1:17:32:20.0000 = -0:05:17:04.0000 - // 1:12:15:16 - -0:07:30:00.0000 = 1:19:45:16.0000 - // - } + // The example displays the following output: + // 1:12:15:16 - 1:12:00:00.0000 = 0:00:15:16.0000 + // 1:12:15:16 - 0:01:30:00.0000 = 1:10:45:16.0000 + // 1:12:15:16 - 0:00:45:00.0000 = 1:11:30:16.0000 + // 1:12:15:16 - 0:00:00:00.5050 = 1:12:15:15.4950 + // 1:12:15:16 - 1:17:32:20.0000 = -0:05:17:04.0000 + // 1:12:15:16 - -0:07:30:00.0000 = 1:19:45:16.0000 + // + } } diff --git a/snippets/csharp/System/TimeSpan/ToString/Program.cs b/snippets/csharp/System/TimeSpan/ToString/Program.cs new file mode 100644 index 00000000000..177d5246b61 --- /dev/null +++ b/snippets/csharp/System/TimeSpan/ToString/Program.cs @@ -0,0 +1,3 @@ +TimeSpanToStringExample.Run(); +Class1.Run(); +Example.Run(); diff --git a/snippets/csharp/System/TimeSpan/ToString/Project.csproj b/snippets/csharp/System/TimeSpan/ToString/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TimeSpan/ToString/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TimeSpan/ToString/ToString1.cs b/snippets/csharp/System/TimeSpan/ToString/ToString1.cs index 173f1550dab..2c4fdfd08f1 100644 --- a/snippets/csharp/System/TimeSpan/ToString/ToString1.cs +++ b/snippets/csharp/System/TimeSpan/ToString/ToString1.cs @@ -1,48 +1,48 @@ using System; -public class ToString +public class TimeSpanToStringExample { - public static void Main() - { - // - TimeSpan span; - - // Initialize a time span to zero. - span = TimeSpan.Zero; - Console.WriteLine(span); - - // Initialize a time span to 14 days. - span = new TimeSpan(-14, 0, 0, 0, 0); - Console.WriteLine(span); - - // Initialize a time span to 1:02:03. - span = new TimeSpan(1, 2, 3); - Console.WriteLine(span); - - // Initialize a time span to 250 milliseconds. - span = new TimeSpan(0, 0, 0, 0, 250); - Console.WriteLine(span); - - // Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds. - span = new TimeSpan(99, 23, 59, 59, 999); - Console.WriteLine(span); - - // Initialize a time span to 3 hours. - span = new TimeSpan(3, 0, 0); - Console.WriteLine(span); - - // Initialize a timespan to 25 milliseconds. - span = new TimeSpan(0, 0, 0, 0, 25); - Console.WriteLine(span); - - // The example displays the following output: - // 00:00:00 - // -14.00:00:00 - // 01:02:03 - // 00:00:00.2500000 - // 99.23:59:59.9990000 - // 03:00:00 - // 00:00:00.0250000 - // - } + public static void Run() + { + // + TimeSpan span; + + // Initialize a time span to zero. + span = TimeSpan.Zero; + Console.WriteLine(span); + + // Initialize a time span to 14 days. + span = new(-14, 0, 0, 0, 0); + Console.WriteLine(span); + + // Initialize a time span to 1:02:03. + span = new(1, 2, 3); + Console.WriteLine(span); + + // Initialize a time span to 250 milliseconds. + span = new(0, 0, 0, 0, 250); + Console.WriteLine(span); + + // Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds. + span = new(99, 23, 59, 59, 999); + Console.WriteLine(span); + + // Initialize a time span to 3 hours. + span = new(3, 0, 0); + Console.WriteLine(span); + + // Initialize a timespan to 25 milliseconds. + span = new(0, 0, 0, 0, 25); + Console.WriteLine(span); + + // The example displays the following output: + // 00:00:00 + // -14.00:00:00 + // 01:02:03 + // 00:00:00.2500000 + // 99.23:59:59.9990000 + // 03:00:00 + // 00:00:00.0250000 + // + } } diff --git a/snippets/csharp/System/TimeSpan/ToString/tostring3.cs b/snippets/csharp/System/TimeSpan/ToString/tostring3.cs index 13e72927122..227ae2cf0f3 100644 --- a/snippets/csharp/System/TimeSpan/ToString/tostring3.cs +++ b/snippets/csharp/System/TimeSpan/ToString/tostring3.cs @@ -2,69 +2,69 @@ public class Class1 { - public static void Main() - { - // - TimeSpan[] spans = { - TimeSpan.Zero, - new TimeSpan(-14, 0, 0, 0, 0), - new TimeSpan(1, 2, 3), - new TimeSpan(0, 0, 0, 0, 250), + public static void Run() + { + // + TimeSpan[] spans = [ + TimeSpan.Zero, + new TimeSpan(-14, 0, 0, 0, 0), + new TimeSpan(1, 2, 3), + new TimeSpan(0, 0, 0, 0, 250), new TimeSpan(99, 23, 59, 59, 999), - new TimeSpan(3, 0, 0), - new TimeSpan(0, 0, 0, 0, 25) - }; + new TimeSpan(3, 0, 0), + new TimeSpan(0, 0, 0, 0, 25) + ]; - string[] fmts = { "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" }; - foreach (TimeSpan span in spans) - { - foreach (string fmt in fmts) - Console.WriteLine("{0}: {1}", fmt, span.ToString(fmt)); + string[] fmts = [ "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" ]; + foreach (TimeSpan span in spans) + { + foreach (string fmt in fmts) + Console.WriteLine($"{fmt}: {span.ToString(fmt)}"); - Console.WriteLine(); - } - // The example displays the following output: - // c: 00:00:00 - // g: 0:00:00 - // G: 0:00:00:00.0000000 - // hh\:mm\:ss: 00:00:00 - // %m' min.': 0 min. - // - // c: -14.00:00:00 - // g: -14:0:00:00 - // G: -14:00:00:00.0000000 - // hh\:mm\:ss: 00:00:00 - // %m' min.': 0 min. - // - // c: 01:02:03 - // g: 1:02:03 - // G: 0:01:02:03.0000000 - // hh\:mm\:ss: 01:02:03 - // %m' min.': 2 min. - // - // c: 00:00:00.2500000 - // g: 0:00:00.25 - // G: 0:00:00:00.2500000 - // hh\:mm\:ss: 00:00:00 - // %m' min.': 0 min. - // - // c: 99.23:59:59.9990000 - // g: 99:23:59:59.999 - // G: 99:23:59:59.9990000 - // hh\:mm\:ss: 23:59:59 - // %m' min.': 59 min. - // - // c: 03:00:00 - // g: 3:00:00 - // G: 0:03:00:00.0000000 - // hh\:mm\:ss: 03:00:00 - // %m' min.': 0 min. - // - // c: 00:00:00.0250000 - // g: 0:00:00.025 - // G: 0:00:00:00.0250000 - // hh\:mm\:ss: 00:00:00 - // %m' min.': 0 min. - // - } + Console.WriteLine(); + } + // The example displays the following output: + // c: 00:00:00 + // g: 0:00:00 + // G: 0:00:00:00.0000000 + // hh\:mm\:ss: 00:00:00 + // %m' min.': 0 min. + // + // c: -14.00:00:00 + // g: -14:0:00:00 + // G: -14:00:00:00.0000000 + // hh\:mm\:ss: 00:00:00 + // %m' min.': 0 min. + // + // c: 01:02:03 + // g: 1:02:03 + // G: 0:01:02:03.0000000 + // hh\:mm\:ss: 01:02:03 + // %m' min.': 2 min. + // + // c: 00:00:00.2500000 + // g: 0:00:00.25 + // G: 0:00:00:00.2500000 + // hh\:mm\:ss: 00:00:00 + // %m' min.': 0 min. + // + // c: 99.23:59:59.9990000 + // g: 99:23:59:59.999 + // G: 99:23:59:59.9990000 + // hh\:mm\:ss: 23:59:59 + // %m' min.': 59 min. + // + // c: 03:00:00 + // g: 3:00:00 + // G: 0:03:00:00.0000000 + // hh\:mm\:ss: 03:00:00 + // %m' min.': 0 min. + // + // c: 00:00:00.0250000 + // g: 0:00:00.025 + // G: 0:00:00:00.0250000 + // hh\:mm\:ss: 00:00:00 + // %m' min.': 0 min. + // + } } diff --git a/snippets/csharp/System/TimeSpan/ToString/tostring4.cs b/snippets/csharp/System/TimeSpan/ToString/tostring4.cs index abfc9d0e3cb..341876b4264 100644 --- a/snippets/csharp/System/TimeSpan/ToString/tostring4.cs +++ b/snippets/csharp/System/TimeSpan/ToString/tostring4.cs @@ -4,36 +4,33 @@ public class Example { - public static void Main() - { - TimeSpan[] intervals = { new TimeSpan(38, 30, 15), - new TimeSpan(16, 14, 30) }; - CultureInfo[] cultures = { new CultureInfo("en-US"), - new CultureInfo("fr-FR") }; - string[] formats = {"c", "g", "G", @"hh\:mm\:ss" }; - Console.WriteLine("{0,12} Format {1,22} {2,22}\n", - "Interval", cultures[0].Name, cultures[1].Name); + public static void Run() + { + TimeSpan[] intervals = [ new TimeSpan(38, 30, 15), + new TimeSpan(16, 14, 30) ]; + CultureInfo[] cultures = [ new CultureInfo("en-US"), + new CultureInfo("fr-FR") ]; + string[] formats = [ "c", "g", "G", @"hh\:mm\:ss" ]; + Console.WriteLine($"{"Interval",12} Format {cultures[0].Name,22} {cultures[1].Name,22}\n"); - foreach (var interval in intervals) { - foreach (var fmt in formats) - Console.WriteLine("{0,12} {1,10} {2,22} {3,22}", - interval, fmt, - interval.ToString(fmt, cultures[0]), - interval.ToString(fmt, cultures[1])); - Console.WriteLine(); - } - } + foreach (var interval in intervals) + { + foreach (string fmt in formats) + Console.WriteLine($"{interval,12} {fmt,10} {interval.ToString(fmt, cultures[0]),22} {interval.ToString(fmt, cultures[1]),22}"); + Console.WriteLine(); + } + } } // The example displays the following output: // Interval Format en-US fr-FR -// +// // 1.14:30:15 c 1.14:30:15 1.14:30:15 // 1.14:30:15 g 1:14:30:15 1:14:30:15 // 1.14:30:15 G 1:14:30:15.0000000 1:14:30:15,0000000 // 1.14:30:15 hh\:mm\:ss 14:30:15 14:30:15 -// +// // 16:14:30 c 16:14:30 16:14:30 // 16:14:30 g 16:14:30 16:14:30 // 16:14:30 G 0:16:14:30.0000000 0:16:14:30,0000000 // 16:14:30 hh\:mm\:ss 16:14:30 16:14:30 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs b/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs index 14b4f8aa574..6f02c72adaa 100644 --- a/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs +++ b/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs @@ -2,28 +2,28 @@ public class Example { - public static void Main() - { - // - // Define an interval of 3 days, 16+ hours. - TimeSpan interval = new TimeSpan(3, 16, 42, 45, 750); - Console.WriteLine("Value of TimeSpan: {0}", interval); - - Console.WriteLine("{0:N5} days, as follows:", interval.TotalDays); - Console.WriteLine(" Days: {0,3}", interval.Days); - Console.WriteLine(" Hours: {0,3}", interval.Hours); - Console.WriteLine(" Minutes: {0,3}", interval.Minutes); - Console.WriteLine(" Seconds: {0,3}", interval.Seconds); - Console.WriteLine(" Milliseconds: {0,3}", interval.Milliseconds); + public static void Main() + { + // + // Define an interval of 3 days, 16+ hours. + TimeSpan interval = new(3, 16, 42, 45, 750); + Console.WriteLine($"Value of TimeSpan: {interval}"); - // The example displays the following output: - // Value of TimeSpan: 3.16:42:45.7500000 - // 3.69636 days, as follows: - // Days: 3 - // Hours: 16 - // Minutes: 42 - // Seconds: 45 - // Milliseconds: 750 - // - } + Console.WriteLine($"{interval.TotalDays:N5} days, as follows:"); + Console.WriteLine($" Days: {interval.Days,3}"); + Console.WriteLine($" Hours: {interval.Hours,3}"); + Console.WriteLine($" Minutes: {interval.Minutes,3}"); + Console.WriteLine($" Seconds: {interval.Seconds,3}"); + Console.WriteLine($" Milliseconds: {interval.Milliseconds,3}"); + + // The example displays the following output: + // Value of TimeSpan: 3.16:42:45.7500000 + // 3.69636 days, as follows: + // Days: 3 + // Hours: 16 + // Minutes: 42 + // Seconds: 45 + // Milliseconds: 750 + // + } } diff --git a/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs b/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs index c667cc0911d..efc9ea06c12 100644 --- a/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs +++ b/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs @@ -2,27 +2,26 @@ public class Example { - public static void Main() - { - // - // Define an interval of 1 day, 15+ hours. - TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); - Console.WriteLine("Value of TimeSpan: {0}", interval); - - Console.WriteLine("{0:N5} hours, as follows:", interval.TotalHours); - Console.WriteLine(" Hours: {0,3}", - interval.Days * 24 + interval.Hours); - Console.WriteLine(" Minutes: {0,3}", interval.Minutes); - Console.WriteLine(" Seconds: {0,3}", interval.Seconds); - Console.WriteLine(" Milliseconds: {0,3}", interval.Milliseconds); + public static void Main() + { + // + // Define an interval of 1 day, 15+ hours. + TimeSpan interval = new(1, 15, 42, 45, 750); + Console.WriteLine($"Value of TimeSpan: {interval}"); - // The example displays the following output: - // Value of TimeSpan: 1.15:42:45.7500000 - // 39.71271 hours, as follows: - // Hours: 39 - // Minutes: 42 - // Seconds: 45 - // Milliseconds: 750 - // - } + Console.WriteLine($"{interval.TotalHours:N5} hours, as follows:"); + Console.WriteLine($" Hours: {interval.Days * 24 + interval.Hours,3}"); + Console.WriteLine($" Minutes: {interval.Minutes,3}"); + Console.WriteLine($" Seconds: {interval.Seconds,3}"); + Console.WriteLine($" Milliseconds: {interval.Milliseconds,3}"); + + // The example displays the following output: + // Value of TimeSpan: 1.15:42:45.7500000 + // 39.71271 hours, as follows: + // Hours: 39 + // Minutes: 42 + // Seconds: 45 + // Milliseconds: 750 + // + } } diff --git a/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs b/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs index d79e8f3206c..53e4c8b9508 100644 --- a/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs +++ b/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs @@ -2,28 +2,27 @@ public class Example { - public static void Main() - { - // - // Define an interval of 1 day, 15+ hours. - TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); - Console.WriteLine("Value of TimeSpan: {0}", interval); - - Console.WriteLine("There are {0:N5} milliseconds, as follows:", interval.TotalMilliseconds); - long nMilliseconds = interval.Days * 24 * 60 * 60 * 1000 + - interval.Hours *60 * 60 * 1000 + - interval.Minutes * 60 * 1000 + - interval.Seconds * 1000 + - interval.Milliseconds; - Console.WriteLine(" Milliseconds: {0,18:N0}", nMilliseconds); - Console.WriteLine(" Ticks: {0,18:N0}", - nMilliseconds * 10000 - interval.Ticks); + public static void Main() + { + // + // Define an interval of 1 day, 15+ hours. + TimeSpan interval = new(1, 15, 42, 45, 750); + Console.WriteLine($"Value of TimeSpan: {interval}"); - // The example displays the following output: - // Value of TimeSpan: 1.15:42:45.7500000 - // There are 142,965,750.00000 milliseconds, as follows: - // Milliseconds: 142,965,750 - // Ticks: 0 - // - } + Console.WriteLine($"There are {interval.TotalMilliseconds:N5} milliseconds, as follows:"); + long nMilliseconds = interval.Days * 24 * 60 * 60 * 1000 + + interval.Hours * 60 * 60 * 1000 + + interval.Minutes * 60 * 1000 + + interval.Seconds * 1000 + + interval.Milliseconds; + Console.WriteLine($" Milliseconds: {nMilliseconds,18:N0}"); + Console.WriteLine($" Ticks: {nMilliseconds * 10000 - interval.Ticks,18:N0}"); + + // The example displays the following output: + // Value of TimeSpan: 1.15:42:45.7500000 + // There are 142,965,750.00000 milliseconds, as follows: + // Milliseconds: 142,965,750 + // Ticks: 0 + // + } } diff --git a/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs b/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs index b3aa641a06d..534257ccf03 100644 --- a/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs +++ b/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs @@ -2,26 +2,26 @@ public class Example { - public static void Main() - { - // - // Define an interval of 1 day, 15+ hours. - TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); - Console.WriteLine("Value of TimeSpan: {0}", interval); - - Console.WriteLine("{0:N5} minutes, as follows:", interval.TotalMinutes); - Console.WriteLine(" Minutes: {0,5}", interval.Days * 24 * 60 + - interval.Hours * 60 + - interval.Minutes); - Console.WriteLine(" Seconds: {0,5}", interval.Seconds); - Console.WriteLine(" Milliseconds: {0,5}", interval.Milliseconds); + public static void Main() + { + // + // Define an interval of 1 day, 15+ hours. + TimeSpan interval = new(1, 15, 42, 45, 750); + Console.WriteLine($"Value of TimeSpan: {interval}"); - // The example displays the following output: - // Value of TimeSpan: 1.15:42:45.7500000 - // 2,382.76250 minutes, as follows: - // Minutes: 2382 - // Seconds: 45 - // Milliseconds: 750 - // - } + Console.WriteLine($"{interval.TotalMinutes:N5} minutes, as follows:"); + Console.WriteLine($" Minutes: {interval.Days * 24 * 60 + + interval.Hours * 60 + + interval.Minutes,5}"); + Console.WriteLine($" Seconds: {interval.Seconds,5}"); + Console.WriteLine($" Milliseconds: {interval.Milliseconds,5}"); + + // The example displays the following output: + // Value of TimeSpan: 1.15:42:45.7500000 + // 2,382.76250 minutes, as follows: + // Minutes: 2382 + // Seconds: 45 + // Milliseconds: 750 + // + } } diff --git a/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs b/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs index db041c79fd1..784ca177241 100644 --- a/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs +++ b/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs @@ -2,25 +2,25 @@ public class Example { - public static void Main() - { - // - // Define an interval of 1 day, 15+ hours. - TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750); - Console.WriteLine("Value of TimeSpan: {0}", interval); - - Console.WriteLine("{0:N5} seconds, as follows:", interval.TotalSeconds); - Console.WriteLine(" Seconds: {0,8:N0}", interval.Days * 24 * 60 * 60 + - interval.Hours *60 * 60 + - interval.Minutes * 60 + - interval.Seconds); - Console.WriteLine(" Milliseconds: {0,8}", interval.Milliseconds); + public static void Main() + { + // + // Define an interval of 1 day, 15+ hours. + TimeSpan interval = new(1, 15, 42, 45, 750); + Console.WriteLine($"Value of TimeSpan: {interval}"); - // The example displays the following output: - // Value of TimeSpan: 1.15:42:45.7500000 - // 142,965.75000 seconds, as follows: - // Seconds: 142,965 - // Milliseconds: 750 - // - } + Console.WriteLine($"{interval.TotalSeconds:N5} seconds, as follows:"); + Console.WriteLine($" Seconds: {interval.Days * 24 * 60 * 60 + + interval.Hours * 60 * 60 + + interval.Minutes * 60 + + interval.Seconds,8:N0}"); + Console.WriteLine($" Milliseconds: {interval.Milliseconds,8}"); + + // The example displays the following output: + // Value of TimeSpan: 1.15:42:45.7500000 + // 142,965.75000 seconds, as follows: + // Seconds: 142,965 + // Milliseconds: 750 + // + } } diff --git a/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs b/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs index 783b776fbfc..22d3336a17a 100644 --- a/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs +++ b/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs @@ -3,39 +3,37 @@ public class TryParse { - private static void ParseTimeSpan(string intervalStr) - { - // Write the first part of the output line. - Console.Write( "{0,20} ", intervalStr ); + private static void ParseTimeSpan(string intervalStr) + { + // Write the first part of the output line. + Console.Write($"{intervalStr,20} "); - // Parse the parameter, and then convert it back to a string. - TimeSpan intervalVal; - if (TimeSpan.TryParse(intervalStr, out intervalVal)) - { - string intervalToStr = intervalVal.ToString(); - - // Pad the end of the TimeSpan string with spaces if it - // does not contain milliseconds. - int pIndex = intervalToStr.IndexOf(':'); - pIndex = intervalToStr.IndexOf('.', pIndex); - if (pIndex < 0) - intervalToStr += " "; - - Console.WriteLine("{0,21}", intervalToStr); - // Handle failure of TryParse method. - } - else - { - Console.WriteLine("Parse operation failed."); - } - } - - public static void Main() - { - Console.WriteLine( "{0,20} {1,21}", - "String to Parse", "TimeSpan" ); - Console.WriteLine( "{0,20} {1,21}", - "---------------", "---------------------" ); + // Parse the parameter, and then convert it back to a string. + TimeSpan intervalVal; + if (TimeSpan.TryParse(intervalStr, out intervalVal)) + { + string intervalToStr = intervalVal.ToString(); + + // Pad the end of the TimeSpan string with spaces if it + // does not contain milliseconds. + int pIndex = intervalToStr.IndexOf(':'); + pIndex = intervalToStr.IndexOf('.', pIndex); + if (pIndex < 0) + intervalToStr += " "; + + Console.WriteLine($"{intervalToStr,21}"); + // Handle failure of TryParse method. + } + else + { + Console.WriteLine("Parse operation failed."); + } + } + + public static void Main() + { + Console.WriteLine($"{"String to Parse",20} {"TimeSpan",21}"); + Console.WriteLine($"{"---------------",20} {"---------------------",21}"); ParseTimeSpan("0"); ParseTimeSpan("14"); @@ -61,7 +59,7 @@ public static void Main() ParseTimeSpan("10."); ParseTimeSpan("10.12"); ParseTimeSpan("10.12:00"); - } + } } // String to Parse TimeSpan // --------------- --------------------- diff --git a/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs b/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs index 3824d3786a7..b8218ec673d 100644 --- a/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs +++ b/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs @@ -4,42 +4,42 @@ public class Example { - public static void Main() - { - string[] values = { "6", "6:12", "6:12:14", "6:12:14:45", - "6.12:14:45", "6:12:14:45.3448", - "6:12:14:45,3448", "6:34:14:45" }; - CultureInfo[] cultures = { new CultureInfo("en-US"), + public static void Main() + { + string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45", + "6.12:14:45", "6:12:14:45.3448", + "6:12:14:45,3448", "6:34:14:45" ]; + CultureInfo[] cultures = [ new CultureInfo("en-US"), new CultureInfo("ru-RU"), - CultureInfo.InvariantCulture }; - - string header = String.Format("{0,-17}", "String"); - foreach (CultureInfo culture in cultures) - header += culture.Equals(CultureInfo.InvariantCulture) ? - String.Format("{0,20}", "Invariant") : - String.Format("{0,20}", culture.Name); + CultureInfo.InvariantCulture ]; - Console.WriteLine(header); - Console.WriteLine(); - - foreach (string value in values) - { - Console.Write("{0,-17}", value); - foreach (CultureInfo culture in cultures) - { - TimeSpan interval = new TimeSpan(); - if (TimeSpan.TryParse(value, culture, out interval)) - Console.Write("{0,20}", interval.ToString("c")); - else - Console.Write("{0,20}", "Unable to Parse"); - } - Console.WriteLine(); - } - } + string header = $"{"String",-17}"; + foreach (CultureInfo culture in cultures) + header += culture.Equals(CultureInfo.InvariantCulture) ? + $"{"Invariant",20}" : + $"{culture.Name,20}"; + + Console.WriteLine(header); + Console.WriteLine(); + + foreach (string value in values) + { + Console.Write($"{value,-17}"); + foreach (CultureInfo culture in cultures) + { + TimeSpan interval = new(); + if (TimeSpan.TryParse(value, culture, out interval)) + Console.Write($"{interval.ToString("c"),20}"); + else + Console.Write($"{"Unable to Parse",20}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // String en-US ru-RU Invariant -// +// // 6 6.00:00:00 6.00:00:00 6.00:00:00 // 6:12 06:12:00 06:12:00 06:12:00 // 6:12:14 06:12:14 06:12:14 06:12:14 @@ -48,4 +48,4 @@ public static void Main() // 6:12:14:45.3448 6.12:14:45.3448000 Unable to Parse 6.12:14:45.3448000 // 6:12:14:45,3448 Unable to Parse 6.12:14:45.3448000 Unable to Parse // 6:34:14:45 Unable to Parse Unable to Parse Unable to Parse -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs b/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs new file mode 100644 index 00000000000..9f145ec0812 --- /dev/null +++ b/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs @@ -0,0 +1,4 @@ +TryParseExactExample1.Run(); +TryParseExactExample2.Run(); +TryParseExactExample3.Run(); +TryParseExactExample4.Run(); diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj b/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs index 08d4d54eb50..cbe17d7617a 100644 --- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs +++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs @@ -2,93 +2,93 @@ using System; using System.Globalization; -public class Example +public class TryParseExactExample1 { - public static void Main() - { - string intervalString, format; - TimeSpan interval; - CultureInfo culture; - - // Parse hour:minute value with "g" specifier current culture. - intervalString = "17:14"; - format = "g"; - culture = CultureInfo.CurrentCulture; - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse hour:minute:second value with "G" specifier. - intervalString = "17:14:48"; - format = "G"; - culture = CultureInfo.InvariantCulture; - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); + public static void Run() + { + string intervalString, format; + TimeSpan interval; + CultureInfo culture; - // Parse days:hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = new CultureInfo("fr-FR"); - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48,153"; - format = "G"; - if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); + // Parse hour:minute value with "g" specifier current culture. + intervalString = "17:14"; + format = "g"; + culture = CultureInfo.CurrentCulture; + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); - // Parse a single number using the "c" standard format string. - intervalString = "12"; - format = "c"; - if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse a single number using the "%h" custom format string. - format = "%h"; - if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - - // Parse a single number using the "%s" custom format string. - format = "%s"; - if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) - Console.WriteLine("'{0}' --> {1}", intervalString, interval); - else - Console.WriteLine("Unable to parse {0}", intervalString); - } + // Parse hour:minute:second value with "G" specifier. + intervalString = "17:14:48"; + format = "G"; + culture = CultureInfo.InvariantCulture; + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse days:hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = new("fr-FR"); + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48,153"; + format = "G"; + if (TimeSpan.TryParseExact(intervalString, format, culture, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse a single number using the "c" standard format string. + intervalString = "12"; + format = "c"; + if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse a single number using the "%h" custom format string. + format = "%h"; + if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + + // Parse a single number using the "%s" custom format string. + format = "%s"; + if (TimeSpan.TryParseExact(intervalString, format, null, out interval)) + Console.WriteLine($"'{intervalString}' --> {interval}"); + else + Console.WriteLine($"Unable to parse {intervalString}"); + } } // The example displays the following output: // '17:14' --> 17:14:00 diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs index d496905410c..8901e941aea 100644 --- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs +++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs @@ -2,110 +2,101 @@ using System; using System.Globalization; -public class Example +public class TryParseExactExample2 { - public static void Main() - { - string intervalString, format; - TimeSpan interval; - CultureInfo culture = null; - - // Parse hour:minute value with custom format specifier. - intervalString = "17:14"; - format = "h\\:mm"; - culture = CultureInfo.CurrentCulture; - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse hour:minute:second value with "g" specifier. - intervalString = "17:14:48"; - format = "g"; - culture = CultureInfo.InvariantCulture; - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse hours:minute.second value with custom format specifier. - intervalString = "17:14:48.153"; - format = @"h\:mm\:ss\.fff"; - culture = null; - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); + public static void Run() + { + string intervalString, format; + TimeSpan interval; + CultureInfo culture = null; - // Parse days:hours:minute.second value with "G" specifier - // and current (en-US) culture. - intervalString = "3:17:14:48.153"; - format = "G"; - culture = CultureInfo.CurrentCulture; - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse days:hours:minute.second value with a custom format specifier. - intervalString = "3:17:14:48.153"; - format = @"d\:hh\:mm\:ss\.fff"; - culture = null; - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse days:hours:minute.second value with "G" specifier - // and fr-FR culture. - intervalString = "3:17:14:48,153"; - format = "G"; - culture = new CultureInfo("fr-FR"); - if (TimeSpan.TryParseExact(intervalString, format, - culture, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); + // Parse hour:minute value with custom format specifier. + intervalString = "17:14"; + format = "h\\:mm"; + culture = CultureInfo.CurrentCulture; + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); - // Parse a single number using the "c" standard format string. - intervalString = "12"; - format = "c"; - if (TimeSpan.TryParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse a single number using the "%h" custom format string. - format = "%h"; - if (TimeSpan.TryParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - - // Parse a single number using the "%s" custom format string. - format = "%s"; - if (TimeSpan.TryParseExact(intervalString, format, - null, TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval); - else - Console.WriteLine("Unable to parse '{0}' using format {1}", - intervalString, format); - } + // Parse hour:minute:second value with "g" specifier. + intervalString = "17:14:48"; + format = "g"; + culture = CultureInfo.InvariantCulture; + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse hours:minute.second value with custom format specifier. + intervalString = "17:14:48.153"; + format = @"h\:mm\:ss\.fff"; + culture = null; + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse days:hours:minute.second value with "G" specifier + // and current (en-US) culture. + intervalString = "3:17:14:48.153"; + format = "G"; + culture = CultureInfo.CurrentCulture; + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse days:hours:minute.second value with a custom format specifier. + intervalString = "3:17:14:48.153"; + format = @"d\:hh\:mm\:ss\.fff"; + culture = null; + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse days:hours:minute.second value with "G" specifier + // and fr-FR culture. + intervalString = "3:17:14:48,153"; + format = "G"; + culture = new("fr-FR"); + if (TimeSpan.TryParseExact(intervalString, format, + culture, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse a single number using the "c" standard format string. + intervalString = "12"; + format = "c"; + if (TimeSpan.TryParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse a single number using the "%h" custom format string. + format = "%h"; + if (TimeSpan.TryParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + + // Parse a single number using the "%s" custom format string. + format = "%s"; + if (TimeSpan.TryParseExact(intervalString, format, + null, TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"'{intervalString}' ({format}) --> {interval}"); + else + Console.WriteLine($"Unable to parse '{intervalString}' using format {format}"); + } } // The example displays the following output: // '17:14' (h\:mm) --> -17:14:00 diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs index 8a1398b4bed..4caee9407ce 100644 --- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs +++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs @@ -2,24 +2,25 @@ using System; using System.Globalization; -public class Example +public class TryParseExactExample3 { - public static void Main() - { - string[] inputs = { "3", "16:42", "1:6:52:35.0625", - "1:6:52:35,0625" }; - string[] formats = { "g", "G", "%h"}; - TimeSpan interval; - CultureInfo culture = new CultureInfo("fr-FR"); - - // Parse each string in inputs using formats and the fr-FR culture. - foreach (string input in inputs) { - if(TimeSpan.TryParseExact(input, formats, culture, out interval)) - Console.WriteLine("{0} --> {1:c}", input, interval); - else - Console.WriteLine("Unable to parse {0}", input); - } - } + public static void Run() + { + string[] inputs = [ "3", "16:42", "1:6:52:35.0625", + "1:6:52:35,0625" ]; + string[] formats = [ "g", "G", "%h" ]; + TimeSpan interval; + CultureInfo culture = new("fr-FR"); + + // Parse each string in inputs using formats and the fr-FR culture. + foreach (string input in inputs) + { + if (TimeSpan.TryParseExact(input, formats, culture, out interval)) + Console.WriteLine($"{input} --> {interval:c}"); + else + Console.WriteLine($"Unable to parse {input}"); + } + } } // The example displays the following output: // 3 --> 03:00:00 diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs index 1e53dd05895..1a0ac2931b9 100644 --- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs +++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs @@ -2,25 +2,26 @@ using System; using System.Globalization; -public class Example +public class TryParseExactExample4 { - public static void Main() - { - string[] inputs = { "3", "16:42", "1:6:52:35.0625", - "1:6:52:35,0625" }; - string[] formats = { "%h", "g", "G" }; - TimeSpan interval; - CultureInfo culture = new CultureInfo("fr-FR"); - - // Parse each string in inputs using formats and the fr-FR culture. - foreach (string input in inputs) { - if(TimeSpan.TryParseExact(input, formats, culture, - TimeSpanStyles.AssumeNegative, out interval)) - Console.WriteLine("{0} --> {1:c}", input, interval); - else - Console.WriteLine("Unable to parse {0}", input); - } - } + public static void Run() + { + string[] inputs = [ "3", "16:42", "1:6:52:35.0625", + "1:6:52:35,0625" ]; + string[] formats = [ "%h", "g", "G" ]; + TimeSpan interval; + CultureInfo culture = new("fr-FR"); + + // Parse each string in inputs using formats and the fr-FR culture. + foreach (string input in inputs) + { + if (TimeSpan.TryParseExact(input, formats, culture, + TimeSpanStyles.AssumeNegative, out interval)) + Console.WriteLine($"{input} --> {interval:c}"); + else + Console.WriteLine($"Unable to parse {input}"); + } + } } // The example displays the following output: // 3 --> -03:00:00 diff --git a/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs b/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs index 80fa199e085..9fec60265f2 100644 --- a/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs +++ b/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs @@ -2,22 +2,20 @@ public class Example { - public static void Main() - { - // - var startWork = new TimeSpan(08,00,00); - var endWork = new TimeSpan(18,30,00); - var lunchBreak = new TimeSpan(1, 0, 0); - var breaks = new TimeSpan(0, 30, 0); - - Console.WriteLine("Length of work day: {0}", - endWork - startWork); - Console.WriteLine("Actual time worked: {0}", - endWork - startWork - (lunchBreak + breaks)); + public static void Main() + { + // + var startWork = new TimeSpan(08, 00, 00); + var endWork = new TimeSpan(18, 30, 00); + var lunchBreak = new TimeSpan(1, 0, 0); + var breaks = new TimeSpan(0, 30, 0); - // The example displays the following output: - // Length of work day: 10:30:00 - // Actual time worked: 09:00:00 - // - } + Console.WriteLine($"Length of work day: {endWork - startWork}"); + Console.WriteLine($"Actual time worked: {endWork - startWork - (lunchBreak + breaks)}"); + + // The example displays the following output: + // Length of work day: 10:30:00 + // Actual time worked: 09:00:00 + // + } } diff --git a/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs b/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs index bde80fdaa9b..155b5f3ca17 100644 --- a/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs +++ b/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs @@ -2,21 +2,21 @@ public class Class1 { - public static void Main() - { - // - TimeSpan time1 = new TimeSpan(1, 0, 0, 0); // TimeSpan equivalent to 1 day. - TimeSpan time2 = new TimeSpan(12, 0, 0); // TimeSpan equivalent to 1/2 day. - TimeSpan time3 = time1 + time2; // Add the two time spans. - - Console.WriteLine(" {0,12}\n + {1,10}\n {3}\n {2,10}", - time1, time2, time3, new String('_', 10)); + public static void Main() + { + // + TimeSpan time1 = new(1, 0, 0, 0); // TimeSpan equivalent to 1 day. + TimeSpan time2 = new(12, 0, 0); // TimeSpan equivalent to 1/2 day. + TimeSpan time3 = time1 + time2; // Add the two time spans. - // The example displays the following output: - // 1.00:00:00 - // + 12:00:00 - // __________ - // 1.12:00:00 - // - } + Console.WriteLine(" {0,12}\n + {1,10}\n {3}\n {2,10}", + time1, time2, time3, new string('_', 10)); + + // The example displays the following output: + // 1.00:00:00 + // + 12:00:00 + // __________ + // 1.12:00:00 + // + } } diff --git a/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs b/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs index fdeeea2e211..b3d2ed170ca 100644 --- a/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs +++ b/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs @@ -4,45 +4,45 @@ class TSRelationalOpsDemo { - const string dataFmt = "{0,34} {1}" ; + const string dataFmt = "{0,34} {1}"; // Compare TimeSpan parameters, and display them with the results. - static void CompareTimeSpans( TimeSpan Left, TimeSpan Right, - string RightText ) + static void CompareTimeSpans(TimeSpan Left, TimeSpan Right, + string RightText) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "Right: " + RightText, Right ); - Console.WriteLine( dataFmt, "Left == Right", Left == Right ); - Console.WriteLine( dataFmt, "Left > Right", Left > Right ); - Console.WriteLine( dataFmt, "Left >= Right", Left >= Right ); - Console.WriteLine( dataFmt, "Left != Right", Left != Right ); - Console.WriteLine( dataFmt, "Left < Right", Left < Right ); - Console.WriteLine( dataFmt, "Left <= Right", Left <= Right ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "Right: " + RightText, Right); + Console.WriteLine(dataFmt, "Left == Right", Left == Right); + Console.WriteLine(dataFmt, "Left > Right", Left > Right); + Console.WriteLine(dataFmt, "Left >= Right", Left >= Right); + Console.WriteLine(dataFmt, "Left != Right", Left != Right); + Console.WriteLine(dataFmt, "Left < Right", Left < Right); + Console.WriteLine(dataFmt, "Left <= Right", Left <= Right); } - static void Main( ) + static void Main() { - TimeSpan Left = new TimeSpan( 2, 0, 0 ); + TimeSpan Left = new(2, 0, 0); Console.WriteLine( "This example of the TimeSpan relational operators " + "generates \nthe following output. It creates several " + "different TimeSpan \nobjects and compares them with " + - "a 2-hour TimeSpan.\n" ); - Console.WriteLine( dataFmt, - "Left: TimeSpan( 2, 0, 0 )", Left ); + "a 2-hour TimeSpan.\n"); + Console.WriteLine(dataFmt, + "Left: TimeSpan( 2, 0, 0 )", Left); // Create objects to compare with a 2-hour TimeSpan. - CompareTimeSpans( Left, new TimeSpan( 0, 120, 0 ), - "TimeSpan( 0, 120, 0 )" ); - CompareTimeSpans( Left, new TimeSpan( 2, 0, 1 ), - "TimeSpan( 2, 0, 1 )" ); - CompareTimeSpans( Left, new TimeSpan( 2, 0, -1 ), - "TimeSpan( 2, 0, -1 )" ); - CompareTimeSpans( Left, TimeSpan.FromDays( 1.0 / 12D ), - "TimeSpan.FromDays( 1 / 12 )" ); - } -} + CompareTimeSpans(Left, new TimeSpan(0, 120, 0), + "TimeSpan( 0, 120, 0 )"); + CompareTimeSpans(Left, new TimeSpan(2, 0, 1), + "TimeSpan( 2, 0, 1 )"); + CompareTimeSpans(Left, new TimeSpan(2, 0, -1), + "TimeSpan( 2, 0, -1 )"); + CompareTimeSpans(Left, TimeSpan.FromDays(1.0 / 12D), + "TimeSpan.FromDays( 1 / 12 )"); + } +} /* This example of the TimeSpan relational operators generates @@ -82,5 +82,5 @@ objects and compares them with a 2-hour TimeSpan. Left != Right False Left < Right False Left <= Right True -*/ +*/ // diff --git a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs index 1e312e5fb10..7f3234b3836 100644 --- a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs +++ b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs @@ -5,76 +5,63 @@ public class Example { - public static void Main() - { - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; - - foreach (var zone in timeZones) - { - Console.WriteLine("{0} transition time information:", zone.StandardName); - Console.WriteLine(" Time zone information: "); - Console.WriteLine(" Base UTC Offset: {0}", zone.BaseUtcOffset); - Console.WriteLine(" Supports DST: {0}", zone.SupportsDaylightSavingTime); + public static void Main() + { + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; - TimeZoneInfo.AdjustmentRule[] adjustmentRules= zone.GetAdjustmentRules(); - - // Indicate that time zone has no adjustment rules - if (adjustmentRules.Length == 0) { - Console.WriteLine(" No adjustment rules defined."); - } - else { - Console.WriteLine(" Adjustment Rules: {0}", adjustmentRules.Length); - // Iterate adjustment rules - foreach (var adjustmentRule in adjustmentRules) { - Console.WriteLine(" Adjustment rule from {0:d} to {1:d}:", - adjustmentRule.DateStart, - adjustmentRule.DateEnd); - Console.WriteLine(" Delta: {0}", adjustmentRule.DaylightDelta); - // Get start of transition - TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; - // Display information on floating date rule - if (!daylightStart.IsFixedDateRule) - Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}", - daylightStart.TimeOfDay, - (WeekOfMonth) daylightStart.Week, - daylightStart.DayOfWeek, - dateInfo.GetMonthName(daylightStart.Month)); - // Display information on fixed date rule - else - Console.WriteLine(" Begins at {0:t} on {1} {2}", - daylightStart.TimeOfDay, - dateInfo.GetMonthName(daylightStart.Month), - daylightStart.Day); - - // Get end of transition. - TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; - // Display information on floating date rule. - if (!daylightEnd.IsFixedDateRule) - Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}", - daylightEnd.TimeOfDay, - (WeekOfMonth) daylightEnd.Week, - daylightEnd.DayOfWeek, - dateInfo.GetMonthName(daylightEnd.Month)); - // Display information on fixed date rule. - else - Console.WriteLine(" Ends at {0:t} on {1} {2}", - daylightEnd.TimeOfDay, - dateInfo.GetMonthName(daylightEnd.Month), - daylightEnd.Day); + foreach (var zone in timeZones) + { + Console.WriteLine($"{zone.StandardName} transition time information:"); + Console.WriteLine(" Time zone information: "); + Console.WriteLine($" Base UTC Offset: {zone.BaseUtcOffset}"); + Console.WriteLine($" Supports DST: {zone.SupportsDaylightSavingTime}"); + + TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); + + // Indicate that time zone has no adjustment rules + if (adjustmentRules.Length == 0) + { + Console.WriteLine(" No adjustment rules defined."); + } + else + { + Console.WriteLine($" Adjustment Rules: {adjustmentRules.Length}"); + // Iterate adjustment rules + foreach (var adjustmentRule in adjustmentRules) + { + Console.WriteLine($" Adjustment rule from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}:"); + Console.WriteLine($" Delta: {adjustmentRule.DaylightDelta}"); + // Get start of transition + TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; + // Display information on floating date rule + if (!daylightStart.IsFixedDateRule) + Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {(WeekOfMonth)daylightStart.Week} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}"); + // Display information on fixed date rule + else + Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on {dateInfo.GetMonthName(daylightStart.Month)} {daylightStart.Day}"); + + // Get end of transition. + TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; + // Display information on floating date rule. + if (!daylightEnd.IsFixedDateRule) + Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on the {(WeekOfMonth)daylightEnd.Week} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}"); + // Display information on fixed date rule. + else + Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on {dateInfo.GetMonthName(daylightEnd.Month)} {daylightEnd.Day}"); + } } - } - } - } + } + } - private enum WeekOfMonth - { - First = 1, - Second = 2, - Third = 3, - Fourth = 4, - Last = 5, - } + private enum WeekOfMonth + { + First = 1, + Second = 2, + Third = 3, + Fourth = 4, + Last = 5, + } } // A portion of the output from the example might appear as follows: // Tonga Standard Time transition time information: diff --git a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs index 2c6a43727c5..af88a729795 100644 --- a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs +++ b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs @@ -3,240 +3,214 @@ using System.Collections.ObjectModel; using System.Globalization; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] namespace TimeZoneInfoCode { -public class AdjustmentRuleTest -{ - private static void Main() - { - CreateCustomTimeZone(); - CompareRulesForEquality(); - ShowStartAndEndDates(); - } + public class AdjustmentRuleTest + { + private static void Main() + { + CreateCustomTimeZone(); + CompareRulesForEquality(); + ShowStartAndEndDates(); + } + + private static void CreateCustomTimeZone() + { + // + // Create alternate Central Standard Time to include historical time zone information + // + // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment; + List adjustmentList = []; + // Declare transition time variables to hold transition time information + TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; - private static void CreateCustomTimeZone() - { - // - // Create alternate Central Standard Time to include historical time zone information - // - // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment; - List adjustmentList = new List(); - // Declare transition time variables to hold transition time information - TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; + // Define end rule (for 1976-2006) + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); + // Define rule (1976-1986) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule (1987-2006) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule (2007- ) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 01, 01), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); - // Define end rule (for 1976-2006) - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); - // Define rule (1976-1986) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule (1987-2006) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule (2007- ) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 01, 01), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - - // Create custom U.S. Central Standard Time zone - TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0), - "(GMT-06:00) Central Time (US Only)", "Central Standard Time", - "Central Daylight Time", adjustmentList.ToArray()); - // - } + // Create custom U.S. Central Standard Time zone + TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0), + "(GMT-06:00) Central Time (US Only)", "Central Standard Time", + "Central Daylight Time", adjustmentList.ToArray()); + // + } - private static void CompareRulesForEquality() - { - // - string timeZoneName = ""; - // Get CST, Canadian CST, and Mexican CST adjustment rules - TimeZoneInfo.AdjustmentRule[] usCstAdjustments = null; - TimeZoneInfo.AdjustmentRule[] canCstAdjustments = null; - TimeZoneInfo.AdjustmentRule[] mexCstAdjustments = null; - try - { - timeZoneName = "Central Standard Time"; - usCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The {0} time zone is not defined in the registry.", - timeZoneName); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Data for the {0} time zone is invalid.", - timeZoneName); - } - try - { - timeZoneName = "Canada Central Standard Time"; - canCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The {0} time zone is not defined in the registry.", - timeZoneName); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Data for the {0} time zone is invalid.", - timeZoneName); - } - try - { - timeZoneName = "Central Standard Time (Mexico)"; - mexCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The {0} time zone is not defined in the registry.", - timeZoneName); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Data for the {0} time zone is invalid.", - timeZoneName); - } - // Determine if CST and other time zones have the same rules - foreach(TimeZoneInfo.AdjustmentRule rule in usCstAdjustments) - { - Console.WriteLine("Comparing Central Standard Time rule for {0:d} to {1:d} with:", - rule.DateStart, rule.DateEnd); - // Compare with Canada Central Standard Time - if (canCstAdjustments.Length == 0) - { - Console.WriteLine(" Canada Central Standard Time has no adjustment rules."); - } - else - { - foreach (TimeZoneInfo.AdjustmentRule canRule in canCstAdjustments) + private static void CompareRulesForEquality() + { + // + string timeZoneName = ""; + // Get CST, Canadian CST, and Mexican CST adjustment rules + TimeZoneInfo.AdjustmentRule[] usCstAdjustments = null; + TimeZoneInfo.AdjustmentRule[] canCstAdjustments = null; + TimeZoneInfo.AdjustmentRule[] mexCstAdjustments = null; + try + { + timeZoneName = "Central Standard Time"; + usCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry."); + } + catch (InvalidTimeZoneException) { - Console.WriteLine(" Canadian CST for {0:d} to {1:d}: {2}", - canRule.DateStart, canRule.DateEnd, - rule.Equals(canRule) ? "Equal" : "Not Equal"); - } - } - - // Compare with Mexico Central Standard Time - if (mexCstAdjustments.Length == 0) - { - Console.WriteLine(" Mexican Central Standard Time has no adjustment rules."); - } - else - { - foreach (TimeZoneInfo.AdjustmentRule mexRule in mexCstAdjustments) + Console.WriteLine($"Data for the {timeZoneName} time zone is invalid."); + } + try + { + timeZoneName = "Canada Central Standard Time"; + canCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); + } + catch (TimeZoneNotFoundException) { - Console.WriteLine(" Mexican CST for {0:d} to {1:d}: {2}", - mexRule.DateStart, mexRule.DateEnd, - rule.Equals(mexRule) ? "Equal" : "Not Equal"); - } - } - } - // This code displays the following output to the console: - // - // Comparing Central Standard Time rule for 1/1/0001 to 12/31/9999 with: - // Canada Central Standard Time has no adjustment rules. - // Mexican CST for 1/1/0001 to 12/31/9999: Equal - // - } + Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine($"Data for the {timeZoneName} time zone is invalid."); + } + try + { + timeZoneName = "Central Standard Time (Mexico)"; + mexCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules(); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine($"Data for the {timeZoneName} time zone is invalid."); + } + // Determine if CST and other time zones have the same rules + foreach (TimeZoneInfo.AdjustmentRule rule in usCstAdjustments) + { + Console.WriteLine($"Comparing Central Standard Time rule for {rule.DateStart:d} to {rule.DateEnd:d} with:"); + // Compare with Canada Central Standard Time + if (canCstAdjustments.Length == 0) + { + Console.WriteLine(" Canada Central Standard Time has no adjustment rules."); + } + else + { + foreach (TimeZoneInfo.AdjustmentRule canRule in canCstAdjustments) + { + Console.WriteLine($" Canadian CST for {canRule.DateStart:d} to {canRule.DateEnd:d}: {(rule.Equals(canRule) ? "Equal" : "Not Equal")}"); + } + } - // - private enum WeekOfMonth - { - First = 1, - Second = 2, - Third = 3, - Fourth = 4, - Last = 5, - } + // Compare with Mexico Central Standard Time + if (mexCstAdjustments.Length == 0) + { + Console.WriteLine(" Mexican Central Standard Time has no adjustment rules."); + } + else + { + foreach (TimeZoneInfo.AdjustmentRule mexRule in mexCstAdjustments) + { + Console.WriteLine($" Mexican CST for {mexRule.DateStart:d} to {mexRule.DateEnd:d}: {(rule.Equals(mexRule) ? "Equal" : "Not Equal")}"); + } + } + } + // This code displays the following output to the console: + // + // Comparing Central Standard Time rule for 1/1/0001 to 12/31/9999 with: + // Canada Central Standard Time has no adjustment rules. + // Mexican CST for 1/1/0001 to 12/31/9999: Equal + // + } - private static void ShowStartAndEndDates() - { - // Get all time zones from system - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - string[] monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames; - // Get each time zone - foreach (TimeZoneInfo timeZone in timeZones) - { - TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); - // Display message for time zones with no adjustments - if (adjustments.Length == 0) - { - Console.WriteLine("{0} has no adjustment rules", timeZone.StandardName); - } - else - { - // Handle time zones with 1 or 2+ adjustments differently - bool showCount = false; - int ctr = 0; - string spacer = ""; - - Console.WriteLine("{0} Adjustment rules", timeZone.StandardName); - if (adjustments.Length > 1) - { - showCount = true; - spacer = " "; - } - // Iterate adjustment rules - foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) + // + private enum WeekOfMonth + { + First = 1, + Second = 2, + Third = 3, + Fourth = 4, + Last = 5, + } + + private static void ShowStartAndEndDates() + { + // Get all time zones from system + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + string[] monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames; + // Get each time zone + foreach (TimeZoneInfo timeZone in timeZones) { - if (showCount) - { - Console.WriteLine(" Adjustment rule #{0}", ctr+1); - ctr++; - } - // Display general adjustment information - Console.WriteLine("{0} Start Date: {1:D}", spacer, adjustment.DateStart); - Console.WriteLine("{0} End Date: {1:D}", spacer, adjustment.DateEnd); - Console.WriteLine("{0} Time Change: {1}:{2:00} hours", spacer, - adjustment.DaylightDelta.Hours, adjustment.DaylightDelta.Minutes); - // Get transition start information - TimeZoneInfo.TransitionTime transitionStart = adjustment.DaylightTransitionStart; - Console.Write("{0} Annual Start: ", spacer); - if (transitionStart.IsFixedDateRule) - { - Console.WriteLine("On {0} {1} at {2:t}", - monthNames[transitionStart.Month - 1], - transitionStart.Day, - transitionStart.TimeOfDay); - } - else - { - Console.WriteLine("The {0} {1} of {2} at {3:t}", - ((WeekOfMonth)transitionStart.Week).ToString(), - transitionStart.DayOfWeek.ToString(), - monthNames[transitionStart.Month - 1], - transitionStart.TimeOfDay); - } - // Get transition end information - TimeZoneInfo.TransitionTime transitionEnd = adjustment.DaylightTransitionEnd; - Console.Write("{0} Annual End: ", spacer); - if (transitionEnd.IsFixedDateRule) - { - Console.WriteLine("On {0} {1} at {2:t}", - monthNames[transitionEnd.Month - 1], - transitionEnd.Day, - transitionEnd.TimeOfDay); - } - else - { - Console.WriteLine("The {0} {1} of {2} at {3:t}", - ((WeekOfMonth)transitionEnd.Week).ToString(), - transitionEnd.DayOfWeek.ToString(), - monthNames[transitionEnd.Month - 1], - transitionEnd.TimeOfDay); - } + TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); + // Display message for time zones with no adjustments + if (adjustments.Length == 0) + { + Console.WriteLine($"{timeZone.StandardName} has no adjustment rules"); + } + else + { + // Handle time zones with 1 or 2+ adjustments differently + bool showCount = false; + int ctr = 0; + string spacer = ""; + + Console.WriteLine($"{timeZone.StandardName} Adjustment rules"); + if (adjustments.Length > 1) + { + showCount = true; + spacer = " "; + } + // Iterate adjustment rules + foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) + { + if (showCount) + { + Console.WriteLine($" Adjustment rule #{ctr + 1}"); + ctr++; + } + // Display general adjustment information + Console.WriteLine($"{spacer} Start Date: {adjustment.DateStart:D}"); + Console.WriteLine($"{spacer} End Date: {adjustment.DateEnd:D}"); + Console.WriteLine($"{spacer} Time Change: {adjustment.DaylightDelta.Hours}:{adjustment.DaylightDelta.Minutes:00} hours"); + // Get transition start information + TimeZoneInfo.TransitionTime transitionStart = adjustment.DaylightTransitionStart; + Console.Write($"{spacer} Annual Start: "); + if (transitionStart.IsFixedDateRule) + { + Console.WriteLine($"On {monthNames[transitionStart.Month - 1]} {transitionStart.Day} at {transitionStart.TimeOfDay:t}"); + } + else + { + Console.WriteLine($"The {((WeekOfMonth)transitionStart.Week)} {transitionStart.DayOfWeek} of {monthNames[transitionStart.Month - 1]} at {transitionStart.TimeOfDay:t}"); + } + // Get transition end information + TimeZoneInfo.TransitionTime transitionEnd = adjustment.DaylightTransitionEnd; + Console.Write($"{spacer} Annual End: "); + if (transitionEnd.IsFixedDateRule) + { + Console.WriteLine($"On {monthNames[transitionEnd.Month - 1]} {transitionEnd.Day} at {transitionEnd.TimeOfDay:t}"); + } + else + { + Console.WriteLine($"The {((WeekOfMonth)transitionEnd.Week)} {transitionEnd.DayOfWeek} of {monthNames[transitionEnd.Month - 1]} at {transitionEnd.TimeOfDay:t}"); + } + } + } + Console.WriteLine(); } - } - Console.WriteLine(); - } - } - // -} + } + // + } } // end namespace diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs new file mode 100644 index 00000000000..9e1d688f17e --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs @@ -0,0 +1,2 @@ +TransitionTimeExamplesFull.Run(); +TransitionTimeExamplesYear.Run(); diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs index 49b940fa108..3109acd1f6b 100644 --- a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs +++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs @@ -3,325 +3,271 @@ using System.Collections.ObjectModel; using System.Globalization; -[assembly:CLSCompliant(true)] -public class TransitionTimeExamples +[assembly: CLSCompliant(true)] +public class TransitionTimeExamplesFull { - public static void Main() - { - TransitionTimeExamples tte = new TransitionTimeExamples(); - - Console.WriteLine("***CompareForEquality()"); - tte.CompareForEquality(); - Console.WriteLine(); - Console.WriteLine("***CompareTransitionTimesForEquality()"); - tte.CompareTransitionTimesForEquality(); - Console.WriteLine(); - Console.WriteLine("***CreateTransitionRules()"); - tte.CreateTransitionRules(); - Console.WriteLine(); - Console.WriteLine("***GetFixedTransitionTimes()"); - tte.GetFixedTransitionTimes(); - Console.WriteLine(); - Console.WriteLine("***GetFloatingTransitionTimes()"); - tte.GetFloatingTransitionTimes(); - Console.WriteLine(); - Console.WriteLine("***GetTransitionTimes(2006)"); - tte.GetTransitionTimes(2006); - AdditionalExamples ae = new AdditionalExamples(); - Console.WriteLine(); - Console.WriteLine("***GetAllTransitionTimes()"); - ae.GetAllTransitionTimes(); - } + public static void Run() + { + TransitionTimeExamplesFull tte = new(); - private void CompareForEquality() - { - // - TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); - TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); - TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday); - TimeZoneInfo tz = TimeZoneInfo.Local; - Console.WriteLine(tt1.Equals(tz)); // Returns False (overload with argument of type Object) - Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself) - Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values) - Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values) - // - } + Console.WriteLine("***CompareForEquality()"); + tte.CompareForEquality(); + Console.WriteLine(); + Console.WriteLine("***CompareTransitionTimesForEquality()"); + tte.CompareTransitionTimesForEquality(); + Console.WriteLine(); + Console.WriteLine("***CreateTransitionRules()"); + tte.CreateTransitionRules(); + Console.WriteLine(); + Console.WriteLine("***GetFixedTransitionTimes()"); + tte.GetFixedTransitionTimes(); + Console.WriteLine(); + Console.WriteLine("***GetFloatingTransitionTimes()"); + tte.GetFloatingTransitionTimes(); + Console.WriteLine(); + Console.WriteLine("***GetTransitionTimes(2006)"); + tte.GetTransitionTimes(2006); + AdditionalExamples ae = new(); + Console.WriteLine(); + Console.WriteLine("***GetAllTransitionTimes()"); + ae.GetAllTransitionTimes(); + } - private void CompareTransitionTimesForEquality() - { - // - TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); - TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); - TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday); - Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself) - Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values) - Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values) - // - } + private void CompareForEquality() + { + // + TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); + TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); + TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday); + TimeZoneInfo tz = TimeZoneInfo.Local; + Console.WriteLine(tt1.Equals(tz)); // Returns False (overload with argument of type Object) + Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself) + Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values) + Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values) + // + } - private void CreateTransitionRules() - { - // - // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone - TimeZoneInfo imaginaryTZ; - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment; - List adjustmentList = new List(); - // Declare transition time variables to hold transition time information - TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; - - // Define a fictitious new time zone consisting of fixed and floating adjustment rules - // Define fixed rule (for 1900-1955) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 15); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 3, 0, 0), 11, 15); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1900, 1, 1), new DateTime(1955, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define floating rule (for 1956- ) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 4, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1956, 1, 1), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); + private void CompareTransitionTimesForEquality() + { + // + TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); + TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03); + TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday); + Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself) + Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values) + Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values) + // + } - // Create fictitious time zone - imaginaryTZ = TimeZoneInfo.CreateCustomTimeZone("Fictitious Standard Time", new TimeSpan(-9, 0, 0), - "(GMT-09:00) Fictitious Time", "Fictitious Standard Time", - "Fictitious Daylight Time", adjustmentList.ToArray()); - // - } + private void CreateTransitionRules() + { + // + // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone + TimeZoneInfo imaginaryTZ; + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment; + List adjustmentList = []; + // Declare transition time variables to hold transition time information + TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; - // - private void GetFixedTransitionTimes() - { - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; - foreach (TimeZoneInfo zone in timeZones) - { - TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); - foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) - { - TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; - if (daylightStart.IsFixedDateRule) - Console.WriteLine("For {0}, daylight savings time begins at {1:t} on {2} {3} from {4:d} to {5:d}.", - zone.StandardName, - daylightStart.TimeOfDay, - dateInfo.GetMonthName(daylightStart.Month), - daylightStart.Day, - adjustmentRule.DateStart, - adjustmentRule.DateEnd); - TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; - if (daylightEnd.IsFixedDateRule) - Console.WriteLine("For {0}, daylight savings time ends at {1:t} on {2} {3} from {4:d} to {5:d}.", - zone.StandardName, - daylightEnd.TimeOfDay, - dateInfo.GetMonthName(daylightEnd.Month), - daylightEnd.Day, - adjustmentRule.DateStart, - adjustmentRule.DateEnd); - } - } - } - // - - // - private enum WeekOfMonth - { - First = 1, - Second = 2, - Third = 3, - Fourth = 4, - Last = 5 - } - - private void GetFloatingTransitionTimes() - { - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - foreach (TimeZoneInfo zone in timeZones) - { - TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); - DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; - foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) - { - TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; - if (!daylightStart.IsFixedDateRule) - Console.WriteLine("{0}, {1:d}-{2:d}: Begins at {3:t} on the {4} {5} of {6}.", - zone.StandardName, - adjustmentRule.DateStart, - adjustmentRule.DateEnd, - daylightStart.TimeOfDay, - ((WeekOfMonth)daylightStart.Week).ToString(), - daylightStart.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightStart.Month)); + // Define a fictitious new time zone consisting of fixed and floating adjustment rules + // Define fixed rule (for 1900-1955) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 15); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 3, 0, 0), 11, 15); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1900, 1, 1), new DateTime(1955, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define floating rule (for 1956- ) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 4, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1956, 1, 1), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); - TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; - if (!daylightEnd.IsFixedDateRule) - Console.WriteLine("{0}, {1:d}-{2:d}: Ends at {3:t} on the {4} {5} of {6}.", - zone.StandardName, - adjustmentRule.DateStart, - adjustmentRule.DateEnd, - daylightEnd.TimeOfDay, - ((WeekOfMonth)daylightEnd.Week).ToString(), - daylightEnd.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightEnd.Month)); - } - } - } - // + // Create fictitious time zone + imaginaryTZ = TimeZoneInfo.CreateCustomTimeZone("Fictitious Standard Time", new TimeSpan(-9, 0, 0), + "(GMT-09:00) Fictitious Time", "Fictitious Standard Time", + "Fictitious Daylight Time", adjustmentList.ToArray()); + // + } - private void GetTransitionTimes(int year) - { - // Instantiate DateTimeFormatInfo object for month names - DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat; + // + private void GetFixedTransitionTimes() + { + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; + foreach (TimeZoneInfo zone in timeZones) + { + TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); + foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) + { + TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; + if (daylightStart.IsFixedDateRule) + Console.WriteLine($"For {zone.StandardName}, daylight savings time begins at {daylightStart.TimeOfDay:t} on {dateInfo.GetMonthName(daylightStart.Month)} {daylightStart.Day} from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}."); + TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; + if (daylightEnd.IsFixedDateRule) + Console.WriteLine($"For {zone.StandardName}, daylight savings time ends at {daylightEnd.TimeOfDay:t} on {dateInfo.GetMonthName(daylightEnd.Month)} {daylightEnd.Day} from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}."); + } + } + } + // - // Get and iterate time zones on local computer - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - foreach (TimeZoneInfo timeZone in timeZones) - { - Console.WriteLine("{0}:", timeZone.StandardName); - TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); - if (adjustments.Length == 0) - { - Console.WriteLine(" No adjustment rules."); - } - else - { - // Iterate adjustment rules for time zone - foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) + // + private enum WeekOfMonth + { + First = 1, + Second = 2, + Third = 3, + Fourth = 4, + Last = 5 + } + + private void GetFloatingTransitionTimes() + { + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + foreach (TimeZoneInfo zone in timeZones) + { + TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); + DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; + foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) { - // Determine if this adjustment rule covers year desired - if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year) - { - TimeZoneInfo.TransitionTime startTransition, endTransition; - // Determine if starting transition is fixed - startTransition = adjustment.DaylightTransitionStart; - // Determine if starting transition is fixed and display transition info for year - if (startTransition.IsFixedDateRule) - Console.WriteLine(" Begins on {0} {1} at {2:t}", - dateFormat.GetMonthName(startTransition.Month), - startTransition.Day, - startTransition.TimeOfDay); - else - DisplayTransitionInfo(startTransition, year, "Begins on"); + TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; + if (!daylightStart.IsFixedDateRule) + Console.WriteLine($"{zone.StandardName}, {adjustmentRule.DateStart:d}-{adjustmentRule.DateEnd:d}: Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}."); - // Determine if ending transition is fixed and display transition info for year - endTransition = adjustment.DaylightTransitionEnd; - if (endTransition.IsFixedDateRule) - Console.WriteLine(" Ends on {0} {1} at {2:t}", - dateFormat.GetMonthName(endTransition.Month), - endTransition.Day, - endTransition.TimeOfDay); - else - DisplayTransitionInfo(endTransition, year, "Ends on"); - - break; - } + TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; + if (!daylightEnd.IsFixedDateRule) + Console.WriteLine($"{zone.StandardName}, {adjustmentRule.DateStart:d}-{adjustmentRule.DateEnd:d}: Ends at {daylightEnd.TimeOfDay:t} on the {((WeekOfMonth)daylightEnd.Week)} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}."); } - } - } - } - - private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label) - { - // For non-fixed date rules, get local calendar - Calendar cal = CultureInfo.CurrentCulture.Calendar; - // Get first day of week for transition - // For example, the 3rd week starts no earlier than the 15th of the month - int startOfWeek = transition.Week * 7 - 6; - // What day of the week does the month start on? - int firstDayOfWeek = (int) cal.GetDayOfWeek(new DateTime(year, transition.Month, startOfWeek)); - // Determine how much start date has to be adjusted - int transitionDay; - int changeDayOfWeek = (int) transition.DayOfWeek; + } + } + // - if (firstDayOfWeek <= changeDayOfWeek) - transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek); - else - transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek); + private void GetTransitionTimes(int year) + { + // Instantiate DateTimeFormatInfo object for month names + DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat; - // Adjust for months with no fifth week - if (transitionDay > cal.GetDaysInMonth(year, transition.Month)) - transitionDay -= 7; + // Get and iterate time zones on local computer + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + foreach (TimeZoneInfo timeZone in timeZones) + { + Console.WriteLine($"{timeZone.StandardName}:"); + TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); + if (adjustments.Length == 0) + { + Console.WriteLine(" No adjustment rules."); + } + else + { + // Iterate adjustment rules for time zone + foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) + { + // Determine if this adjustment rule covers year desired + if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year) + { + TimeZoneInfo.TransitionTime startTransition, endTransition; + // Determine if starting transition is fixed + startTransition = adjustment.DaylightTransitionStart; + // Determine if starting transition is fixed and display transition info for year + if (startTransition.IsFixedDateRule) + Console.WriteLine($" Begins on {dateFormat.GetMonthName(startTransition.Month)} {startTransition.Day} at {startTransition.TimeOfDay:t}"); + else + DisplayTransitionInfo(startTransition, year, "Begins on"); + + // Determine if ending transition is fixed and display transition info for year + endTransition = adjustment.DaylightTransitionEnd; + if (endTransition.IsFixedDateRule) + Console.WriteLine($" Ends on {dateFormat.GetMonthName(endTransition.Month)} {endTransition.Day} at {endTransition.TimeOfDay:t}"); + else + DisplayTransitionInfo(endTransition, year, "Ends on"); + + break; + } + } + } + } + } - Console.WriteLine(" {0} {1}, {2:d} at {3:t}", - label, - transition.DayOfWeek, - new DateTime(year, transition.Month, transitionDay), - transition.TimeOfDay); - } + private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label) + { + // For non-fixed date rules, get local calendar + Calendar cal = CultureInfo.CurrentCulture.Calendar; + // Get first day of week for transition + // For example, the 3rd week starts no earlier than the 15th of the month + int startOfWeek = transition.Week * 7 - 6; + // What day of the week does the month start on? + int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, startOfWeek)); + // Determine how much start date has to be adjusted + int transitionDay; + int changeDayOfWeek = (int)transition.DayOfWeek; + + if (firstDayOfWeek <= changeDayOfWeek) + transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek); + else + transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek); + + // Adjust for months with no fifth week + if (transitionDay > cal.GetDaysInMonth(year, transition.Month)) + transitionDay -= 7; + + Console.WriteLine($" {label} {transition.DayOfWeek}, {new DateTime(year, transition.Month, transitionDay):d} at {transition.TimeOfDay:t}"); + } } public class AdditionalExamples { - // - private enum WeekOfMonth - { - First = 1, - Second = 2, - Third = 3, - Fourth = 4, - Last = 5, - } + // + private enum WeekOfMonth + { + First = 1, + Second = 2, + Third = 3, + Fourth = 4, + Last = 5, + } - public void GetAllTransitionTimes() - { - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; - - foreach (TimeZoneInfo zone in timeZones) - { - Console.WriteLine("{0} transition time information:", zone.StandardName); - TimeZoneInfo.AdjustmentRule[] adjustmentRules= zone.GetAdjustmentRules(); - - // Indicate that time zone has no adjustment rules - if (adjustmentRules.Length == 0) - { - Console.WriteLine(" No adjustment rules defined."); - } - else - { - // Iterate adjustment rules - foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) + public void GetAllTransitionTimes() + { + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat; + + foreach (TimeZoneInfo zone in timeZones) + { + Console.WriteLine($"{zone.StandardName} transition time information:"); + TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); + + // Indicate that time zone has no adjustment rules + if (adjustmentRules.Length == 0) + { + Console.WriteLine(" No adjustment rules defined."); + } + else { - Console.WriteLine(" Adjustment rule from {0:d} to {1:d}:", - adjustmentRule.DateStart, - adjustmentRule.DateEnd); - - // Get start of transition - TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; - // Display information on fixed date rule - if (!daylightStart.IsFixedDateRule) - Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}.", - daylightStart.TimeOfDay, - ((WeekOfMonth)daylightStart.Week).ToString(), - daylightStart.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightStart.Month)); - // Display information on floating date rule - else - Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}.", - daylightStart.TimeOfDay, - ((WeekOfMonth)daylightStart.Week).ToString(), - daylightStart.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightStart.Month)); - - // Get end of transition - TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; - // Display information on fixed date rule - if (!daylightEnd.IsFixedDateRule) - Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}.", - daylightEnd.TimeOfDay, - ((WeekOfMonth)daylightEnd.Week).ToString(), - daylightEnd.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightEnd.Month)); - // Display information on floating date rule - else - Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}.", - daylightStart.TimeOfDay, - ((WeekOfMonth)daylightStart.Week).ToString(), - daylightStart.DayOfWeek.ToString(), - dateInfo.GetMonthName(daylightStart.Month)); + // Iterate adjustment rules + foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) + { + Console.WriteLine($" Adjustment rule from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}:"); + + // Get start of transition + TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart; + // Display information on fixed date rule + if (!daylightStart.IsFixedDateRule) + Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}."); + // Display information on floating date rule + else + Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}."); + + // Get end of transition + TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd; + // Display information on fixed date rule + if (!daylightEnd.IsFixedDateRule) + Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on the {((WeekOfMonth)daylightEnd.Week)} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}."); + // Display information on floating date rule + else + Console.WriteLine($" Ends at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}."); + } } - } - } - } - // + } + } + // } diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs index c9e6c34b54a..0f59475c641 100644 --- a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs +++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs @@ -1,120 +1,108 @@ using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; -[assembly:CLSCompliant(true)] -public class TransitionTimeExamples +public class TransitionTimeExamplesYear { - public static void Main() - { - TransitionTimeExamples tte = new TransitionTimeExamples(); - tte.GetTransitionTimes(2007); - } + public static void Run() + { + TransitionTimeExamplesYear tte = new(); + tte.GetTransitionTimes(2007); + } - // - private void GetTransitionTimes(int year) - { - // Instantiate DateTimeFormatInfo object for month names - DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat; + // + private void GetTransitionTimes(int year) + { + // Instantiate DateTimeFormatInfo object for month names + DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat; - // Get and iterate time zones on local computer - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - foreach (TimeZoneInfo timeZone in timeZones) - { - Console.WriteLine("{0}:", timeZone.StandardName); - TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); - int startYear = year; - int endYear = startYear; + // Get and iterate time zones on local computer + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + foreach (TimeZoneInfo timeZone in timeZones) + { + Console.WriteLine($"{timeZone.StandardName}:"); + TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules(); + int startYear = year; + int endYear = startYear; - if (adjustments.Length == 0) - { - Console.WriteLine(" No adjustment rules."); - } - else - { - TimeZoneInfo.AdjustmentRule adjustment = GetAdjustment(adjustments, year); - if (adjustment == null) + if (adjustments.Length == 0) { - Console.WriteLine(" No adjustment rules available for this year."); - continue; + Console.WriteLine(" No adjustment rules."); } - TimeZoneInfo.TransitionTime startTransition, endTransition; - - // Determine if starting transition is fixed - startTransition = adjustment.DaylightTransitionStart; - // Determine if starting transition is fixed and display transition info for year - if (startTransition.IsFixedDateRule) - Console.WriteLine(" Begins on {0} {1} at {2:t}", - dateFormat.GetMonthName(startTransition.Month), - startTransition.Day, - startTransition.TimeOfDay); else - DisplayTransitionInfo(startTransition, startYear, "Begins on"); - - // Determine if ending transition is fixed and display transition info for year - endTransition = adjustment.DaylightTransitionEnd; - - // Does the transition back occur in an earlier month (i.e., - // the following year) than the transition to DST? If so, make - // sure we have the right adjustment rule. - if (endTransition.Month < startTransition.Month) { - endTransition = GetAdjustment(adjustments, year + 1).DaylightTransitionEnd; - endYear++; + TimeZoneInfo.AdjustmentRule adjustment = GetAdjustment(adjustments, year); + if (adjustment == null) + { + Console.WriteLine(" No adjustment rules available for this year."); + continue; + } + TimeZoneInfo.TransitionTime startTransition, endTransition; + + // Determine if starting transition is fixed + startTransition = adjustment.DaylightTransitionStart; + // Determine if starting transition is fixed and display transition info for year + if (startTransition.IsFixedDateRule) + Console.WriteLine($" Begins on {dateFormat.GetMonthName(startTransition.Month)} {startTransition.Day} at {startTransition.TimeOfDay:t}"); + else + DisplayTransitionInfo(startTransition, startYear, "Begins on"); + + // Determine if ending transition is fixed and display transition info for year + endTransition = adjustment.DaylightTransitionEnd; + + // Does the transition back occur in an earlier month (i.e., + // the following year) than the transition to DST? If so, make + // sure we have the right adjustment rule. + if (endTransition.Month < startTransition.Month) + { + endTransition = GetAdjustment(adjustments, year + 1).DaylightTransitionEnd; + endYear++; + } + + if (endTransition.IsFixedDateRule) + Console.WriteLine($" Ends on {dateFormat.GetMonthName(endTransition.Month)} {endTransition.Day} at {endTransition.TimeOfDay:t}"); + else + DisplayTransitionInfo(endTransition, endYear, "Ends on"); } - - if (endTransition.IsFixedDateRule) - Console.WriteLine(" Ends on {0} {1} at {2:t}", - dateFormat.GetMonthName(endTransition.Month), - endTransition.Day, - endTransition.TimeOfDay); - else - DisplayTransitionInfo(endTransition, endYear, "Ends on"); - } - } - } + } + } + + private static TimeZoneInfo.AdjustmentRule GetAdjustment(TimeZoneInfo.AdjustmentRule[] adjustments, + int year) + { + // Iterate adjustment rules for time zone + foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) + { + // Determine if this adjustment rule covers year desired + if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year) + return adjustment; + } + return null; + } - private static TimeZoneInfo.AdjustmentRule GetAdjustment(TimeZoneInfo.AdjustmentRule[] adjustments, - int year) - { - // Iterate adjustment rules for time zone - foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments) - { - // Determine if this adjustment rule covers year desired - if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year) - return adjustment; - } - return null; - } - - private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label) - { - // For non-fixed date rules, get local calendar - Calendar cal = CultureInfo.CurrentCulture.Calendar; - // Get first day of week for transition - // For example, the 3rd week starts no earlier than the 15th of the month - int startOfWeek = transition.Week * 7 - 6; - // What day of the week does the month start on? - int firstDayOfWeek = (int) cal.GetDayOfWeek(new DateTime(year, transition.Month, 1)); - // Determine how much start date has to be adjusted - int transitionDay; - int changeDayOfWeek = (int) transition.DayOfWeek; + private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label) + { + // For non-fixed date rules, get local calendar + Calendar cal = CultureInfo.CurrentCulture.Calendar; + // Get first day of week for transition + // For example, the 3rd week starts no earlier than the 15th of the month + int startOfWeek = transition.Week * 7 - 6; + // What day of the week does the month start on? + int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, 1)); + // Determine how much start date has to be adjusted + int transitionDay; + int changeDayOfWeek = (int)transition.DayOfWeek; - if (firstDayOfWeek <= changeDayOfWeek) - transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek); - else - transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek); + if (firstDayOfWeek <= changeDayOfWeek) + transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek); + else + transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek); - // Adjust for months with no fifth week - if (transitionDay > cal.GetDaysInMonth(year, transition.Month)) - transitionDay -= 7; + // Adjust for months with no fifth week + if (transitionDay > cal.GetDaysInMonth(year, transition.Month)) + transitionDay -= 7; - Console.WriteLine(" {0} {1}, {2:d} at {3:t}", - label, - transition.DayOfWeek, - new DateTime(year, transition.Month, transitionDay), - transition.TimeOfDay); - } - // + Console.WriteLine($" {label} {transition.DayOfWeek}, {new DateTime(year, transition.Month, transitionDay):d} at {transition.TimeOfDay:t}"); + } + // } diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs new file mode 100644 index 00000000000..ea77484b8d8 --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs @@ -0,0 +1,3 @@ +GetSystemTimeZonesExample.Run(); +ShowTimeZoneNamesExample.Run(); +TimeZoneExamples.TZClass.Run(); diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj new file mode 100644 index 00000000000..c27165eee76 --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj @@ -0,0 +1,8 @@ + + + Exe + net10.0-windows + true + true + + diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs index 65c5d51c2ac..1f08961d414 100644 --- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs +++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs @@ -1,16 +1,16 @@ // using System; -public class Example +public class ShowTimeZoneNamesExample { - public static void Main() - { - TimeZoneInfo localZone = TimeZoneInfo.Local; - Console.WriteLine("Local Time Zone ID: {0}", localZone.Id); - Console.WriteLine(" Display Name is: {0}.", localZone.DisplayName); - Console.WriteLine(" Standard name is: {0}.", localZone.StandardName); - Console.WriteLine(" Daylight saving name is: {0}.", localZone.DaylightName); - } + public static void Run() + { + TimeZoneInfo localZone = TimeZoneInfo.Local; + Console.WriteLine($"Local Time Zone ID: {localZone.Id}"); + Console.WriteLine($" Display Name is: {localZone.DisplayName}."); + Console.WriteLine($" Standard name is: {localZone.StandardName}."); + Console.WriteLine($" Daylight saving name is: {localZone.DaylightName}."); + } } // The example displays output like the following: // Local Time Zone ID: Pacific Standard Time diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs index e5fbfa74fd7..109d32ad764 100644 --- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs +++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs @@ -1,147 +1,141 @@ using System; using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; using System.Windows.Forms; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] namespace TimeZoneExamples { - public class TZClass - { - public static void Main() - { - TZClass tz = new TZClass(); - if(MessageBox.Show("Display time zone offset?", "Offset", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowTimezoneOffset(); - - if(MessageBox.Show("Display time zone names?", "Names", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowTimeZoneNames(); - - if(MessageBox.Show("Display universal time zone names?", "Universal Time Zone Names", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowUniversalTimeZoneNames(); - - if(MessageBox.Show("Show time zones without daylight savings time", "Zones Supporting DST", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowNoDSTZones(); - - if(MessageBox.Show("List all time zone IDs?", "IDs", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowTimeZoneIDs(); - - if(MessageBox.Show("Test Time Zones for Equality?", "TimeZoneInfo.Equals", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.TestForEquality(); - - if(MessageBox.Show("Show ambiguous times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsAmbiguousTime", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowAmbiguousTimes(); - - if(MessageBox.Show("Show invalid times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsInvalidTime", MessageBoxButtons.YesNo) == DialogResult.Yes) - tz.ShowInvalidTimes(); - } - - private void ShowTimezoneOffset() - { - // - TimeZoneInfo localZone = TimeZoneInfo.Local; - Console.WriteLine("The {0} time zone is {1}:{2} {3} than Coordinated Universal Time.", - localZone.DisplayName, - Math.Abs(localZone.BaseUtcOffset.Hours), - Math.Abs(localZone.BaseUtcOffset.Minutes), - (localZone.BaseUtcOffset >= TimeSpan.Zero) ? "later" : "earlier"); - // - } - - private void ShowTimeZoneNames() - { - TimeZoneInfo localZone = TimeZoneInfo.Local; - Console.WriteLine("Local Time Zone ID: {0}", localZone.Id); - Console.WriteLine(" Display Name is: {0}.", localZone.DisplayName); - Console.WriteLine(" Standard name is: {0}.", localZone.StandardName); - Console.WriteLine(" Daylight saving name is: {0}.", localZone.DaylightName); - } - - private void ShowUniversalTimeZoneNames() - { - // - TimeZoneInfo universalZone = TimeZoneInfo.Utc; - Console.WriteLine("The universal time zone is {0}.", universalZone.DisplayName); - Console.WriteLine("Its standard name is {0}.", universalZone.StandardName); - Console.WriteLine("Its daylight savings name is {0}.", universalZone.DaylightName); - // - } - - private void ShowNoDSTZones() - { - // - ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); - foreach(TimeZoneInfo zone in zones) - { - if (!zone.SupportsDaylightSavingTime) - Console.WriteLine(zone.DisplayName); - } - // - } - - private void ShowTimeZoneIDs() - { - // - ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); - Console.WriteLine("The local system has the following {0} time zones", zones.Count); - foreach (TimeZoneInfo zone in zones) - Console.WriteLine(zone.Id); - // - } - - private void TestForEquality() - { - // - TimeZoneInfo thisTimeZone, zone1, zone2; - - thisTimeZone = TimeZoneInfo.Local; - zone1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); - zone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); - Console.WriteLine(thisTimeZone.Equals(zone1)); - Console.WriteLine(thisTimeZone.Equals(zone2)); - // - } - - private void ShowAmbiguousTimes() - { - // - // Specify DateTimeKind in Date constructor - DateTime baseTime = new DateTime(2007, 11, 4, 0, 59, 00, DateTimeKind.Unspecified); - DateTime newTime; - - // Get Pacific Standard Time zone - TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); - - // List possible ambiguous times for 63-minute interval, from 12:59 AM to 2:01 AM - for (int ctr = 0; ctr < 63; ctr++) - { - // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified - newTime = baseTime.AddMinutes(ctr); - Console.WriteLine("{0} is ambiguous: {1}", newTime, pstZone.IsAmbiguousTime(newTime)); - } - // - } - - private void ShowInvalidTimes() - { - // - // Specify DateTimeKind in Date constructor - DateTime baseTime = new DateTime(2007, 3, 11, 1, 59, 0, DateTimeKind.Unspecified); - DateTime newTime; - - // Get Pacific Standard Time zone - TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); - - // List possible invalid times for a 63-minute interval, from 1:59 AM to 3:01 AM - for (int ctr = 0; ctr < 63; ctr++) - { - // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified - newTime = baseTime.AddMinutes(ctr); - Console.WriteLine("{0} is invalid: {1}", newTime, pstZone.IsInvalidTime(newTime)); - } - // - } - } + public class TZClass + { + public static void Run() + { + TZClass tz = new(); + if (MessageBox.Show("Display time zone offset?", "Offset", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowTimezoneOffset(); + + if (MessageBox.Show("Display time zone names?", "Names", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowTimeZoneNames(); + + if (MessageBox.Show("Display universal time zone names?", "Universal Time Zone Names", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowUniversalTimeZoneNames(); + + if (MessageBox.Show("Show time zones without daylight savings time", "Zones Supporting DST", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowNoDSTZones(); + + if (MessageBox.Show("List all time zone IDs?", "IDs", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowTimeZoneIDs(); + + if (MessageBox.Show("Test Time Zones for Equality?", "TimeZoneInfo.Equals", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.TestForEquality(); + + if (MessageBox.Show("Show ambiguous times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsAmbiguousTime", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowAmbiguousTimes(); + + if (MessageBox.Show("Show invalid times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsInvalidTime", MessageBoxButtons.YesNo) == DialogResult.Yes) + tz.ShowInvalidTimes(); + } + + private void ShowTimezoneOffset() + { + // + TimeZoneInfo localZone = TimeZoneInfo.Local; + Console.WriteLine($"The {localZone.DisplayName} time zone is {Math.Abs(localZone.BaseUtcOffset.Hours)}:{Math.Abs(localZone.BaseUtcOffset.Minutes)} {((localZone.BaseUtcOffset >= TimeSpan.Zero) ? "later" : "earlier")} than Coordinated Universal Time."); + // + } + + private void ShowTimeZoneNames() + { + TimeZoneInfo localZone = TimeZoneInfo.Local; + Console.WriteLine($"Local Time Zone ID: {localZone.Id}"); + Console.WriteLine($" Display Name is: {localZone.DisplayName}."); + Console.WriteLine($" Standard name is: {localZone.StandardName}."); + Console.WriteLine($" Daylight saving name is: {localZone.DaylightName}."); + } + + private void ShowUniversalTimeZoneNames() + { + // + TimeZoneInfo universalZone = TimeZoneInfo.Utc; + Console.WriteLine($"The universal time zone is {universalZone.DisplayName}."); + Console.WriteLine($"Its standard name is {universalZone.StandardName}."); + Console.WriteLine($"Its daylight savings name is {universalZone.DaylightName}."); + // + } + + private void ShowNoDSTZones() + { + // + ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); + foreach (TimeZoneInfo zone in zones) + { + if (!zone.SupportsDaylightSavingTime) + Console.WriteLine(zone.DisplayName); + } + // + } + + private void ShowTimeZoneIDs() + { + // + ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); + Console.WriteLine($"The local system has the following {zones.Count} time zones"); + foreach (TimeZoneInfo zone in zones) + Console.WriteLine(zone.Id); + // + } + + private void TestForEquality() + { + // + TimeZoneInfo thisTimeZone, zone1, zone2; + + thisTimeZone = TimeZoneInfo.Local; + zone1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); + zone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + Console.WriteLine(thisTimeZone.Equals(zone1)); + Console.WriteLine(thisTimeZone.Equals(zone2)); + // + } + + private void ShowAmbiguousTimes() + { + // + // Specify DateTimeKind in Date constructor + DateTime baseTime = new(2007, 11, 4, 0, 59, 00, DateTimeKind.Unspecified); + DateTime newTime; + + // Get Pacific Standard Time zone + TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); + + // List possible ambiguous times for 63-minute interval, from 12:59 AM to 2:01 AM + for (int ctr = 0; ctr < 63; ctr++) + { + // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified + newTime = baseTime.AddMinutes(ctr); + Console.WriteLine($"{newTime} is ambiguous: {pstZone.IsAmbiguousTime(newTime)}"); + } + // + } + + private void ShowInvalidTimes() + { + // + // Specify DateTimeKind in Date constructor + DateTime baseTime = new(2007, 3, 11, 1, 59, 0, DateTimeKind.Unspecified); + DateTime newTime; + + // Get Pacific Standard Time zone + TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); + + // List possible invalid times for a 63-minute interval, from 1:59 AM to 3:01 AM + for (int ctr = 0; ctr < 63; ctr++) + { + // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified + newTime = baseTime.AddMinutes(ctr); + Console.WriteLine($"{newTime} is invalid: {pstZone.IsInvalidTime(newTime)}"); + } + // + } + } } diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs index 5c28ea5f202..4f85f055478 100644 --- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs +++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs @@ -4,67 +4,57 @@ using System.IO; using System.Collections.ObjectModel; -public class Example +public class GetSystemTimeZonesExample { - public static void Main() - { - const string OUTPUTFILENAME = @"C:\Temp\TimeZoneInfo.txt"; - - DateTimeFormatInfo dateFormats = CultureInfo.CurrentCulture.DateTimeFormat; - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - StreamWriter sw = new StreamWriter(OUTPUTFILENAME, false); - - foreach (TimeZoneInfo timeZone in timeZones) - { - bool hasDST = timeZone.SupportsDaylightSavingTime; - TimeSpan offsetFromUtc = timeZone.BaseUtcOffset; - TimeZoneInfo.AdjustmentRule[] adjustRules; - string offsetString; - - sw.WriteLine("ID: {0}", timeZone.Id); - sw.WriteLine(" Display Name: {0, 40}", timeZone.DisplayName); - sw.WriteLine(" Standard Name: {0, 39}", timeZone.StandardName); - sw.Write(" Daylight Name: {0, 39}", timeZone.DaylightName); - sw.Write(hasDST ? " ***Has " : " ***Does Not Have "); - sw.WriteLine("Daylight Saving Time***"); - offsetString = String.Format("{0} hours, {1} minutes", offsetFromUtc.Hours, offsetFromUtc.Minutes); - sw.WriteLine(" Offset from UTC: {0, 40}", offsetString); - adjustRules = timeZone.GetAdjustmentRules(); - sw.WriteLine(" Number of adjustment rules: {0, 26}", adjustRules.Length); - if (adjustRules.Length > 0) - { - sw.WriteLine(" Adjustment Rules:"); - foreach (TimeZoneInfo.AdjustmentRule rule in adjustRules) + public static void Run() + { + const string OUTPUTFILENAME = @"C:\Temp\TimeZoneInfo.txt"; + + DateTimeFormatInfo dateFormats = CultureInfo.CurrentCulture.DateTimeFormat; + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + StreamWriter sw = new(OUTPUTFILENAME, false); + + foreach (TimeZoneInfo timeZone in timeZones) + { + bool hasDST = timeZone.SupportsDaylightSavingTime; + TimeSpan offsetFromUtc = timeZone.BaseUtcOffset; + TimeZoneInfo.AdjustmentRule[] adjustRules; + string offsetString; + + sw.WriteLine($"ID: {timeZone.Id}"); + sw.WriteLine($" Display Name: {timeZone.DisplayName,40}"); + sw.WriteLine($" Standard Name: {timeZone.StandardName,39}"); + sw.Write($" Daylight Name: {timeZone.DaylightName,39}"); + sw.Write(hasDST ? " ***Has " : " ***Does Not Have "); + sw.WriteLine("Daylight Saving Time***"); + offsetString = $"{offsetFromUtc.Hours} hours, {offsetFromUtc.Minutes} minutes"; + sw.WriteLine($" Offset from UTC: {offsetString,40}"); + adjustRules = timeZone.GetAdjustmentRules(); + sw.WriteLine($" Number of adjustment rules: {adjustRules.Length,26}"); + if (adjustRules.Length > 0) { - TimeZoneInfo.TransitionTime transTimeStart = rule.DaylightTransitionStart; - TimeZoneInfo.TransitionTime transTimeEnd = rule.DaylightTransitionEnd; - - sw.WriteLine(" From {0} to {1}", rule.DateStart, rule.DateEnd); - sw.WriteLine(" Delta: {0}", rule.DaylightDelta); - if (!transTimeStart.IsFixedDateRule) - { - sw.WriteLine(" Begins at {0:t} on {1} of week {2} of {3}", transTimeStart.TimeOfDay, - transTimeStart.DayOfWeek, - transTimeStart.Week, - dateFormats.MonthNames[transTimeStart.Month - 1]); - sw.WriteLine(" Ends at {0:t} on {1} of week {2} of {3}", transTimeEnd.TimeOfDay, - transTimeEnd.DayOfWeek, - transTimeEnd.Week, - dateFormats.MonthNames[transTimeEnd.Month - 1]); - } - else - { - sw.WriteLine(" Begins at {0:t} on {1} {2}", transTimeStart.TimeOfDay, - transTimeStart.Day, - dateFormats.MonthNames[transTimeStart.Month - 1]); - sw.WriteLine(" Ends at {0:t} on {1} {2}", transTimeEnd.TimeOfDay, - transTimeEnd.Day, - dateFormats.MonthNames[transTimeEnd.Month - 1]); - } + sw.WriteLine(" Adjustment Rules:"); + foreach (TimeZoneInfo.AdjustmentRule rule in adjustRules) + { + TimeZoneInfo.TransitionTime transTimeStart = rule.DaylightTransitionStart; + TimeZoneInfo.TransitionTime transTimeEnd = rule.DaylightTransitionEnd; + + sw.WriteLine($" From {rule.DateStart} to {rule.DateEnd}"); + sw.WriteLine($" Delta: {rule.DaylightDelta}"); + if (!transTimeStart.IsFixedDateRule) + { + sw.WriteLine($" Begins at {transTimeStart.TimeOfDay:t} on {transTimeStart.DayOfWeek} of week {transTimeStart.Week} of {dateFormats.MonthNames[transTimeStart.Month - 1]}"); + sw.WriteLine($" Ends at {transTimeEnd.TimeOfDay:t} on {transTimeEnd.DayOfWeek} of week {transTimeEnd.Week} of {dateFormats.MonthNames[transTimeEnd.Month - 1]}"); + } + else + { + sw.WriteLine($" Begins at {transTimeStart.TimeOfDay:t} on {transTimeStart.Day} {dateFormats.MonthNames[transTimeStart.Month - 1]}"); + sw.WriteLine($" Ends at {transTimeEnd.TimeOfDay:t} on {transTimeEnd.Day} {dateFormats.MonthNames[transTimeEnd.Month - 1]}"); + } + } } - } - } - sw.Close(); - } + } + sw.Close(); + } } // diff --git a/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs b/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs index 2d477152dd5..16c248c6beb 100644 --- a/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs +++ b/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs @@ -2,28 +2,28 @@ public class BestTimeZonePractices { - public static void Main() - { - BestTimeZonePractices best = new BestTimeZonePractices(); - best.NoCachedReferences(); - } + public static void Main() + { + BestTimeZonePractices best = new(); + best.NoCachedReferences(); + } - private void NoCachedReferences() - { - // - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); - TimeZoneInfo local = TimeZoneInfo.Local; - Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst)); + private void NoCachedReferences() + { + // + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); + TimeZoneInfo local = TimeZoneInfo.Local; + Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst)); - TimeZoneInfo.ClearCachedData(); - try - { - Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst)); - } - catch (ArgumentException e) - { - Console.WriteLine(e.GetType().Name + "\n " + e.Message); - } - // - } + TimeZoneInfo.ClearCachedData(); + try + { + Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst)); + } + catch (ArgumentException e) + { + Console.WriteLine(e.GetType().Name + "\n " + e.Message); + } + // + } } diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs new file mode 100644 index 00000000000..de79dcfbfd2 --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs @@ -0,0 +1,3 @@ +ConvertTimeExample1.Run(); +ConvertTimeExample2.Run(); +TZExamples.Run(); diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj new file mode 100644 index 00000000000..c27165eee76 --- /dev/null +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj @@ -0,0 +1,8 @@ + + + Exe + net10.0-windows + true + true + + diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs index 664a65d775e..db89a9a9436 100644 --- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs @@ -1,386 +1,354 @@ // Note that this source code file includes a code module (modMain) and -// a WinForm. +// a WinForm. using System; using System.Collections.ObjectModel; using System.Security; using System.Windows.Forms; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] public class TZExamples { - public static void Main() - { - TZExamples tze = new TZExamples(); -// tze.IterateTimeZones(); -// tze.SelectTimeZone(); + public static void Run() + { + TZExamples tze = new(); + // tze.IterateTimeZones(); + // tze.SelectTimeZone(); tze.ShowDaylightStatus(); Console.WriteLine("\nShowLocalAndUtcTime:"); tze.ShowLocalAndUtcTime(); tze.ConvertToArbitraryTime(); Console.WriteLine("**ConvertTimeToUtc***"); tze.ConvertToUtc(); - Console.WriteLine("ConvertEasternToUtc:"); + Console.WriteLine("ConvertEasternToUtc:"); tze.ConvertEasternToUtc(); Console.WriteLine("\nConvertUtcToCentral:"); tze.ConvertUtcToCentral(); - Console.WriteLine("\nConvertHawaiianToLocal:"); - tze.ConvertHawaiianToLocal(); - Console.WriteLine("Resolving ambiguous times:"); - Console.WriteLine(tze.ResolveAmbiguousTime(new DateTime(2006, 10, 29, 02, 03, 15))); - Console.WriteLine(tze.ResolveAmbiguousTime(DateTime.Now)); - Console.WriteLine(); - tze.GetUserDateInput(); - } + Console.WriteLine("\nConvertHawaiianToLocal:"); + tze.ConvertHawaiianToLocal(); + Console.WriteLine("Resolving ambiguous times:"); + Console.WriteLine(tze.ResolveAmbiguousTime(new DateTime(2006, 10, 29, 02, 03, 15))); + Console.WriteLine(tze.ResolveAmbiguousTime(DateTime.Now)); + Console.WriteLine(); + tze.GetUserDateInput(); + } - private void IterateTimeZones() - { - // - ReadOnlyCollection tzCollection; - tzCollection = TimeZoneInfo.GetSystemTimeZones(); - // - - Console.WriteLine("Listing {0} time zones found on the system:", tzCollection.Count); - // - foreach (TimeZoneInfo timeZone in tzCollection) - Console.WriteLine(" {0}: {1}", timeZone.Id, timeZone.DisplayName); - // - } + private void IterateTimeZones() + { + // + ReadOnlyCollection tzCollection; + tzCollection = TimeZoneInfo.GetSystemTimeZones(); + // - private void SelectTimeZone() - { - TZListForm frm = new TZListForm(); - frm.ShowDialog(); - } + Console.WriteLine($"Listing {tzCollection.Count} time zones found on the system:"); + // + foreach (TimeZoneInfo timeZone in tzCollection) + Console.WriteLine($" {timeZone.Id}: {timeZone.DisplayName}"); + // + } - private void ShowDaylightStatus() - { - // - DateTime dateToday = DateTime.Now; - TimeSpan differenceFromUtc = TimeZoneInfo.Local.GetUtcOffset(dateToday); - Console.WriteLine("The time is {0:t} in {1} time, {2:##.0} hours {3} universal time.", - dateToday, - TimeZoneInfo.Local.IsDaylightSavingTime(dateToday) ? "daylight saving" : "standard", - Math.Abs(differenceFromUtc.TotalHours), - differenceFromUtc.Hours > 0 ? "after" : "earlier than"); - // - } + private void SelectTimeZone() + { + TZListForm frm = new(); + frm.ShowDialog(); + } - private void ShowLocalAndUtcTime() - { - // - DateTime timeNow = DateTime.Now; - Console.WriteLine("It is now {0:t} {1}, or {2:t} {3}.", - timeNow, - TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ? - TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName, - TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, TimeZoneInfo.Utc), - TimeZoneInfo.Utc.StandardName); - // - } + private void ShowDaylightStatus() + { + // + DateTime dateToday = DateTime.Now; + TimeSpan differenceFromUtc = TimeZoneInfo.Local.GetUtcOffset(dateToday); + Console.WriteLine($"The time is {dateToday:t} in {(TimeZoneInfo.Local.IsDaylightSavingTime(dateToday) ? "daylight saving" : "standard")} time, {Math.Abs(differenceFromUtc.TotalHours):##.0} hours {(differenceFromUtc.Hours > 0 ? "after" : "earlier than")} universal time."); + // + } - private void ConvertToArbitraryTime() - { - // - DateTime timeNow = DateTime.Now; - try - { - TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); - DateTime easternTimeNow = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, - easternZone); - Console.WriteLine("{0} {1} corresponds to {2} {3}.", - timeNow, - TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ? - TimeZoneInfo.Local.DaylightName : - TimeZoneInfo.Local.StandardName, - easternTimeNow, - easternZone.IsDaylightSavingTime(easternTimeNow) ? - easternZone.DaylightName : - easternZone.StandardName); - } - // Handle exception - // - // As an alternative to simply displaying an error message, an alternate Eastern - // Standard Time TimeZoneInfo object could be instantiated here either by restoring - // it from a serialized string or by providing the necessary data to the - // CreateCustomTimeZone method. - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system."); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data."); - } - catch (SecurityException) - { - Console.WriteLine("The application lacks permission to read time zone information from the registry."); - } - catch (OutOfMemoryException) - { - Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone."); - } - // If we weren't passing FindSystemTimeZoneById a literal string, we also - // would handle an ArgumentNullException. - // - } + private void ShowLocalAndUtcTime() + { + // + DateTime timeNow = DateTime.Now; + Console.WriteLine($"It is now {timeNow:t} {(TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ? + TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName)}, or {TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, TimeZoneInfo.Utc):t} {TimeZoneInfo.Utc.StandardName}."); + // + } - private void ConvertToUtc() - { - // - DateTime dateNow = DateTime.Now; - Console.WriteLine("The date and time are {0} UTC.", - TimeZoneInfo.ConvertTimeToUtc(dateNow)); - // - } + private void ConvertToArbitraryTime() + { + // + DateTime timeNow = DateTime.Now; + try + { + TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + DateTime easternTimeNow = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, + easternZone); + Console.WriteLine($"{timeNow} {(TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ? + TimeZoneInfo.Local.DaylightName : + TimeZoneInfo.Local.StandardName)} corresponds to {easternTimeNow} {(easternZone.IsDaylightSavingTime(easternTimeNow) ? + easternZone.DaylightName : + easternZone.StandardName)}."); + } + // Handle exception + // + // As an alternative to simply displaying an error message, an alternate Eastern + // Standard Time TimeZoneInfo object could be instantiated here either by restoring + // it from a serialized string or by providing the necessary data to the + // CreateCustomTimeZone method. + catch (TimeZoneNotFoundException) + { + Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data."); + } + catch (SecurityException) + { + Console.WriteLine("The application lacks permission to read time zone information from the registry."); + } + catch (OutOfMemoryException) + { + Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone."); + } + // If we weren't passing FindSystemTimeZoneById a literal string, we also + // would handle an ArgumentNullException. + // + } - private void ConvertEasternToUtc() - { - // - DateTime easternTime = new DateTime(2007, 01, 02, 12, 16, 00); - string easternZoneId = "Eastern Standard Time"; - try - { - TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId); - Console.WriteLine("The date and time are {0} UTC.", - TimeZoneInfo.ConvertTimeToUtc(easternTime, easternZone)); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("Unable to find the {0} zone in the registry.", - easternZoneId); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Registry data on the {0} zone has been corrupted.", - easternZoneId); - } - // - } + private void ConvertToUtc() + { + // + DateTime dateNow = DateTime.Now; + Console.WriteLine($"The date and time are {TimeZoneInfo.ConvertTimeToUtc(dateNow)} UTC."); + // + } - private void ConvertUtcToCentral() - { - // - DateTime timeUtc = DateTime.UtcNow; - try - { - TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); - DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone); - Console.WriteLine("The date and time are {0} {1}.", - cstTime, - cstZone.IsDaylightSavingTime(cstTime) ? - cstZone.DaylightName : cstZone.StandardName); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The registry does not define the Central Standard Time zone."); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted."); - } - // - } + private void ConvertEasternToUtc() + { + // + DateTime easternTime = new(2007, 01, 02, 12, 16, 00); + string easternZoneId = "Eastern Standard Time"; + try + { + TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId); + Console.WriteLine($"The date and time are {TimeZoneInfo.ConvertTimeToUtc(easternTime, easternZone)} UTC."); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine($"Unable to find the {easternZoneId} zone in the registry."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine($"Registry data on the {easternZoneId} zone has been corrupted."); + } + // + } - private void ConvertHawaiianToLocal() - { - // - DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00); - try - { - TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"); - Console.WriteLine("{0} {1} is {2} local time.", - hwTime, - hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName, - TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local)); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The registry does not define the Hawaiian Standard Time zone."); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("Registry data on the Hawaiian Standard Time zone has been corrupted."); - } - // - } + private void ConvertUtcToCentral() + { + // + DateTime timeUtc = DateTime.UtcNow; + try + { + TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); + DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone); + Console.WriteLine($"The date and time are {cstTime} {(cstZone.IsDaylightSavingTime(cstTime) ? + cstZone.DaylightName : cstZone.StandardName)}."); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("The registry does not define the Central Standard Time zone."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted."); + } + // + } - // Map an ambiguous time to the time zone's standard time - // - private DateTime ResolveAmbiguousTime(DateTime ambiguousTime) - { - // Time is not ambiguous - if (!TimeZoneInfo.Local.IsAmbiguousTime(ambiguousTime)) - { - return ambiguousTime; - } - // Time is ambiguous - else - { - DateTime utcTime = DateTime.SpecifyKind(ambiguousTime - TimeZoneInfo.Local.BaseUtcOffset, - DateTimeKind.Utc); - Console.WriteLine("{0} local time corresponds to {1} {2}.", - ambiguousTime, utcTime, utcTime.Kind.ToString()); - return utcTime; - } - } - // + private void ConvertHawaiianToLocal() + { + // + DateTime hwTime = new(2007, 02, 01, 08, 00, 00); + try + { + TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"); + Console.WriteLine($"{hwTime} {(hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName)} is {TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local)} local time."); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("The registry does not define the Hawaiian Standard Time zone."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine("Registry data on the Hawaiian Standard Time zone has been corrupted."); + } + // + } - // Allow the user to resolve an ambiguous time - // - private void GetUserDateInput() - { - // Get date and time from user - DateTime inputDate = GetUserDateTime(); - DateTime utcDate; - - // Exit if date has no significant value - if (inputDate == DateTime.MinValue) return; - - if (TimeZoneInfo.Local.IsAmbiguousTime(inputDate)) - { - Console.WriteLine("The date you've entered is ambiguous."); - Console.WriteLine("Please select the correct offset from Universal Coordinated Time:"); - TimeSpan[] offsets = TimeZoneInfo.Local.GetAmbiguousTimeOffsets(inputDate); - for (int ctr = 0; ctr < offsets.Length; ctr++) - { - Console.WriteLine("{0}.) {1} hours, {2} minutes", ctr, offsets[ctr].Hours, offsets[ctr].Minutes); - } - Console.Write("> "); - int selection = int.Parse(Console.ReadLine()); - - // Convert local time to UTC, and set Kind property to DateTimeKind.Utc - utcDate = DateTime.SpecifyKind(inputDate - offsets[selection], DateTimeKind.Utc); + // Map an ambiguous time to the time zone's standard time + // + private DateTime ResolveAmbiguousTime(DateTime ambiguousTime) + { + // Time is not ambiguous + if (!TimeZoneInfo.Local.IsAmbiguousTime(ambiguousTime)) + { + return ambiguousTime; + } + // Time is ambiguous + else + { + DateTime utcTime = DateTime.SpecifyKind(ambiguousTime - TimeZoneInfo.Local.BaseUtcOffset, + DateTimeKind.Utc); + Console.WriteLine($"{ambiguousTime} local time corresponds to {utcTime} {utcTime.Kind}."); + return utcTime; + } + } + // - Console.WriteLine("{0} local time corresponds to {1} {2}.", inputDate, utcDate, utcDate.Kind.ToString()); - } - else - { - utcDate = inputDate.ToUniversalTime(); - Console.WriteLine("{0} local time corresponds to {1} {2}.", inputDate, utcDate, utcDate.Kind.ToString()); - } - } + // Allow the user to resolve an ambiguous time + // + private void GetUserDateInput() + { + // Get date and time from user + DateTime inputDate = GetUserDateTime(); + DateTime utcDate; - private DateTime GetUserDateTime() - { - bool exitFlag = false; // flag to exit loop if date is valid - string dateString; - DateTime inputDate = DateTime.MinValue; - - Console.Write("Enter a local date and time: "); - while (!exitFlag) - { - dateString = Console.ReadLine(); - if (dateString.ToUpper() == "E") - exitFlag = true; - - if (DateTime.TryParse(dateString, out inputDate)) - exitFlag = true; - else - Console.Write("Enter a valid date and time, or enter 'e' to exit: "); - } + // Exit if date has no significant value + if (inputDate == DateTime.MinValue) return; - return inputDate; - } - // + if (TimeZoneInfo.Local.IsAmbiguousTime(inputDate)) + { + Console.WriteLine("The date you've entered is ambiguous."); + Console.WriteLine("Please select the correct offset from Universal Coordinated Time:"); + TimeSpan[] offsets = TimeZoneInfo.Local.GetAmbiguousTimeOffsets(inputDate); + for (int ctr = 0; ctr < offsets.Length; ctr++) + { + Console.WriteLine($"{ctr}.) {offsets[ctr].Hours} hours, {offsets[ctr].Minutes} minutes"); + } + Console.Write("> "); + int selection = int.Parse(Console.ReadLine()); + + // Convert local time to UTC, and set Kind property to DateTimeKind.Utc + utcDate = DateTime.SpecifyKind(inputDate - offsets[selection], DateTimeKind.Utc); + + Console.WriteLine($"{inputDate} local time corresponds to {utcDate} {utcDate.Kind}."); + } + else + { + utcDate = inputDate.ToUniversalTime(); + Console.WriteLine($"{inputDate} local time corresponds to {utcDate} {utcDate.Kind}."); + } + } + + private DateTime GetUserDateTime() + { + bool exitFlag = false; // flag to exit loop if date is valid + string dateString; + DateTime inputDate = DateTime.MinValue; + + Console.Write("Enter a local date and time: "); + while (!exitFlag) + { + dateString = Console.ReadLine(); + if (dateString.ToUpper() == "E") + exitFlag = true; + + if (DateTime.TryParse(dateString, out inputDate)) + exitFlag = true; + else + Console.Write("Enter a valid date and time, or enter 'e' to exit: "); + } + + return inputDate; + } + // } public class TZListForm : Form { - private System.Windows.Forms.ListBox timeZoneList; - private System.Windows.Forms.Button OkButton; - - public TZListForm() - { - this.timeZoneList = new System.Windows.Forms.ListBox(); - this.OkButton = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // timeZoneList - // - this.timeZoneList.FormattingEnabled = true; - this.timeZoneList.Location = new System.Drawing.Point(12, 12); - this.timeZoneList.Name = "timeZoneList"; - this.timeZoneList.Size = new System.Drawing.Size(250, 212); - this.timeZoneList.TabIndex = 0; - // - // OkButton - // - this.OkButton.Location = new System.Drawing.Point(186, 231); - this.OkButton.Name = "OkButton"; - this.OkButton.Size = new System.Drawing.Size(75, 23); - this.OkButton.TabIndex = 1; - this.OkButton.Text = "&OK"; - this.OkButton.UseVisualStyleBackColor = true; - this.OkButton.Click += new System.EventHandler(this.OkButton_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(292, 266); - this.Controls.Add(this.OkButton); - this.Controls.Add(this.timeZoneList); - this.Name = "Form1"; - this.Text = "Form1"; - this.Load += new System.EventHandler(this.Form1_Load); - this.ResumeLayout(false); - } + private System.Windows.Forms.ListBox timeZoneList; + private System.Windows.Forms.Button OkButton; + + public TZListForm() + { + this.timeZoneList = new(); + this.OkButton = new(); + this.SuspendLayout(); + // + // timeZoneList + // + this.timeZoneList.FormattingEnabled = true; + this.timeZoneList.Location = new(12, 12); + this.timeZoneList.Name = "timeZoneList"; + this.timeZoneList.Size = new(250, 212); + this.timeZoneList.TabIndex = 0; + // + // OkButton + // + this.OkButton.Location = new(186, 231); + this.OkButton.Name = "OkButton"; + this.OkButton.Size = new(75, 23); + this.OkButton.TabIndex = 1; + this.OkButton.Text = "&OK"; + this.OkButton.UseVisualStyleBackColor = true; + this.OkButton.Click += new System.EventHandler(this.OkButton_Click); + // + // Form1 + // + this.AutoScaleDimensions = new(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new(292, 266); + this.Controls.Add(this.OkButton); + this.Controls.Add(this.timeZoneList); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + } + + // + private void Form1_Load(object sender, EventArgs e) + { + ReadOnlyCollection tzCollection; + tzCollection = TimeZoneInfo.GetSystemTimeZones(); + this.timeZoneList.DataSource = tzCollection; + } + + private void OkButton_Click(object sender, EventArgs e) + { + TimeZoneInfo selectedTimeZone = (TimeZoneInfo)this.timeZoneList.SelectedItem; + MessageBox.Show("You selected the " + selectedTimeZone + " time zone."); + } + // - // - private void Form1_Load(object sender, EventArgs e) - { - ReadOnlyCollection tzCollection; - tzCollection = TimeZoneInfo.GetSystemTimeZones(); - this.timeZoneList.DataSource = tzCollection; - } + private void ShowLocalAndUtc() + { + // + // Create Eastern Standard Time value and TimeZoneInfo object + DateTime estTime = new(2007, 1, 1, 00, 00, 00); + string timeZoneName = "Eastern Standard Time"; + try + { + TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName); - private void OkButton_Click(object sender, EventArgs e) - { - TimeZoneInfo selectedTimeZone = (TimeZoneInfo) this.timeZoneList.SelectedItem; - MessageBox.Show("You selected the " + selectedTimeZone.ToString() + " time zone."); - } - // + // Convert EST to local time + DateTime localTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Local); + Console.WriteLine($"At {estTime} {est}, the local time is {localTime} {(TimeZoneInfo.Local.IsDaylightSavingTime(localTime) ? + TimeZoneInfo.Local.DaylightName : + TimeZoneInfo.Local.StandardName)}."); - private void ShowLocalAndUtc() - { - // - // Create Eastern Standard Time value and TimeZoneInfo object - DateTime estTime = new DateTime(2007, 1, 1, 00, 00, 00); - string timeZoneName = "Eastern Standard Time"; - try - { - TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName); - - // Convert EST to local time - DateTime localTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Local); - Console.WriteLine("At {0} {1}, the local time is {2} {3}.", - estTime, - est, - localTime, - TimeZoneInfo.Local.IsDaylightSavingTime(localTime) ? - TimeZoneInfo.Local.DaylightName : - TimeZoneInfo.Local.StandardName); - - // Convert EST to UTC - DateTime utcTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Utc); - Console.WriteLine("At {0} {1}, the time is {2} {3}.", - estTime, - est, - utcTime, - TimeZoneInfo.Utc.StandardName); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("The {0} zone cannot be found in the registry.", - timeZoneName); - } - catch (InvalidTimeZoneException) - { - Console.WriteLine("The registry contains invalid data for the {0} zone.", - timeZoneName); - } - // - } + // Convert EST to UTC + DateTime utcTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Utc); + Console.WriteLine($"At {estTime} {est}, the time is {utcTime} {TimeZoneInfo.Utc.StandardName}."); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine($"The {timeZoneName} zone cannot be found in the registry."); + } + catch (InvalidTimeZoneException) + { + Console.WriteLine($"The registry contains invalid data for the {timeZoneName} zone."); + } + // + } } diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs index a060daa1a61..1ff28977fad 100644 --- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs @@ -1,46 +1,48 @@ // using System; -public class Example +public class ConvertTimeExample1 { - public static void Main() - { - // Define times to be converted. - DateTime[] times = { new DateTime(2010, 1, 1, 0, 1, 0), - new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Utc), - new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Local), + public static void Run() + { + // Define times to be converted. + DateTime[] times = [ new DateTime(2010, 1, 1, 0, 1, 0), + new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Utc), + new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Local), new DateTime(2010, 11, 6, 23, 30, 0), - new DateTime(2010, 11, 7, 2, 30, 0) }; - - // Retrieve the time zone for Eastern Standard Time (U.S. and Canada). - TimeZoneInfo est; - try { - est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); - } - catch (TimeZoneNotFoundException) { - Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); - return; - } - catch (InvalidTimeZoneException) { - Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); - return; - } + new DateTime(2010, 11, 7, 2, 30, 0) ]; - // Display the current time zone name. - Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName); - - // Convert each time in the array. - foreach (DateTime timeToConvert in times) - { - DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est); - Console.WriteLine("Converted {0} {1} to {2}.", timeToConvert, - timeToConvert.Kind, targetTime); - } - } + // Retrieve the time zone for Eastern Standard Time (U.S. and Canada). + TimeZoneInfo est; + try + { + est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); + return; + } + catch (InvalidTimeZoneException) + { + Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); + return; + } + + // Display the current time zone name. + Console.WriteLine($"Local time zone: {TimeZoneInfo.Local.DisplayName}\n"); + + // Convert each time in the array. + foreach (DateTime timeToConvert in times) + { + DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est); + Console.WriteLine($"Converted {timeToConvert} {timeToConvert.Kind} to {targetTime}."); + } + } } // The example displays the following output: // Local time zone: (GMT-08:00) Pacific Time (US & Canada) -// +// // Converted 1/1/2010 12:01:00 AM Unspecified to 1/1/2010 3:01:00 AM. // Converted 1/1/2010 12:01:00 AM Utc to 12/31/2009 7:01:00 PM. // Converted 1/1/2010 12:01:00 AM Local to 1/1/2010 3:01:00 AM. diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs index 21a4ad4b5db..e518861d1a6 100644 --- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs @@ -1,46 +1,49 @@ // using System; -public class Example +public class ConvertTimeExample2 { - public static void Main() - { - // Define times to be converted. - DateTime time1 = new DateTime(2010, 1, 1, 12, 1, 0); - DateTime time2 = new DateTime(2010, 11, 6, 23, 30, 0); - DateTimeOffset[] times = { new DateTimeOffset(time1, TimeZoneInfo.Local.GetUtcOffset(time1)), + public static void Run() + { + // Define times to be converted. + DateTime time1 = new(2010, 1, 1, 12, 1, 0); + DateTime time2 = new(2010, 11, 6, 23, 30, 0); + DateTimeOffset[] times = [ new DateTimeOffset(time1, TimeZoneInfo.Local.GetUtcOffset(time1)), new DateTimeOffset(time1, TimeSpan.Zero), new DateTimeOffset(time2, TimeZoneInfo.Local.GetUtcOffset(time2)), - new DateTimeOffset(time2.AddHours(3), TimeZoneInfo.Local.GetUtcOffset(time2.AddHours(3))) }; - - // Retrieve the time zone for Eastern Standard Time (U.S. and Canada). - TimeZoneInfo est; - try { - est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); - } - catch (TimeZoneNotFoundException) { - Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); - return; - } - catch (InvalidTimeZoneException) { - Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); - return; - } + new DateTimeOffset(time2.AddHours(3), TimeZoneInfo.Local.GetUtcOffset(time2.AddHours(3))) ]; - // Display the current time zone name. - Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName); - - // Convert each time in the array. - foreach (DateTimeOffset timeToConvert in times) - { - DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est); - Console.WriteLine("Converted {0} to {1}.", timeToConvert, targetTime); - } - } + // Retrieve the time zone for Eastern Standard Time (U.S. and Canada). + TimeZoneInfo est; + try + { + est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); + return; + } + catch (InvalidTimeZoneException) + { + Console.WriteLine("Unable to retrieve the Eastern Standard time zone."); + return; + } + + // Display the current time zone name. + Console.WriteLine($"Local time zone: {TimeZoneInfo.Local.DisplayName}\n"); + + // Convert each time in the array. + foreach (DateTimeOffset timeToConvert in times) + { + DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est); + Console.WriteLine($"Converted {timeToConvert} to {targetTime}."); + } + } } // The example displays the following output: // Local time zone: (GMT-08:00) Pacific Time (US & Canada) -// +// // Converted 1/1/2010 12:01:00 AM -08:00 to 1/1/2010 3:01:00 AM -05:00. // Converted 1/1/2010 12:01:00 AM +00:00 to 12/31/2009 7:01:00 PM -05:00. // Converted 11/6/2010 11:30:00 PM -07:00 to 11/7/2010 1:30:00 AM -05:00. diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs index 9116ab83038..9c734110837 100644 --- a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs @@ -1,109 +1,101 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] public class TimeZoneConversion { - public static void Main() - { - TimeZoneConversion tzc = new TimeZoneConversion(); - Console.WriteLine("\nConvertToUtc:"); - tzc.ConvertToUtc(); - Console.WriteLine("\nConvertZonesToUtc:"); - tzc.ConvertZonesToUtc(); - Console.WriteLine(); - tzc.ConvertZonesById(); - } + public static void Main() + { + TimeZoneConversion tzc = new(); + Console.WriteLine("\nConvertToUtc:"); + tzc.ConvertToUtc(); + Console.WriteLine("\nConvertZonesToUtc:"); + tzc.ConvertZonesToUtc(); + Console.WriteLine(); + tzc.ConvertZonesById(); + } - private void ConvertToUtc() - { - // - DateTime datNowLocal = DateTime.Now; - Console.WriteLine("Converting {0}, Kind {1}:", datNowLocal, datNowLocal.Kind); - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNowLocal), TimeZoneInfo.ConvertTimeToUtc(datNowLocal).Kind); - Console.WriteLine(); + private void ConvertToUtc() + { + // + DateTime datNowLocal = DateTime.Now; + Console.WriteLine($"Converting {datNowLocal}, Kind {datNowLocal.Kind}:"); + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNowLocal)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNowLocal).Kind}"); + Console.WriteLine(); - DateTime datNowUtc = DateTime.UtcNow; - Console.WriteLine("Converting {0}, Kind {1}", datNowUtc, datNowUtc.Kind); - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNowUtc), TimeZoneInfo.ConvertTimeToUtc(datNowUtc).Kind); - Console.WriteLine(); - - DateTime datNow = new DateTime(2007, 10, 26, 13, 32, 00); - Console.WriteLine("Converting {0}, Kind {1}", datNow, datNow.Kind); - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNow), TimeZoneInfo.ConvertTimeToUtc(datNow).Kind); - Console.WriteLine(); - - DateTime datAmbiguous = new DateTime(2007, 11, 4, 1, 30, 00); - Console.WriteLine("Converting {0}, Kind {1}, Ambiguous {2}", datAmbiguous, datAmbiguous.Kind, TimeZoneInfo.Local.IsAmbiguousTime(datAmbiguous)); - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datAmbiguous), TimeZoneInfo.ConvertTimeToUtc(datAmbiguous).Kind); - Console.WriteLine(); - - DateTime datInvalid = new DateTime(2007, 3, 11, 02, 30, 00); - Console.WriteLine("Converting {0}, Kind {1}, Invalid {2}", datInvalid, datInvalid.Kind, TimeZoneInfo.Local.IsInvalidTime(datInvalid)); - try - { - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datInvalid), TimeZoneInfo.ConvertTimeToUtc(datInvalid).Kind); - } - catch (ArgumentException e) - { - Console.WriteLine(" {0}: Cannot convert {1} to UTC.", e.GetType().Name, datInvalid); - } - Console.WriteLine(); + DateTime datNowUtc = DateTime.UtcNow; + Console.WriteLine($"Converting {datNowUtc}, Kind {datNowUtc.Kind}"); + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNowUtc)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNowUtc).Kind}"); + Console.WriteLine(); - DateTime datNearMax = new DateTime(9999, 12, 31, 22, 00, 00); - Console.WriteLine("Converting {0}, Kind {1}", datNearMax, datNearMax.Kind); - Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNearMax), TimeZoneInfo.ConvertTimeToUtc(datNearMax).Kind); - Console.WriteLine(); - // - // This example produces the following output if the local time zone - // is Pacific Standard Time: - // - // Converting 8/31/2007 2:26:28 PM, Kind Local: - // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc - // - // Converting 8/31/2007 9:26:28 PM, Kind Utc - // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc - // - // Converting 10/26/2007 1:32:00 PM, Kind Unspecified - // ConvertTimeToUtc: 10/26/2007 8:32:00 PM, Kind Utc - // - // Converting 11/4/2007 1:30:00 AM, Kind Unspecified, Ambiguous True - // ConvertTimeToUtc: 11/4/2007 9:30:00 AM, Kind Utc - // - // Converting 3/11/2007 2:30:00 AM, Kind Unspecified, Invalid True - // ArgumentException: Cannot convert 3/11/2007 2:30:00 AM to UTC. - // - // Converting 12/31/9999 10:00:00 PM, Kind Unspecified - // ConvertTimeToUtc: 12/31/9999 11:59:59 PM, Kind Utc - // - // - } + DateTime datNow = new(2007, 10, 26, 13, 32, 00); + Console.WriteLine($"Converting {datNow}, Kind {datNow.Kind}"); + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNow)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNow).Kind}"); + Console.WriteLine(); - private void ConvertZonesToUtc() - { - } + DateTime datAmbiguous = new(2007, 11, 4, 1, 30, 00); + Console.WriteLine($"Converting {datAmbiguous}, Kind {datAmbiguous.Kind}, Ambiguous {TimeZoneInfo.Local.IsAmbiguousTime(datAmbiguous)}"); + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datAmbiguous)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datAmbiguous).Kind}"); + Console.WriteLine(); - private void ConvertZonesById() - { - // - DateTime currentTime = DateTime.Now; - Console.WriteLine("Current Times:"); - Console.WriteLine(); - Console.WriteLine("Los Angeles: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time")); - Console.WriteLine("Chicago: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time")); - Console.WriteLine("New York: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time")); - Console.WriteLine("London: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time")); - Console.WriteLine("Moscow: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time")); - Console.WriteLine("New Delhi: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time")); - Console.WriteLine("Beijing: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time")); - Console.WriteLine("Tokyo: {0}", - TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time")); - // - } + DateTime datInvalid = new(2007, 3, 11, 02, 30, 00); + Console.WriteLine($"Converting {datInvalid}, Kind {datInvalid.Kind}, Invalid {TimeZoneInfo.Local.IsInvalidTime(datInvalid)}"); + try + { + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datInvalid)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datInvalid).Kind}"); + } + catch (ArgumentException e) + { + Console.WriteLine($" {e.GetType().Name}: Cannot convert {datInvalid} to UTC."); + } + Console.WriteLine(); + + DateTime datNearMax = new(9999, 12, 31, 22, 00, 00); + Console.WriteLine($"Converting {datNearMax}, Kind {datNearMax.Kind}"); + Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNearMax)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNearMax).Kind}"); + Console.WriteLine(); + // + // This example produces the following output if the local time zone + // is Pacific Standard Time: + // + // Converting 8/31/2007 2:26:28 PM, Kind Local: + // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc + // + // Converting 8/31/2007 9:26:28 PM, Kind Utc + // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc + // + // Converting 10/26/2007 1:32:00 PM, Kind Unspecified + // ConvertTimeToUtc: 10/26/2007 8:32:00 PM, Kind Utc + // + // Converting 11/4/2007 1:30:00 AM, Kind Unspecified, Ambiguous True + // ConvertTimeToUtc: 11/4/2007 9:30:00 AM, Kind Utc + // + // Converting 3/11/2007 2:30:00 AM, Kind Unspecified, Invalid True + // ArgumentException: Cannot convert 3/11/2007 2:30:00 AM to UTC. + // + // Converting 12/31/9999 10:00:00 PM, Kind Unspecified + // ConvertTimeToUtc: 12/31/9999 11:59:59 PM, Kind Utc + // + // + } + + private void ConvertZonesToUtc() + { + } + + private void ConvertZonesById() + { + // + DateTime currentTime = DateTime.Now; + Console.WriteLine("Current Times:"); + Console.WriteLine(); + Console.WriteLine($"Los Angeles: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time")}"); + Console.WriteLine($"Chicago: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time")}"); + Console.WriteLine($"New York: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time")}"); + Console.WriteLine($"London: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time")}"); + Console.WriteLine($"Moscow: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time")}"); + Console.WriteLine($"New Delhi: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time")}"); + Console.WriteLine($"Beijing: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time")}"); + Console.WriteLine($"Tokyo: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time")}"); + // + } } diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs index 8840694a6ab..c42551b7094 100644 --- a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs +++ b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs @@ -3,20 +3,20 @@ public class Example { - public static void Main() - { - // Get time in local time zone - DateTime thisTime = DateTime.Now; - Console.WriteLine("Time in {0} zone: {1}", TimeZoneInfo.Local.IsDaylightSavingTime(thisTime) ? - TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName, thisTime); - Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local)); - // Get Tokyo Standard Time zone - TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"); - DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst); - Console.WriteLine("Time in {0} zone: {1}", tst.IsDaylightSavingTime(tstTime) ? - tst.DaylightName : tst.StandardName, tstTime); - Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(tstTime, tst)); - } + public static void Main() + { + // Get time in local time zone + DateTime thisTime = DateTime.Now; + Console.WriteLine($"Time in {(TimeZoneInfo.Local.IsDaylightSavingTime(thisTime) ? + TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName)} zone: {thisTime}"); + Console.WriteLine($" UTC Time: {TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local)}"); + // Get Tokyo Standard Time zone + TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"); + DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst); + Console.WriteLine($"Time in {(tst.IsDaylightSavingTime(tstTime) ? + tst.DaylightName : tst.StandardName)} zone: {tstTime}"); + Console.WriteLine($" UTC Time: {TimeZoneInfo.ConvertTimeToUtc(tstTime, tst)}"); + } } // The example displays output like the following when run on a system in the // U.S. Pacific Standard Time zone: diff --git a/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs b/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs index 009775a0c46..ae9f0a3c7b0 100644 --- a/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs +++ b/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs @@ -2,261 +2,249 @@ using System.IO; // using System.Collections.Generic; -using System.Collections.ObjectModel; + // public class TimeZoneCreation { - public static void Main() - { - Console.WriteLine("First Overload of CreateCustomTimeZone: "); - TimeZoneCreation tzc = new TimeZoneCreation(); - tzc.DefineMawsonTime(); - Console.WriteLine(); - Console.WriteLine("Second Overload of CreateCustomTimeZone: "); - tzc.DefinePalmerTime(); - Console.WriteLine(); - tzc.DefineNonDSTTime(); - Console.WriteLine("About to create Antarctic/South Pole time zone"); - // Define Time Zone for Serialization - TimeZoneInfo southPole = tzc.InitializeTimeZone(); - tzc.TestCST(); - } + public static void Main() + { + Console.WriteLine("First Overload of CreateCustomTimeZone: "); + TimeZoneCreation tzc = new(); + tzc.DefineMawsonTime(); + Console.WriteLine(); + Console.WriteLine("Second Overload of CreateCustomTimeZone: "); + tzc.DefinePalmerTime(); + Console.WriteLine(); + tzc.DefineNonDSTTime(); + Console.WriteLine("About to create Antarctic/South Pole time zone"); + // Define Time Zone for Serialization + TimeZoneInfo southPole = tzc.InitializeTimeZone(); + tzc.TestCST(); + } + + private void TestCST() + { + Console.WriteLine(); + Console.WriteLine("Testing new Central Standard Time zone..."); + Console.WriteLine(); + TimeZoneInfo cst = CreateNewCentralStandardTimeZone(); + // + TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + + DateTime pastDate1 = new(1942, 2, 11); + Console.WriteLine($"Is {pastDate1} daylight saving time: {cst.IsDaylightSavingTime(pastDate1)}"); - private void TestCST() - { - Console.WriteLine(); - Console.WriteLine("Testing new Central Standard Time zone..."); - Console.WriteLine(); - TimeZoneInfo cst = CreateNewCentralStandardTimeZone(); - // - TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + DateTime pastDate2 = new(1967, 10, 29, 1, 30, 00); + Console.WriteLine($"Is {pastDate2} ambiguous: {cst.IsAmbiguousTime(pastDate2)}"); - DateTime pastDate1 = new DateTime(1942, 2, 11); - Console.WriteLine("Is {0} daylight saving time: {1}", pastDate1, - cst.IsDaylightSavingTime(pastDate1)); - - DateTime pastDate2 = new DateTime(1967, 10, 29, 1, 30, 00); - Console.WriteLine("Is {0} ambiguous: {1}", pastDate2, - cst.IsAmbiguousTime(pastDate2)); + DateTime pastDate3 = new(1974, 1, 7, 2, 59, 00); + Console.WriteLine($"{pastDate3} {(est.IsDaylightSavingTime(pastDate3) ? + est.DaylightName : est.StandardName)} is {TimeZoneInfo.ConvertTime(pastDate3, est, cst)} {(cst.IsDaylightSavingTime(TimeZoneInfo.ConvertTime(pastDate3, est, cst)) ? + cst.DaylightName : cst.StandardName)}"); + // + // This code produces the following output to the console: + // + // Is 2/11/1942 12:00:00 AM daylight saving time: True + // Is 10/29/1967 1:30:00 AM ambiguous: True + // 1/7/1974 2:59:00 AM Eastern Standard Time is 1/7/1974 2:59:00 AM Central Daylight Time + // + } - DateTime pastDate3 = new DateTime(1974, 1, 7, 2, 59, 00); - Console.WriteLine("{0} {1} is {2} {3}", pastDate3, - est.IsDaylightSavingTime(pastDate3) ? - est.DaylightName : est.StandardName, - TimeZoneInfo.ConvertTime(pastDate3, est, cst), - cst.IsDaylightSavingTime(TimeZoneInfo.ConvertTime(pastDate3, est, cst)) ? - cst.DaylightName : cst.StandardName); - // - // This code produces the following output to the console: - // - // Is 2/11/1942 12:00:00 AM daylight saving time: True - // Is 10/29/1967 1:30:00 AM ambiguous: True - // 1/7/1974 2:59:00 AM Eastern Standard Time is 1/7/1974 2:59:00 AM Central Daylight Time - // - } + private void DefineMawsonTime() + { + // + string displayName = "(GMT+06:00) Antarctica/Mawson Time"; + string standardName = "Mawson Time"; + TimeSpan offset = new(06, 00, 00); + TimeZoneInfo mawson = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName); + Console.WriteLine($"The current time is {TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, mawson)} {mawson.StandardName}"); + // + } - private void DefineMawsonTime() - { - // - string displayName = "(GMT+06:00) Antarctica/Mawson Time"; - string standardName = "Mawson Time"; - TimeSpan offset = new TimeSpan(06, 00, 00); - TimeZoneInfo mawson = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName); - Console.WriteLine("The current time is {0} {1}", - TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, mawson), - mawson.StandardName); - // - } - - private void DefinePalmerTime() - { - // - // Define transition times to/from DST - TimeZoneInfo.TransitionTime startTransition, endTransition; - startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), - 10, 2, DayOfWeek.Sunday); - endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), - 3, 2, DayOfWeek.Sunday); - // Define adjustment rule - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment; - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); - // Create array for adjustment rules - TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment}; - // Define other custom time zone arguments - string displayName = "(GMT-04:00) Antarctica/Palmer Time"; - string standardName = "Palmer Time"; - string daylightName = "Palmer Daylight Time"; - TimeSpan offset = new TimeSpan(-4, 0, 0); - TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments); - Console.WriteLine("The current time is {0} {1}", - TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, palmer), - palmer.StandardName); - // - } + private void DefinePalmerTime() + { + // + // Define transition times to/from DST + TimeZoneInfo.TransitionTime startTransition, endTransition; + startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), + 10, 2, DayOfWeek.Sunday); + endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), + 3, 2, DayOfWeek.Sunday); + // Define adjustment rule + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment; + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); + // Create array for adjustment rules + TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ]; + // Define other custom time zone arguments + string displayName = "(GMT-04:00) Antarctica/Palmer Time"; + string standardName = "Palmer Time"; + string daylightName = "Palmer Daylight Time"; + TimeSpan offset = new(-4, 0, 0); + TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments); + Console.WriteLine($"The current time is {TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, palmer)} {palmer.StandardName}"); + // + } - private void DefineNonDSTTime() - { - // - // Define transition times to/from DST - TimeZoneInfo.TransitionTime startTransition, endTransition; - startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), - 10, 2, DayOfWeek.Sunday); - endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1,3, 0, 0), - 3, 2, DayOfWeek.Sunday); - // Define adjustment rule - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), - DateTime.MaxValue.Date, delta, startTransition, endTransition); - // Create array for adjustment rules - TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment}; - // Define other custom time zone arguments - string displayName = "(GMT-04:00) Antarctica/Palmer Time"; - string standardName = "Palmer Standard Time"; - string daylightName = "Palmer Daylight Time"; - TimeSpan offset = new TimeSpan(-4, 0, 0); - // Create custom time zone without copying DST information - TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, - daylightName, adjustments, true); - // Indicate whether new time zone//s adjustment rules are present - Console.WriteLine("{0} {1}has {2} adjustment rules.", - palmer.StandardName, - ! (string.IsNullOrEmpty(palmer.DaylightName)) ? "(" + palmer.DaylightName + ") ": "" , - palmer.GetAdjustmentRules().Length); - // Indicate whether new time zone supports DST - Console.WriteLine("{0} supports DST: {1}", palmer.StandardName, palmer.SupportsDaylightSavingTime); - // - } + private void DefineNonDSTTime() + { + // + // Define transition times to/from DST + TimeZoneInfo.TransitionTime startTransition, endTransition; + startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), + 10, 2, DayOfWeek.Sunday); + endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), + 3, 2, DayOfWeek.Sunday); + // Define adjustment rule + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), + DateTime.MaxValue.Date, delta, startTransition, endTransition); + // Create array for adjustment rules + TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ]; + // Define other custom time zone arguments + string displayName = "(GMT-04:00) Antarctica/Palmer Time"; + string standardName = "Palmer Standard Time"; + string daylightName = "Palmer Daylight Time"; + TimeSpan offset = new(-4, 0, 0); + // Create custom time zone without copying DST information + TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, + daylightName, adjustments, true); + // Indicate whether new time zone//s adjustment rules are present + Console.WriteLine($"{palmer.StandardName} {(!(string.IsNullOrEmpty(palmer.DaylightName)) ? "(" + palmer.DaylightName + ") " : "")}has {palmer.GetAdjustmentRules().Length} adjustment rules."); + // Indicate whether new time zone supports DST + Console.WriteLine($"{palmer.StandardName} supports DST: {palmer.SupportsDaylightSavingTime}"); + // + } - // - private TimeZoneInfo InitializeTimeZone() - { - TimeZoneInfo southPole = null; - // Determine if South Pole time zone is defined in system - try - { - southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time"); - } - // Time zone does not exist; create it, store it in a text file, and return it - catch - { - const string filename = @".\TimeZoneInfo.txt"; - bool found = false; - - if (File.Exists(filename)) - { - StreamReader reader = new StreamReader(filename); - string timeZoneInfo; - while (reader.Peek() >= 0) + // + private TimeZoneInfo InitializeTimeZone() + { + TimeZoneInfo southPole = null; + // Determine if South Pole time zone is defined in system + try + { + southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time"); + } + // Time zone does not exist; create it, store it in a text file, and return it + catch + { + const string filename = @".\TimeZoneInfo.txt"; + bool found = false; + + if (File.Exists(filename)) { - timeZoneInfo = reader.ReadLine(); - if (timeZoneInfo.Contains("Antarctica/South Pole")) - { - southPole = TimeZoneInfo.FromSerializedString(timeZoneInfo); - reader.Close(); - found = true; - break; - } + StreamReader reader = new(filename); + string timeZoneInfo; + while (reader.Peek() >= 0) + { + timeZoneInfo = reader.ReadLine(); + if (timeZoneInfo.Contains("Antarctica/South Pole")) + { + southPole = TimeZoneInfo.FromSerializedString(timeZoneInfo); + reader.Close(); + found = true; + break; + } + } } - } - if (!found) - { - // Define transition times to/from DST - TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 1, DayOfWeek.Sunday); - TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 3, DayOfWeek.Sunday); - // Define adjustment rule - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1989, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); - // Create array for adjustment rules - TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment}; - // Define other custom time zone arguments - string displayName = "(GMT+12:00) Antarctica/South Pole"; - string standardName = "Antarctica/South Pole Standard Time"; - string daylightName = "Antarctica/South Pole Daylight Time"; - TimeSpan offset = new TimeSpan(12, 0, 0); - southPole = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments); - // Write time zone to the file - StreamWriter writer = new StreamWriter(filename, true); - writer.WriteLine(southPole.ToSerializedString()); - writer.Close(); - } - } - return southPole; - } - // + if (!found) + { + // Define transition times to/from DST + TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 1, DayOfWeek.Sunday); + TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 3, DayOfWeek.Sunday); + // Define adjustment rule + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1989, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); + // Create array for adjustment rules + TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ]; + // Define other custom time zone arguments + string displayName = "(GMT+12:00) Antarctica/South Pole"; + string standardName = "Antarctica/South Pole Standard Time"; + string daylightName = "Antarctica/South Pole Daylight Time"; + TimeSpan offset = new(12, 0, 0); + southPole = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments); + // Write time zone to the file + StreamWriter writer = new(filename, true); + writer.WriteLine(southPole.ToSerializedString()); + writer.Close(); + } + } + return southPole; + } + // + + private TimeZoneInfo CreateNewCentralStandardTimeZone() + { + // + TimeZoneInfo cst; + // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone + TimeSpan delta = new(1, 0, 0); + TimeZoneInfo.AdjustmentRule adjustment; + List adjustmentList = []; + // Declare transition time variables to hold transition time information + TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; + + // Define new Central Standard Time zone 6 hours earlier than UTC + // Define rule 1 (for 1918-1919) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 05, DayOfWeek.Sunday); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 05, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1918, 1, 1), new DateTime(1919, 12, 31), delta, + transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 2 (for 1942) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 09); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1942, 1, 1), new DateTime(1942, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 3 (for 1945) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 0, 0), 08, 14); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 09, 30); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1945, 1, 1), new DateTime(1945, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define end rule (for 1967-2006) + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); + // Define rule 4 (for 1967-73) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1967, 1, 1), new DateTime(1973, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 5 (for 1974 only) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 01, 06); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1974, 1, 1), new DateTime(1974, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 6 (for 1975 only) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 23); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1975, 1, 1), new DateTime(1975, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 7 (1976-1986) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 8 (1987-2006) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + // Define rule 9 (2007- ) + transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday); + transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday); + adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 1, 1), DateTime.MaxValue.Date, + delta, transitionRuleStart, transitionRuleEnd); + adjustmentList.Add(adjustment); + + // Convert list of adjustment rules to an array + TimeZoneInfo.AdjustmentRule[] adjustments = new TimeZoneInfo.AdjustmentRule[adjustmentList.Count]; + adjustmentList.CopyTo(adjustments); - private TimeZoneInfo CreateNewCentralStandardTimeZone() - { - // - TimeZoneInfo cst; - // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone - TimeSpan delta = new TimeSpan(1, 0, 0); - TimeZoneInfo.AdjustmentRule adjustment; - List adjustmentList = new List(); - // Declare transition time variables to hold transition time information - TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd; - - // Define new Central Standard Time zone 6 hours earlier than UTC - // Define rule 1 (for 1918-1919) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 05, DayOfWeek.Sunday); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 05, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1918, 1, 1), new DateTime(1919, 12, 31), delta, - transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 2 (for 1942) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 09); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1942, 1, 1), new DateTime(1942, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 3 (for 1945) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 0, 0), 08, 14); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 09, 30); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1945, 1, 1), new DateTime(1945, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define end rule (for 1967-2006) - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); - // Define rule 4 (for 1967-73) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1967, 1, 1), new DateTime(1973, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 5 (for 1974 only) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 01, 06); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1974, 1, 1), new DateTime(1974, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 6 (for 1975 only) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 23); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1975, 1, 1), new DateTime(1975, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 7 (1976-1986) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 8 (1987-2006) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - // Define rule 9 (2007- ) - transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday); - transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday); - adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 1, 1), DateTime.MaxValue.Date, - delta, transitionRuleStart, transitionRuleEnd); - adjustmentList.Add(adjustment); - - // Convert list of adjustment rules to an array - TimeZoneInfo.AdjustmentRule[] adjustments = new TimeZoneInfo.AdjustmentRule[adjustmentList.Count]; - adjustmentList.CopyTo(adjustments); - - cst = TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0), - "(GMT-06:00) Central Time (US Only)", "Central Standard Time", - "Central Daylight Time", adjustments); - // - return cst; - } + cst = TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0), + "(GMT-06:00) Central Time (US Only)", "Central Standard Time", + "Central Daylight Time", adjustments); + // + return cst; + } } diff --git a/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs b/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs index 7078d2a0e16..6adfa570872 100644 --- a/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs +++ b/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs @@ -1,53 +1,43 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] public class DstTest { - public static void Main() - { - DstTest test = new DstTest(); - test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 05, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local); - test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 01, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local); - test.MayBeDST(); - } + public static void Main() + { + DstTest test = new(); + test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 05, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local); + test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 01, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local); + test.MayBeDST(); + } - // - private void DisplayDateWithTimeZoneName(DateTime date1, TimeZoneInfo timeZone) - { - Console.WriteLine("The time is {0:t} on {0:d} {1}", - date1, - timeZone.IsDaylightSavingTime(date1) ? - timeZone.DaylightName : timeZone.StandardName); - } - // The example displays output similar to the following: - // The time is 1:00 AM on 4/2/2006 Pacific Standard Time - // - - private void MayBeDST() - { - // - DateTime unclearDate = new DateTime(2007, 11, 4, 1, 30, 0); - // Test if time is ambiguous. - Console.WriteLine("In the {0}, {1} is {2}ambiguous.", - TimeZoneInfo.Local.DisplayName, - unclearDate, - TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ? "" : "not "); - // Test if time is DST. - Console.WriteLine("In the {0}, {1} is {2}daylight saving time.", - TimeZoneInfo.Local.DisplayName, - unclearDate, - TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate) ? "" : "not "); - Console.WriteLine(); - // Report time as DST if it is either ambiguous or DST. - if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) || - TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate)) - Console.WriteLine("{0} may be daylight saving time in {1}.", - unclearDate, TimeZoneInfo.Local.DisplayName); - // The example displays the following output: - // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is ambiguous. - // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is not daylight saving time. - // - // 11/4/2007 1:30:00 AM may be daylight saving time in (GMT-08:00) Pacific Time (US & Canada). - // - } + // + private void DisplayDateWithTimeZoneName(DateTime date1, TimeZoneInfo timeZone) => Console.WriteLine("The time is {0:t} on {0:d} {1}", + date1, + timeZone.IsDaylightSavingTime(date1) ? + timeZone.DaylightName : timeZone.StandardName); + // The example displays output similar to the following: + // The time is 1:00 AM on 4/2/2006 Pacific Standard Time + // + + private void MayBeDST() + { + // + DateTime unclearDate = new(2007, 11, 4, 1, 30, 0); + // Test if time is ambiguous. + Console.WriteLine($"In the {TimeZoneInfo.Local.DisplayName}, {unclearDate} is {(TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ? "" : "not ")}ambiguous."); + // Test if time is DST. + Console.WriteLine($"In the {TimeZoneInfo.Local.DisplayName}, {unclearDate} is {(TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate) ? "" : "not ")}daylight saving time."); + Console.WriteLine(); + // Report time as DST if it is either ambiguous or DST. + if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) || + TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate)) + Console.WriteLine($"{unclearDate} may be daylight saving time in {TimeZoneInfo.Local.DisplayName}."); + // The example displays the following output: + // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is ambiguous. + // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is not daylight saving time. + // + // 11/4/2007 1:30:00 AM may be daylight saving time in (GMT-08:00) Pacific Time (US & Canada). + // + } } diff --git a/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs b/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs index f2f192d1c2a..d27f1973e91 100644 --- a/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs +++ b/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - TimeZoneInfo thisTimeZone; - object obj1, obj2; - - thisTimeZone = TimeZoneInfo.Local; - obj1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); - obj2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); - Console.WriteLine(thisTimeZone.Equals(obj1)); - Console.WriteLine(thisTimeZone.Equals(obj2)); - } + public static void Main() + { + TimeZoneInfo thisTimeZone; + object obj1, obj2; + + thisTimeZone = TimeZoneInfo.Local; + obj1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); + obj2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + Console.WriteLine(thisTimeZone.Equals(obj1)); + Console.WriteLine(thisTimeZone.Equals(obj2)); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs b/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs index e1ab69a2697..9314fc9e9b1 100644 --- a/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs +++ b/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs @@ -1,102 +1,99 @@ using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] namespace TimeZoneInfoCode { -public class TimeOffsets -{ - public static void Main() - { - TimeOffsets to = new TimeOffsets(); - to.Start(); - } - - private void Start() - { - // - Console.WriteLine(); - ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 1, 0, 0), - TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); - Console.WriteLine(); - ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Local), - TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); - Console.WriteLine(); - ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 00, 00, 00, DateTimeKind.Local), - TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); - Console.WriteLine(); - ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Unspecified), - TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); - Console.WriteLine(); - ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 07, 00, 00, DateTimeKind.Utc), - TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); - // - // This example produces the following output if run in the Pacific time zone: - // - // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times: - // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC - // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC - // - // 11/4/2007 1:00:00 AM Pacific Standard Time is not ambiguous in time zone (GMT-06:00) Central Time (US & Canada). - // - // 11/4/2007 12:00:00 AM local time maps to the following possible times: - // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC - // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC - // - // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times: - // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC - // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC - // - // 11/4/2007 7:00:00 AM UTC maps to the following possible times: - // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC - // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC - // - // - } - - // - private void ShowPossibleUtcTimes(DateTime ambiguousTime, TimeZoneInfo timeZone) - { - // Determine if time is ambiguous in target time zone - if (!timeZone.IsAmbiguousTime(ambiguousTime)) - { - Console.WriteLine("{0} is not ambiguous in time zone {1}.", - ambiguousTime, - timeZone.DisplayName); - } - else - { - // Display time and its time zone (local, UTC, or indicated by timeZone argument) - string originalTimeZoneName; - if (ambiguousTime.Kind == DateTimeKind.Utc) - originalTimeZoneName = "UTC"; - else if (ambiguousTime.Kind == DateTimeKind.Local) - originalTimeZoneName = "local time"; - else - originalTimeZoneName = timeZone.DisplayName; + public class TimeOffsets + { + public static void Main() + { + TimeOffsets to = new(); + to.Start(); + } - Console.WriteLine("{0} {1} maps to the following possible times:", - ambiguousTime, originalTimeZoneName); - // Get ambiguous offsets - TimeSpan[] offsets = timeZone.GetAmbiguousTimeOffsets(ambiguousTime); - // Handle times not in time zone of timeZone argument - // Local time where timeZone is not local zone - if ((ambiguousTime.Kind == DateTimeKind.Local) && ! timeZone.Equals(TimeZoneInfo.Local)) - ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Local, timeZone); - // UTC time where timeZone is not UTC zone - else if ((ambiguousTime.Kind == DateTimeKind.Utc) && ! timeZone.Equals(TimeZoneInfo.Utc)) - ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Utc, timeZone); + private void Start() + { + // + Console.WriteLine(); + ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 1, 0, 0), + TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); + Console.WriteLine(); + ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Local), + TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); + Console.WriteLine(); + ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 00, 00, 00, DateTimeKind.Local), + TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); + Console.WriteLine(); + ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Unspecified), + TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); + Console.WriteLine(); + ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 07, 00, 00, DateTimeKind.Utc), + TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); + // + // This example produces the following output if run in the Pacific time zone: + // + // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times: + // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC + // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC + // + // 11/4/2007 1:00:00 AM Pacific Standard Time is not ambiguous in time zone (GMT-06:00) Central Time (US & Canada). + // + // 11/4/2007 12:00:00 AM local time maps to the following possible times: + // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC + // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC + // + // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times: + // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC + // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC + // + // 11/4/2007 7:00:00 AM UTC maps to the following possible times: + // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC + // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC + // + // + } - // Display each offset and its mapping to UTC - foreach (TimeSpan offset in offsets) - { - if (offset.Equals(timeZone.BaseUtcOffset)) - Console.WriteLine("If {0} is {1}, {2} UTC", ambiguousTime, timeZone.StandardName, ambiguousTime - offset); + // + private void ShowPossibleUtcTimes(DateTime ambiguousTime, TimeZoneInfo timeZone) + { + // Determine if time is ambiguous in target time zone + if (!timeZone.IsAmbiguousTime(ambiguousTime)) + { + Console.WriteLine($"{ambiguousTime} is not ambiguous in time zone {timeZone.DisplayName}."); + } else - Console.WriteLine("If {0} is {1}, {2} UTC", ambiguousTime, timeZone.DaylightName, ambiguousTime - offset); - } - } - } - // -} + { + // Display time and its time zone (local, UTC, or indicated by timeZone argument) + string originalTimeZoneName; + if (ambiguousTime.Kind == DateTimeKind.Utc) + originalTimeZoneName = "UTC"; + else if (ambiguousTime.Kind == DateTimeKind.Local) + originalTimeZoneName = "local time"; + else + originalTimeZoneName = timeZone.DisplayName; + + Console.WriteLine($"{ambiguousTime} {originalTimeZoneName} maps to the following possible times:"); + // Get ambiguous offsets + TimeSpan[] offsets = timeZone.GetAmbiguousTimeOffsets(ambiguousTime); + // Handle times not in time zone of timeZone argument + // Local time where timeZone is not local zone + if ((ambiguousTime.Kind == DateTimeKind.Local) && !timeZone.Equals(TimeZoneInfo.Local)) + ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Local, timeZone); + // UTC time where timeZone is not UTC zone + else if ((ambiguousTime.Kind == DateTimeKind.Utc) && !timeZone.Equals(TimeZoneInfo.Utc)) + ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Utc, timeZone); + + // Display each offset and its mapping to UTC + foreach (TimeSpan offset in offsets) + { + if (offset.Equals(timeZone.BaseUtcOffset)) + Console.WriteLine($"If {ambiguousTime} is {timeZone.StandardName}, {ambiguousTime - offset} UTC"); + else + Console.WriteLine($"If {ambiguousTime} is {timeZone.DaylightName}, {ambiguousTime - offset} UTC"); + } + } + } + // + } } // end namespace diff --git a/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs b/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs index e8362f99e5c..45d37a4afd0 100644 --- a/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs +++ b/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs @@ -1,113 +1,106 @@ // using System; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] namespace TimeZoneInfoCode { - public class TimeOffsets - { - public static void Main() - { - TimeOffsets timeoff = new TimeOffsets(); - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); - - timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Local); - timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Local); - timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), TimeZoneInfo.Local); - timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Local); - timeoff.ShowOffset(DateTime.UtcNow, TimeZoneInfo.Local); - timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Utc); - timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Utc); - timeoff.ShowOffset(new DateTime(2006, 12, 10, 3, 0, 0), TimeZoneInfo.Utc); - timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Utc); - timeoff.ShowOffset(DateTime.Now, TimeZoneInfo.Utc); - timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), cst); - timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), cst); - timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), cst); - timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0, 0), cst); - timeoff.ShowOffset(new DateTime(2007, 11, 14, 00, 00, 00, DateTimeKind.Local), cst); - } - - private void ShowOffset(DateTime time, TimeZoneInfo timeZone) - { - DateTime convertedTime = time; - TimeSpan offset; - - if (time.Kind == DateTimeKind.Local && ! timeZone.Equals(TimeZoneInfo.Local)) - convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Local, timeZone); - else if (time.Kind == DateTimeKind.Utc && ! timeZone.Equals(TimeZoneInfo.Utc)) - convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, timeZone); - - offset = timeZone.GetUtcOffset(time); - if (time == convertedTime) - { - Console.WriteLine("{0} {1} ", time, - timeZone.IsDaylightSavingTime(time) ? timeZone.DaylightName : timeZone.StandardName); - Console.WriteLine(" It differs from UTC by {0} hours, {1} minutes.", - offset.Hours, - offset.Minutes); - } - else - { - Console.WriteLine("{0} {1} ", time, - time.Kind == DateTimeKind.Utc ? "UTC" : TimeZoneInfo.Local.Id); - Console.WriteLine(" converts to {0} {1}.", - convertedTime, - timeZone.Id); - Console.WriteLine(" It differs from UTC by {0} hours, {1} minutes.", - offset.Hours, offset.Minutes); - } - Console.WriteLine(); - } - } + public class TimeOffsets + { + public static void Main() + { + TimeOffsets timeoff = new(); + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); + + timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Local); + timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Local); + timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), TimeZoneInfo.Local); + timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Local); + timeoff.ShowOffset(DateTime.UtcNow, TimeZoneInfo.Local); + timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Utc); + timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Utc); + timeoff.ShowOffset(new DateTime(2006, 12, 10, 3, 0, 0), TimeZoneInfo.Utc); + timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Utc); + timeoff.ShowOffset(DateTime.Now, TimeZoneInfo.Utc); + timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), cst); + timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), cst); + timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), cst); + timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0, 0), cst); + timeoff.ShowOffset(new DateTime(2007, 11, 14, 00, 00, 00, DateTimeKind.Local), cst); + } + + private void ShowOffset(DateTime time, TimeZoneInfo timeZone) + { + DateTime convertedTime = time; + TimeSpan offset; + + if (time.Kind == DateTimeKind.Local && !timeZone.Equals(TimeZoneInfo.Local)) + convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Local, timeZone); + else if (time.Kind == DateTimeKind.Utc && !timeZone.Equals(TimeZoneInfo.Utc)) + convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, timeZone); + + offset = timeZone.GetUtcOffset(time); + if (time == convertedTime) + { + Console.WriteLine($"{time} {(timeZone.IsDaylightSavingTime(time) ? timeZone.DaylightName : timeZone.StandardName)} "); + Console.WriteLine($" It differs from UTC by {offset.Hours} hours, {offset.Minutes} minutes."); + } + else + { + Console.WriteLine($"{time} {(time.Kind == DateTimeKind.Utc ? "UTC" : TimeZoneInfo.Local.Id)} "); + Console.WriteLine($" converts to {convertedTime} {timeZone.Id}."); + Console.WriteLine($" It differs from UTC by {offset.Hours} hours, {offset.Minutes} minutes."); + } + Console.WriteLine(); + } + } } // The example produces the following output: // -// 6/12/2006 11:00:00 AM Pacific Daylight Time +// 6/12/2006 11:00:00 AM Pacific Daylight Time // It differs from UTC by -7 hours, 0 minutes. -// -// 11/4/2007 1:00:00 AM Pacific Standard Time +// +// 11/4/2007 1:00:00 AM Pacific Standard Time // It differs from UTC by -8 hours, 0 minutes. -// -// 12/10/2006 3:00:00 PM Pacific Standard Time +// +// 12/10/2006 3:00:00 PM Pacific Standard Time // It differs from UTC by -8 hours, 0 minutes. -// -// 3/11/2007 2:30:00 AM Pacific Standard Time +// +// 3/11/2007 2:30:00 AM Pacific Standard Time // It differs from UTC by -8 hours, 0 minutes. -// -// 2/2/2007 8:35:46 PM UTC +// +// 2/2/2007 8:35:46 PM UTC // converts to 2/2/2007 12:35:46 PM Pacific Standard Time. // It differs from UTC by -8 hours, 0 minutes. -// -// 6/12/2006 11:00:00 AM UTC +// +// 6/12/2006 11:00:00 AM UTC // It differs from UTC by 0 hours, 0 minutes. -// -// 11/4/2007 1:00:00 AM UTC +// +// 11/4/2007 1:00:00 AM UTC // It differs from UTC by 0 hours, 0 minutes. -// -// 12/10/2006 3:00:00 AM UTC +// +// 12/10/2006 3:00:00 AM UTC // It differs from UTC by 0 hours, 0 minutes. -// -// 3/11/2007 2:30:00 AM UTC +// +// 3/11/2007 2:30:00 AM UTC // It differs from UTC by 0 hours, 0 minutes. -// -// 2/2/2007 12:35:46 PM Pacific Standard Time +// +// 2/2/2007 12:35:46 PM Pacific Standard Time // converts to 2/2/2007 8:35:46 PM UTC. // It differs from UTC by 0 hours, 0 minutes. -// -// 6/12/2006 11:00:00 AM Central Daylight Time +// +// 6/12/2006 11:00:00 AM Central Daylight Time // It differs from UTC by -5 hours, 0 minutes. -// -// 11/4/2007 1:00:00 AM Central Standard Time +// +// 11/4/2007 1:00:00 AM Central Standard Time // It differs from UTC by -6 hours, 0 minutes. -// -// 12/10/2006 3:00:00 PM Central Standard Time +// +// 12/10/2006 3:00:00 PM Central Standard Time // It differs from UTC by -6 hours, 0 minutes. -// -// 3/11/2007 2:30:00 AM Central Standard Time +// +// 3/11/2007 2:30:00 AM Central Standard Time // It differs from UTC by -6 hours, 0 minutes. -// -// 11/14/2007 12:00:00 AM Pacific Standard Time +// +// 11/14/2007 12:00:00 AM Pacific Standard Time // converts to 11/14/2007 2:00:00 AM Central Standard Time. // It differs from UTC by -6 hours, 0 minutes. // diff --git a/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs b/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs index 7cd2afbac76..cbc1b654be9 100644 --- a/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs +++ b/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs @@ -1,37 +1,35 @@ using System; using System.Collections.ObjectModel; -[assembly:CLSCompliant(true)] +[assembly: CLSCompliant(true)] namespace TimeZoneInfoCode { -public sealed class TestSameRules -{ - private TestSameRules() {} + public sealed class TestSameRules + { + private TestSameRules() { } - public static void Main() - { - // - ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); - TimeZoneInfo[] timeZoneArray = new TimeZoneInfo[timeZones.Count]; - timeZones.CopyTo(timeZoneArray, 0); - // Iterate array from top to bottom - for (int ctr = timeZoneArray.GetUpperBound(0); ctr >= 1; ctr--) - { - // Get next item from top - TimeZoneInfo thisTimeZone = timeZoneArray[ctr]; - for (int compareCtr = 0; compareCtr <= ctr - 1; compareCtr++) - { - // Determine if time zones have the same rules - if (thisTimeZone.HasSameRules(timeZoneArray[compareCtr])) + public static void Main() + { + // + ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones(); + TimeZoneInfo[] timeZoneArray = new TimeZoneInfo[timeZones.Count]; + timeZones.CopyTo(timeZoneArray, 0); + // Iterate array from top to bottom + for (int ctr = timeZoneArray.GetUpperBound(0); ctr >= 1; ctr--) { - Console.WriteLine("{0} has the same rules as {1}", - thisTimeZone.StandardName, - timeZoneArray[compareCtr].StandardName); + // Get next item from top + TimeZoneInfo thisTimeZone = timeZoneArray[ctr]; + for (int compareCtr = 0; compareCtr <= ctr - 1; compareCtr++) + { + // Determine if time zones have the same rules + if (thisTimeZone.HasSameRules(timeZoneArray[compareCtr])) + { + Console.WriteLine($"{thisTimeZone.StandardName} has the same rules as {timeZoneArray[compareCtr].StandardName}"); + } + } } - } - } - // - } -} + // + } + } } // End namespace diff --git a/snippets/csharp/System/TimeoutException/Overview/Project.csproj b/snippets/csharp/System/TimeoutException/Overview/Project.csproj new file mode 100644 index 00000000000..32e3c55e48b --- /dev/null +++ b/snippets/csharp/System/TimeoutException/Overview/Project.csproj @@ -0,0 +1,9 @@ + + + Exe + net10.0 + + + + + diff --git a/snippets/csharp/System/TimeoutException/Overview/to.cs b/snippets/csharp/System/TimeoutException/Overview/to.cs index 0043143a9cf..474629ad3db 100644 --- a/snippets/csharp/System/TimeoutException/Overview/to.cs +++ b/snippets/csharp/System/TimeoutException/Overview/to.cs @@ -9,31 +9,31 @@ class Sample { public static void Main() { - string input; - try + string input; + try { -// Set the COM1 serial port to speed = 4800 baud, parity = odd, -// data bits = 8, stop bits = 1. - SerialPort sp = new SerialPort("COM1", - 4800, Parity.Odd, 8, StopBits.One); -// Timeout after 2 seconds. - sp.ReadTimeout = 2000; - sp.Open(); - -// Read until either the default newline termination string -// is detected or the read operation times out. - input = sp.ReadLine(); - - sp.Close(); - -// Echo the input. - Console.WriteLine(input); + // Set the COM1 serial port to speed = 4800 baud, parity = odd, + // data bits = 8, stop bits = 1. + SerialPort sp = new SerialPort("COM1", + 4800, Parity.Odd, 8, StopBits.One); + // Timeout after 2 seconds. + sp.ReadTimeout = 2000; + sp.Open(); + + // Read until either the default newline termination string + // is detected or the read operation times out. + input = sp.ReadLine(); + + sp.Close(); + + // Echo the input. + Console.WriteLine(input); } -// Only catch timeout exceptions. - catch (TimeoutException e) + // Only catch timeout exceptions. + catch (TimeoutException e) { - Console.WriteLine(e); + Console.WriteLine(e); } } } @@ -51,4 +51,4 @@ at System.IO.Ports.SerialPort.ReadTo(String value) at System.IO.Ports.SerialPort.ReadLine() at Sample.Main() */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Tuple/Overview/Program.cs b/snippets/csharp/System/Tuple/Overview/Program.cs new file mode 100644 index 00000000000..c56a5555343 --- /dev/null +++ b/snippets/csharp/System/Tuple/Overview/Program.cs @@ -0,0 +1,5 @@ +TupleCreateC.Create1.Run(args); +CreateNTupleExample.Run(); +Constructor8Example.Run(); +TupleOverviewExample.Run(args); +TupleOverviewExample1.Run(); diff --git a/snippets/csharp/System/Tuple/Overview/Project.csproj b/snippets/csharp/System/Tuple/Overview/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/Tuple/Overview/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/Tuple/Overview/create1.cs b/snippets/csharp/System/Tuple/Overview/create1.cs index 1de4ab7ccbf..66ea3a5d0ba 100644 --- a/snippets/csharp/System/Tuple/Overview/create1.cs +++ b/snippets/csharp/System/Tuple/Overview/create1.cs @@ -4,7 +4,7 @@ namespace TupleCreateC { class Create1 { - static void Main(string[] args) + public static void Run(string[] args) { Create1Tuple(); New1Tuple(); @@ -47,7 +47,7 @@ private static void Create2Tuple() { // var tuple2 = Tuple.Create("New York", 32.68); - Console.WriteLine("{0}: {1}", tuple2.Item1, tuple2.Item2); + Console.WriteLine($"{tuple2.Item1}: {tuple2.Item2}"); // Displays New York: 32.68 // } @@ -56,7 +56,7 @@ private static void New2Tuple() { // var tuple2 = new Tuple("New York", 32.68); - Console.WriteLine("{0}: {1}", tuple2.Item1, tuple2.Item2); + Console.WriteLine($"{tuple2.Item1}: {tuple2.Item2}"); // Displays New York: 32.68 // } @@ -65,8 +65,7 @@ private static void Create3Tuple() { // var tuple3 = Tuple.Create("New York", 32.68, 51.87); - Console.WriteLine("{0}: lo {1}, hi {2}", - tuple3.Item1, tuple3.Item2, tuple3.Item3); + Console.WriteLine($"{tuple3.Item1}: lo {tuple3.Item2}, hi {tuple3.Item3}"); // Displays New York: lo 32.68, hi 51.87 // } @@ -76,8 +75,7 @@ private static void New3Tuple() // var tuple3 = new Tuple ("New York", 32.68, 51.87); - Console.WriteLine("{0}: lo {1}, hi {2}", - tuple3.Item1, tuple3.Item2, tuple3.Item3); + Console.WriteLine($"{tuple3.Item1}: lo {tuple3.Item2}, hi {tuple3.Item3}"); // Displays New York: lo 32.68, hi 51.87 // } @@ -86,9 +84,7 @@ private static void Create4Tuple() { // var tuple4 = Tuple.Create("New York", 32.68, 51.87, 76.3); - Console.WriteLine("{0}: Hi {1}, Lo {2}, Ave {3}", - tuple4.Item1, tuple4.Item4, tuple4.Item2, - tuple4.Item3); + Console.WriteLine($"{tuple4.Item1}: Hi {tuple4.Item4}, Lo {tuple4.Item2}, Ave {tuple4.Item3}"); // Displays New York: Hi 76.3, Lo 32.68, Ave 51.87 // } @@ -98,9 +94,7 @@ private static void New4Tuple() // var tuple4 = new Tuple ("New York", 32.68, 51.87, 76.3); - Console.WriteLine("{0}: Hi {1}, Lo {2}, Ave {3}", - tuple4.Item1, tuple4.Item4, tuple4.Item2, - tuple4.Item3); + Console.WriteLine($"{tuple4.Item1}: Hi {tuple4.Item4}, Lo {tuple4.Item2}, Ave {tuple4.Item3}"); // Displays New York: Hi 76.3, Lo 32.68, Ave 51.87 // } @@ -109,9 +103,7 @@ private static void Create5Tuple() { // var tuple5 = Tuple.Create("New York", 1990, 7322564, 2000, 8008278); - Console.WriteLine("{0}: {1:N0} in {2}, {3:N0} in {4}", - tuple5.Item1, tuple5.Item3, tuple5.Item2, - tuple5.Item5, tuple5.Item4); + Console.WriteLine($"{tuple5.Item1}: {tuple5.Item3:N0} in {tuple5.Item2}, {tuple5.Item5:N0} in {tuple5.Item4}"); // Displays New York: 7,322,564 in 1990, 8,008,278 in 2000 // } @@ -121,9 +113,7 @@ private static void New5Tuple() // var tuple5 = new Tuple ("New York", 1990, 7322564, 2000, 8008278); - Console.WriteLine("{0}: {1:N0} in {2}, {3:N0} in {4}", - tuple5.Item1, tuple5.Item3, tuple5.Item2, - tuple5.Item5, tuple5.Item4); + Console.WriteLine($"{tuple5.Item1}: {tuple5.Item3:N0} in {tuple5.Item2}, {tuple5.Item5:N0} in {tuple5.Item4}"); // Displays New York: 7,322,564 in 1990, 8,008,278 in 2000 // } @@ -132,9 +122,7 @@ private static void Create6Tuple() { // var tuple6 = Tuple.Create("Jane", 90, 87, 93, 67, 100); - Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}", - tuple6.Item1, tuple6.Item2, tuple6.Item3, - tuple6.Item4, tuple6.Item5, tuple6.Item6); + Console.WriteLine($"Test scores for {tuple6.Item1}: {tuple6.Item2}, {tuple6.Item3}, {tuple6.Item4}, {tuple6.Item5}, {tuple6.Item6}"); // Displays Test scores for Jane: 90, 87, 93, 67, 100 // } @@ -144,9 +132,7 @@ private static void New6Tuple() // var tuple6 = new Tuple ("Jane", 90, 87, 93, 67, 100); - Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}", - tuple6.Item1, tuple6.Item2, tuple6.Item3, - tuple6.Item4, tuple6.Item5, tuple6.Item6); + Console.WriteLine($"Test scores for {tuple6.Item1}: {tuple6.Item2}, {tuple6.Item3}, {tuple6.Item4}, {tuple6.Item5}, {tuple6.Item6}"); // Displays Test scores for Jane: 90, 87, 93, 67, 100 // } @@ -155,10 +141,7 @@ private static void Create7Tuple() { // var tuple7 = Tuple.Create("Jane", 90, 87, 93, 67, 100, 92); - Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}, {6}", - tuple7.Item1, tuple7.Item2, tuple7.Item3, - tuple7.Item4, tuple7.Item5, tuple7.Item6, - tuple7.Item7); + Console.WriteLine($"Test scores for {tuple7.Item1}: {tuple7.Item2}, {tuple7.Item3}, {tuple7.Item4}, {tuple7.Item5}, {tuple7.Item6}, {tuple7.Item7}"); // Displays Test scores for Jane: 90, 87, 93, 67, 100, 92 // } @@ -168,44 +151,41 @@ private static void New7Tuple() // var tuple7 = new Tuple ("Jane", 90, 87, 93, 67, 100, 92); - Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}, {6}", - tuple7.Item1, tuple7.Item2, tuple7.Item3, - tuple7.Item4, tuple7.Item5, tuple7.Item6, - tuple7.Item7); + Console.WriteLine($"Test scores for {tuple7.Item1}: {tuple7.Item2}, {tuple7.Item3}, {tuple7.Item4}, {tuple7.Item5}, {tuple7.Item6}, {tuple7.Item7}"); // Displays Test scores for Jane: 90, 87, 93, 67, 100, 92 // } private static void CreateNTuple() { -// Tuple innerTuple = -// Tuple.Create(1960, 1670140, 1980, 1203339, 2000, 951270); -// Tuple> tuple8 = -// Tuple.Create("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple); + // Tuple innerTuple = + // Tuple.Create(1960, 1670140, 1980, 1203339, 2000, 951270); + // Tuple> tuple8 = + // Tuple.Create("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple); } private static void NewNTuple() { // - var innerTuple = new Tuple - (1960, 1670140, 1980, 1203339, + var innerTuple = new Tuple + (1960, 1670140, 1980, 1203339, 2000, 951270); var tuple8 = new Tuple> ("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple); Console.WriteLine("Population of {0} in:\n {1}: {2,10:N0} \n" + - " {3}: {4,10:N0} \n" + - " {5}: {6,10:N0} \n" + - " {7}: {8,10:N0} \n" + - " {9}: {10,10:N0} \n" + + " {3}: {4,10:N0} \n" + + " {5}: {6,10:N0} \n" + + " {7}: {8,10:N0} \n" + + " {9}: {10,10:N0} \n" + " {11}: {12,10:N0} \n", tuple8.Item1, tuple8.Item2, tuple8.Item3, tuple8.Item4, tuple8.Item5, tuple8.Item6, tuple8.Item7, tuple8.Rest.Item1, tuple8.Rest.Item2, tuple8.Rest.Item3, tuple8.Rest.Item4, - tuple8.Rest.Item5, tuple8.Rest.Item6); + tuple8.Rest.Item5, tuple8.Rest.Item6); // The example displays the following output: // Population of Detroit in: // 1900: 285,704 @@ -213,18 +193,18 @@ private static void NewNTuple() // 1940: 1,623,452 // 1960: 1,670,140 // 1980: 1,203,339 - // 2000: 951,270 + // 2000: 951,270 // } private static void Example() { - var from1980 = Tuple.Create(1203339, 1027974, 951270); - var from1910 = new Tuple> - (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980); - var population = new Tuple>> - ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910); + var from1980 = Tuple.Create(1203339, 1027974, 951270); + var from1910 = new Tuple> + (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980); + var population = new Tuple>> + ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910); } } } diff --git a/snippets/csharp/System/Tuple/Overview/createntuple.cs b/snippets/csharp/System/Tuple/Overview/createntuple.cs index a254a670b99..e3229d8fc79 100644 --- a/snippets/csharp/System/Tuple/Overview/createntuple.cs +++ b/snippets/csharp/System/Tuple/Overview/createntuple.cs @@ -1,19 +1,19 @@ using System; -public class Example +public class CreateNTupleExample { - public static void Main() - { - // - var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19); - Console.WriteLine("Prime numbers less than 20: " + - "{0}, {1}, {2}, {3}, {4}, {5}, {6}, and {7}", - primes.Item1, primes.Item2, primes.Item3, - primes.Item4, primes.Item5, primes.Item6, - primes.Item7, primes.Rest.Item1); - // The example displays the following output: - // Prime numbers less than 20: 2, 3, 5, 7, 11, 13, 17, and 19 - // - Console.WriteLine(primes.ToString()); - } + public static void Run() + { + // + var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19); + Console.WriteLine("Prime numbers less than 20: " + + "{0}, {1}, {2}, {3}, {4}, {5}, {6}, and {7}", + primes.Item1, primes.Item2, primes.Item3, + primes.Item4, primes.Item5, primes.Item6, + primes.Item7, primes.Rest.Item1); + // The example displays the following output: + // Prime numbers less than 20: 2, 3, 5, 7, 11, 13, 17, and 19 + // + Console.WriteLine(primes); + } } diff --git a/snippets/csharp/System/Tuple/Overview/ctor8.cs b/snippets/csharp/System/Tuple/Overview/ctor8.cs index d1b551e9334..2ca778424f6 100644 --- a/snippets/csharp/System/Tuple/Overview/ctor8.cs +++ b/snippets/csharp/System/Tuple/Overview/ctor8.cs @@ -1,14 +1,14 @@ using System; -public class Example +public class Constructor8Example { - public static void Main() - { - // - var primes = new Tuple>(2, 3, 5, 7, 11, 13, 16, - new Tuple(19)); - // - Console.WriteLine(primes.ToString()); - } + public static void Run() + { + // + var primes = new Tuple>(2, 3, 5, 7, 11, 13, 16, + new Tuple(19)); + // + Console.WriteLine(primes); + } } diff --git a/snippets/csharp/System/Tuple/Overview/example.cs b/snippets/csharp/System/Tuple/Overview/example.cs index 78752e41f58..5677e08b60d 100644 --- a/snippets/csharp/System/Tuple/Overview/example.cs +++ b/snippets/csharp/System/Tuple/Overview/example.cs @@ -1,20 +1,20 @@ using System; -class Example +class TupleOverviewExample { - static void Main(string[] args) + public static void Run(string[] args) { // var from1980 = Tuple.Create(1203339, 1027974, 951270); - var from1910 = new Tuple> + var from1910 = new Tuple> (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980); var population = new Tuple>> + Tuple>> ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910); // - Console.WriteLine("Population of {0}", population.Item1); + Console.WriteLine($"Population of {population.Item1}"); Console.WriteLine(); - Console.WriteLine("{0,5} {1,14} {2,10}", "Year", "Population", "Change"); + Console.WriteLine($"{"Year",5} {"Population",14} {"Change",10}"); int year = population.Item2; ShowPopulation(year, population.Item3); @@ -48,16 +48,9 @@ static void Main(string[] args) ShowPopulationChange(year, population.Rest.Rest.Item3, population.Rest.Rest.Item2); } - private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, - ((double)(newPopulation - oldPopulation) / oldPopulation) / 10); - } + private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}"); - private static void ShowPopulation(int year, int newPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a"); - } + private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}"); } // The example displays the following output: // diff --git a/snippets/csharp/System/Tuple/Overview/example1.cs b/snippets/csharp/System/Tuple/Overview/example1.cs index dd02f8bc30a..af468923e9a 100644 --- a/snippets/csharp/System/Tuple/Overview/example1.cs +++ b/snippets/csharp/System/Tuple/Overview/example1.cs @@ -1,38 +1,36 @@ using System; -public class Example +public class TupleOverviewExample1 { - public static void Main() - { - Ctor1(); - Factory(); - } + public static void Run() + { + Ctor1(); + Factory(); + } - private static void Ctor1() - { - // - // Create a 7-tuple. - var population = new Tuple( - "New York", 7891957, 7781984, - 7894862, 7071639, 7322564, 8008278); - // Display the first and last elements. - Console.WriteLine("Population of {0} in 2000: {1:N0}", - population.Item1, population.Item7); - // The example displays the following output: - // Population of New York in 2000: 8,008,278 - // - } + private static void Ctor1() + { + // + // Create a 7-tuple. + var population = new Tuple( + "New York", 7891957, 7781984, + 7894862, 7071639, 7322564, 8008278); + // Display the first and last elements. + Console.WriteLine($"Population of {population.Item1} in 2000: {population.Item7:N0}"); + // The example displays the following output: + // Population of New York in 2000: 8,008,278 + // + } - private static void Factory() - { - // - // Create a 7-tuple. - var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278); - // Display the first and last elements. - Console.WriteLine("Population of {0} in 2000: {1:N0}", - population.Item1, population.Item7); - // The example displays the following output: - // Population of New York in 2000: 8,008,278 - // - } + private static void Factory() + { + // + // Create a 7-tuple. + var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278); + // Display the first and last elements. + Console.WriteLine($"Population of {population.Item1} in 2000: {population.Item7:N0}"); + // The example displays the following output: + // Population of New York in 2000: 8,008,278 + // + } } diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs index 4f900260888..09af1b8e0ef 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs @@ -3,33 +3,33 @@ public class Class1 { - public static void Main() - { - // Create five 8-tuple objects containing prime numbers. - var prime1 = new Tuple> (2, 3, 5, 7, 11, 13, 17, - new Tuple(19)); - var prime2 = new Tuple> (23, 29, 31, 37, 41, 43, 47, - new Tuple(55)); - var prime3 = new Tuple> (3, 2, 5, 7, 11, 13, 17, - new Tuple(19)); - var prime4 = new Tuple> (2, 3, 5, 7, 11, 13, 17, - new Tuple(19, 23)); - var prime5 = new Tuple> (2, 3, 5, 7, 11, 13, 17, - new Tuple(19)); - Console.WriteLine("{0} = {1} : {2}", prime1, prime2, prime1.Equals(prime2)); - Console.WriteLine("{0} = {1} : {2}", prime1, prime3, prime1.Equals(prime3)); - Console.WriteLine("{0} = {1} : {2}", prime1, prime4, prime1.Equals(prime4)); - Console.WriteLine("{0} = {1} : {2}", prime1, prime5, prime1.Equals(prime5)); - } + public static void Main() + { + // Create five 8-tuple objects containing prime numbers. + var prime1 = new Tuple>(2, 3, 5, 7, 11, 13, 17, + new Tuple(19)); + var prime2 = new Tuple>(23, 29, 31, 37, 41, 43, 47, + new Tuple(55)); + var prime3 = new Tuple>(3, 2, 5, 7, 11, 13, 17, + new Tuple(19)); + var prime4 = new Tuple>(2, 3, 5, 7, 11, 13, 17, + new Tuple(19, 23)); + var prime5 = new Tuple>(2, 3, 5, 7, 11, 13, 17, + new Tuple(19)); + Console.WriteLine($"{prime1} = {prime2} : {prime1.Equals(prime2)}"); + Console.WriteLine($"{prime1} = {prime3} : {prime1.Equals(prime3)}"); + Console.WriteLine($"{prime1} = {prime4} : {prime1.Equals(prime4)}"); + Console.WriteLine($"{prime1} = {prime5} : {prime1.Equals(prime5)}"); + } } // The example displays the following output: // (2, 3, 5, 7, 11, 13, 17, 19) = (23, 29, 31, 37, 41, 43, 47, 55) : False // (2, 3, 5, 7, 11, 13, 17, 19) = (3, 2, 5, 7, 11, 13, 17, 19) : False // (2, 3, 5, 7, 11, 13, 17, 19) = (2, 3, 5, 7, 11, 13, 17, 19, 23) : False // (2, 3, 5, 7, 11, 13, 17, 19) = (2, 3, 5, 7, 11, 13, 17, 19) : True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs index 7c709f3213f..7828b98e0e5 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs @@ -6,15 +6,15 @@ class Example static void Main(string[] args) { Tuple from1980 = Tuple.Create(1203339, 1027974, 951270); - var from1910 = new Tuple> + var from1910 = new Tuple> (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980); var population = new Tuple>> + Tuple>> ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910); - Console.WriteLine("Population of {0}", population.Item1); + Console.WriteLine($"Population of {population.Item1}"); Console.WriteLine(); - Console.WriteLine("{0,5} {1,14} {2,10}", "Year", "Population", "Change"); + Console.WriteLine($"{"Year",5} {"Population",14} {"Change",10}"); int year = population.Item2; ShowPopulation(year, population.Item3); @@ -48,16 +48,9 @@ static void Main(string[] args) ShowPopulationChange(year, population.Rest.Rest.Item3, population.Rest.Rest.Item2); } - private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, - ((double)(newPopulation - oldPopulation) / oldPopulation) / 10); - } + private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}"); - private static void ShowPopulation(int year, int newPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a"); - } + private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}"); } // The example displays the following output: // @@ -78,4 +71,4 @@ private static void ShowPopulation(int year, int newPopulation) // 1980 1,203,339 -2.04 % // 1990 1,027,974 -1.46 % // 2000 951,270 -0.75 % -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs index e4f1950590e..6e28f8e8778 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs @@ -2,12 +2,12 @@ public class Class1 { - public static void Main() - { - // - var primes = new Tuple> (2, 3, 5, 7, 11, 13, 17, new Tuple(19)); - // - Console.WriteLine(primes.ToString()); - } + public static void Main() + { + // + var primes = new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19)); + // + Console.WriteLine(primes); + } } diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index d4caf4d74e8..980c072d1e5 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,35 +1,35 @@ // using System; -public class Example +public class CompareToExample1 { - public static void Main() - { - // Create array of 8-tuple objects containing prime numbers. - Tuple>[] primes = - { new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19)), - new Tuple>(23, 29, 31, 37, 41, 43, 47, new Tuple(55)), - new Tuple>(3, 2, 5, 7, 11, 13, 17, new Tuple(19)) }; - // Display 8-tuples in unsorted order. - foreach (var prime in primes) - Console.WriteLine(prime.ToString()); - Console.WriteLine(); - - // Sort the array and display its 8-tuples. - Array.Sort(primes); - foreach (var prime in primes) - Console.WriteLine(prime.ToString()); - } + public static void Run() + { + // Create array of 8-tuple objects containing prime numbers. + Tuple>[] primes = + [ new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19)), + new Tuple>(23, 29, 31, 37, 41, 43, 47, new Tuple(55)), + new Tuple>(3, 2, 5, 7, 11, 13, 17, new Tuple(19)) ]; + // Display 8-tuples in unsorted order. + foreach (var prime in primes) + Console.WriteLine(prime); + Console.WriteLine(); + + // Sort the array and display its 8-tuples. + Array.Sort(primes); + foreach (var prime in primes) + Console.WriteLine(prime); + } } // The example displays the following output: // (2, 3, 5, 7, 11, 13, 17, 19) // (23, 29, 31, 37, 41, 43, 47, 55) // (3, 2, 5, 7, 11, 13, 17, 19) -// +// // (2, 3, 5, 7, 11, 13, 17, 19) // (3, 2, 5, 7, 11, 13, 17, 19) // (23, 29, 31, 37, 41, 43, 47, 55) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index e9ff5e13cea..436587ab05c 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,85 +5,76 @@ public class PopulationComparer : IComparer { - private int itemPosition; - private int multiplier = -1; + private int itemPosition; + private int multiplier = -1; - public PopulationComparer(int component) : this(component, true) - { } + public PopulationComparer(int component) : this(component, true) + { } - public PopulationComparer(int component, bool descending) - { - if (!descending) multiplier = 1; + public PopulationComparer(int component, bool descending) + { + if (!descending) multiplier = 1; - if (component <= 0 || component > 8) - throw new ArgumentException("The component argument is out of range."); + if (component <= 0 || component > 8) + throw new ArgumentException("The component argument is out of range."); - itemPosition = component; - } + itemPosition = component; + } - public int Compare(object x, object y) - { - Tuple> tX = x as Tuple>; - if (tX == null) - return 0; + public int Compare(object x, object y) + { + Tuple> tX = x as Tuple>; + if (tX == null) + return 0; - Tuple> tY = y as Tuple>; - switch (itemPosition) - { - case 1: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - case 2: - return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier; - case 3: - return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier; - case 4: - return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier; - case 5: - return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier; - case 6: - return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier; - case 7: - return Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier; - case 8: - return Comparer.Default.Compare(tX.Rest.Item1, tY.Rest.Item1) * multiplier; - default: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - } - } + Tuple> tY = y as Tuple>; + return itemPosition switch + { + 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier, + 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier, + 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier, + 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier, + 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier, + 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier, + 7 => Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier, + 8 => Comparer.Default.Compare(tX.Rest.Item1, tY.Rest.Item1) * multiplier, + _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier + }; + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - // Create array of octuples with population data for three U.S. - // cities, 1940-2000. - Tuple>[] cities = - { Tuple.Create("Los Angeles", 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), - Tuple.Create("New York", 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("Chicago", 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016), - Tuple.Create("Detroit", 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) }; - // Display array in unsorted order. - Console.WriteLine("In unsorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); - - Array.Sort(cities, new PopulationComparer(2)); - - // Display array in sorted order. - Console.WriteLine("Sorted by population in 1950:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); - - Array.Sort(cities, new PopulationComparer(8)); - - // Display array in sorted order. - Console.WriteLine("Sorted by population in 2000:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - } + public static void Run() + { + // Create array of octuples with population data for three U.S. + // cities, 1940-2000. + Tuple>[] cities = + [ Tuple.Create("Los Angeles", 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), + Tuple.Create("New York", 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), + Tuple.Create("Chicago", 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016), + Tuple.Create("Detroit", 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) ]; + // Display array in unsorted order. + Console.WriteLine("In unsorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); + + Array.Sort(cities, new PopulationComparer(2)); + + // Display array in sorted order. + Console.WriteLine("Sorted by population in 1950:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); + + Array.Sort(cities, new PopulationComparer(8)); + + // Display array in sorted order. + Console.WriteLine("Sorted by population in 2000:"); + foreach (var city in cities) + Console.WriteLine(city); + } } // The example displays the following output: // In unsorted order: @@ -91,16 +82,16 @@ public static void Main() // (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) // (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) -// +// // Sorted by population in 1950: // (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) // (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) // (Los Angeles, 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) -// +// // Sorted by population in 2000: // (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Los Angeles, 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) // (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) // (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs index 00ba6e5cf63..d16e813e7ae 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs @@ -6,27 +6,20 @@ class Example static void Main(string[] args) { Tuple from1980 = Tuple.Create(1203339, 1027974, 951270); - var from1910 = new Tuple> + var from1910 = new Tuple> (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980); var population = new Tuple>> + Tuple>> ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910); Console.WriteLine(population.ToString()); } - private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, - ((double)(newPopulation - oldPopulation) / oldPopulation) / 10); - } + private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}"); - private static void ShowPopulation(int year, int newPopulation) - { - Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a"); - } + private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}"); } // The example displays the following output: -// (Detroit, 1860, 45619, 79577, 116340, 205876, 285704, 465766, 993078, +// (Detroit, 1860, 45619, 79577, 116340, 205876, 285704, 465766, 993078, // 1568622, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) // diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs new file mode 100644 index 00000000000..76c3e934c0b --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsExample1.Run(); +EqualsExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs index cf24490a8d4..183e82cfabb 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs @@ -1,38 +1,37 @@ // using System; -public class Example +public class EqualsExample1 { - public static void Main() - { - // Get population data for New York City and Los Angeles, 1960-2000. - Tuple[] urbanPopulations = - { Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), + public static void Run() + { + // Get population data for New York City and Los Angeles, 1960-2000. + Tuple[] urbanPopulations = + [ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), Tuple.Create("New York City", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) }; - // Compare each tuple with every other tuple for equality. - for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++) - { - var urbanPopulation = urbanPopulations[ctr]; - Console.WriteLine(urbanPopulation.ToString() + " = "); - for (int innerCtr = ctr +1; innerCtr <= urbanPopulations.Length - 1; innerCtr++) - Console.WriteLine(" {0}: {1}", urbanPopulations[innerCtr], - urbanPopulation.Equals(urbanPopulations[innerCtr])); - Console.WriteLine(); - } - } + Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) ]; + // Compare each tuple with every other tuple for equality. + for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++) + { + var urbanPopulation = urbanPopulations[ctr]; + Console.WriteLine(urbanPopulation + " = "); + for (int innerCtr = ctr + 1; innerCtr <= urbanPopulations.Length - 1; innerCtr++) + Console.WriteLine($" {urbanPopulations[innerCtr]}: {urbanPopulation.Equals(urbanPopulations[innerCtr])}"); + Console.WriteLine(); + } + } } // The example displays the following output: // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) = // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820): False // (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): True -// +// // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) = // (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False -// +// // (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) = // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs index 9bacff3b868..64e4aa75c97 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs @@ -4,61 +4,58 @@ public class RateComparer : IEqualityComparer { - private int argument = 0; + private int argument = 0; - public new bool Equals(object x, object y) - { - argument++; - if (argument == 1) return true; + public new bool Equals(object x, object y) + { + argument++; + if (argument == 1) return true; - double fx, fy; - if (x is Double || x is Single) - { - fx = (double) x; - fy = (double) y; + double fx, fy; + if (x is double || x is float) + { + fx = (double)x; + fy = (double)y; return Math.Round(fx * 1000).Equals(Math.Round(fy * 1000)); - } - else - { - return x.Equals(y); - } - } + } + else + { + return x.Equals(y); + } + } - public int GetHashCode(object obj) - { - if (obj is Single || obj is Double) - return Math.Round(((double) obj) * 1000).GetHashCode(); - else - return obj.GetHashCode(); - } + public int GetHashCode(object obj) + { + if (obj is float || obj is double) + return Math.Round(((double)obj) * 1000).GetHashCode(); + else + return obj.GetHashCode(); + } } -public class Example +public class EqualsExample2 { - public static void Main() - { - var rate1 = Tuple.Create("New York", -.013934, .014505, - -.1042733, .0354833, .093644, .0290792); - var rate2 = Tuple.Create("Unknown City", -.013934, .014505, - -.1042733, .0354833, .093644, .0290792); - var rate3 = Tuple.Create("Unknown City", -.013934, .014505, - -.1042733, .0354833, .093644, .029079); - var rate4 = Tuple.Create("San Francisco", -.0451934, -.0332858, - -.0512803, .0662544, .0728964, .0491912); - IStructuralEquatable eq = rate1; - // Compare first tuple with remaining two tuples. - Console.WriteLine("{0} = ", rate1.ToString()); - Console.WriteLine(" {0} : {1}", rate2, - eq.Equals(rate2, new RateComparer())); - Console.WriteLine(" {0} : {1}", rate3, - eq.Equals(rate3, new RateComparer())); - Console.WriteLine(" {0} : {1}", rate4, - eq.Equals(rate4, new RateComparer())); - } + public static void Run() + { + var rate1 = Tuple.Create("New York", -.013934, .014505, + -.1042733, .0354833, .093644, .0290792); + var rate2 = Tuple.Create("Unknown City", -.013934, .014505, + -.1042733, .0354833, .093644, .0290792); + var rate3 = Tuple.Create("Unknown City", -.013934, .014505, + -.1042733, .0354833, .093644, .029079); + var rate4 = Tuple.Create("San Francisco", -.0451934, -.0332858, + -.0512803, .0662544, .0728964, .0491912); + IStructuralEquatable eq = rate1; + // Compare first tuple with remaining two tuples. + Console.WriteLine($"{rate1} = "); + Console.WriteLine($" {rate2} : {eq.Equals(rate2, new RateComparer())}"); + Console.WriteLine($" {rate3} : {eq.Equals(rate3, new RateComparer())}"); + Console.WriteLine($" {rate4} : {eq.Equals(rate4, new RateComparer())}"); + } } // The example displays the following output: // (New York, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) = // (Unknown City, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) : True // (Unknown City, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.029079) : True // (San Francisco, -0.0451934, -0.0332858, -0.0512803, 0.0662544, 0.0728964, 0.0491912) : False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs index e9ec3039ced..6e957c5fab3 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs @@ -1,31 +1,27 @@ // using System; -using System.Text.RegularExpressions; + public class Class1 { - public static void Main() - { - // Create tuples containing population data for New York, Chicago, - // and Los Angeles, 1960-2000. - Tuple[] cities = - { Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), + public static void Main() + { + // Create tuples containing population data for New York, Chicago, + // and Los Angeles, 1960-2000. + Tuple[] cities = + [ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), - Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) }; + Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ]; - // Display tuple data in table. - string header = "Population in"; - Console.WriteLine("{0,-12} {1,66}", - "City", new String('-',(66-header.Length)/2) + header + - new String('-', (66-header.Length)/2)); - Console.WriteLine("{0,24}{1,11}{2,11}{3,11}{4,11}{5,11}\n", - "1950", "1960", "1970", "1980", "1990", "2000"); + // Display tuple data in table. + string header = "Population in"; + Console.WriteLine($"{"City",-12} {new string('-', (66 - header.Length) / 2) + header + + new string('-', (66 - header.Length) / 2),66}"); + Console.WriteLine($"{"1950",24}{"1960",11}{"1970",11}{"1980",11}{"1990",11}{"2000",11}\n"); - foreach (var city in cities) - Console.WriteLine("{0,-12} {1,11:N0}{2,11:N0}{3,11:N0}{4,11:N0}{5,11:N0}{6,11:N0}", - city.Item1, city.Item2, city.Item3, city.Item4, - city.Item5, city.Item6, city.Item7); - } + foreach (var city in cities) + Console.WriteLine($"{city.Item1,-12} {city.Item2,11:N0}{city.Item3,11:N0}{city.Item4,11:N0}{city.Item5,11:N0}{city.Item6,11:N0}{city.Item7,11:N0}"); + } } // The example displays the following output: // City --------------------------Population in-------------------------- @@ -34,4 +30,4 @@ public static void Main() // New York 7,891,957 7,781,984 7,894,862 7,071,639 7,322,564 8,008,278 // Los Angeles 1,970,358 2,479,015 2,816,061 2,966,850 3,485,398 3,694,820 // Chicago 3,620,962 3,550,904 3,366,957 3,005,072 2,783,726 2,896,016 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs index 4e81449329c..9f206853fc2 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs @@ -3,41 +3,41 @@ public class Example { - public static void Main() - { - // Get population data for New York City, 1950-2000. - var population = Tuple.Create("New York", 7891957, 7781984, - 7894862, 7071639, 7322564, 8008278); - var rate = ComputePopulationChange(population); - // Display results. - Console.WriteLine("Population Change, {0}, 1950-2000\n", population.Item1); - Console.WriteLine("Year {0,10} {1,9}", "Population", "Annual Rate"); - Console.WriteLine("1950 {0,10:N0} {1,11}", population.Item2, "NA"); - Console.WriteLine("1960 {0,10:N0} {1,11:P2}", population.Item3, rate.Item2/10); - Console.WriteLine("1970 {0,10:N0} {1,11:P2}", population.Item4, rate.Item3/10); - Console.WriteLine("1980 {0,10:N0} {1,11:P2}", population.Item5, rate.Item4/10); - Console.WriteLine("1990 {0,10:N0} {1,11:P2}", population.Item6, rate.Item5/10); - Console.WriteLine("2000 {0,10:N0} {1,11:P2}", population.Item7, rate.Item6/10); - Console.WriteLine("1950-2000 {0,10:N0} {1,11:P2}", "", rate.Item7/50); - } + public static void Main() + { + // Get population data for New York City, 1950-2000. + var population = Tuple.Create("New York", 7891957, 7781984, + 7894862, 7071639, 7322564, 8008278); + var rate = ComputePopulationChange(population); + // Display results. + Console.WriteLine($"Population Change, {population.Item1}, 1950-2000\n"); + Console.WriteLine($"Year {"Population",10} {"Annual Rate",9}"); + Console.WriteLine($"1950 {population.Item2,10:N0} {"NA",11}"); + Console.WriteLine($"1960 {population.Item3,10:N0} {rate.Item2 / 10,11:P2}"); + Console.WriteLine($"1970 {population.Item4,10:N0} {rate.Item3 / 10,11:P2}"); + Console.WriteLine($"1980 {population.Item5,10:N0} {rate.Item4 / 10,11:P2}"); + Console.WriteLine($"1990 {population.Item6,10:N0} {rate.Item5 / 10,11:P2}"); + Console.WriteLine($"2000 {population.Item7,10:N0} {rate.Item6 / 10,11:P2}"); + Console.WriteLine($"1950-2000 {"",10:N0} {rate.Item7 / 50,11:P2}"); + } - private static Tuple - ComputePopulationChange( - Tuple data) - { - var rate = Tuple.Create(data.Item1, - (double)(data.Item3 - data.Item2)/data.Item2, - (double)(data.Item4 - data.Item3)/data.Item3, - (double)(data.Item5 - data.Item4)/data.Item4, - (double)(data.Item6 - data.Item5)/data.Item5, - (double)(data.Item7 - data.Item6)/data.Item6, - (double)(data.Item7 - data.Item2)/data.Item2 ); - return rate; - } + private static Tuple + ComputePopulationChange( + Tuple data) + { + var rate = Tuple.Create(data.Item1, + (double)(data.Item3 - data.Item2) / data.Item2, + (double)(data.Item4 - data.Item3) / data.Item3, + (double)(data.Item5 - data.Item4) / data.Item4, + (double)(data.Item6 - data.Item5) / data.Item5, + (double)(data.Item7 - data.Item6) / data.Item6, + (double)(data.Item7 - data.Item2) / data.Item2); + return rate; + } } // The example displays the following output: // Population Change, New York, 1950-2000 -// +// // Year Population Annual Rate // 1950 7,891,957 NA // 1960 7,781,984 -0.14 % @@ -46,4 +46,4 @@ private static Tuple // 1990 7,322,564 0.35 % // 2000 8,008,278 0.94 % // 1950-2000 0.03 % -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index 231499e88ac..c0fd73593c4 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,40 +1,40 @@ // using System; -public class Example +public class CompareToExample1 { - public static void Main() - { - // Create array of sextuple with population data for three U.S. - // cities, 1950-2000. - Tuple[] cities = - { Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), - Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) }; - - // Display array in unsorted order. - Console.WriteLine("In unsorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); + public static void Run() + { + // Create array of sextuple with population data for three U.S. + // cities, 1950-2000. + Tuple[] cities = + [ Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), + Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), + Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ]; - Console.WriteLine(); - - Array.Sort(cities); - - // Display array in sorted order. - Console.WriteLine("In sorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - } + // Display array in unsorted order. + Console.WriteLine("In unsorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + + Console.WriteLine(); + + Array.Sort(cities); + + // Display array in sorted order. + Console.WriteLine("In sorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + } } // The example displays the following output: // In unsorted order: // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) -// +// // In sorted order: // (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 3c9c896baf8..00dd33ca788 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,99 +5,91 @@ public class PopulationComparer : IComparer { - private int itemPosition; - private int multiplier = -1; + private int itemPosition; + private int multiplier = -1; - public PopulationComparer(int component) : this(component, true) - { } + public PopulationComparer(int component) : this(component, true) + { } - public PopulationComparer(int component, bool descending) - { - if (!descending) multiplier = 1; + public PopulationComparer(int component, bool descending) + { + if (!descending) multiplier = 1; - if (component <= 0 || component > 7) - throw new ArgumentException("The component argument is out of range."); + if (component <= 0 || component > 7) + throw new ArgumentException("The component argument is out of range."); - itemPosition = component; - } + itemPosition = component; + } - public int Compare(object x, object y) - { - Tuple tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - Tuple tY = y as Tuple; - switch (itemPosition) - { - case 1: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - case 2: - return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier; - case 3: - return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier; - case 4: - return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier; - case 5: - return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier; - case 6: - return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier; - case 7: - return Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier; - default: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - } - } - } + public int Compare(object x, object y) + { + Tuple tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + Tuple tY = y as Tuple; + return itemPosition switch + { + 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier, + 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier, + 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier, + 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier, + 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier, + 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier, + 7 => Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier, + _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier + }; + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - // Create array of sextuple with population data for three U.S. - // cities, 1960-2000. - Tuple[] cities = - { Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), + public static void Run() + { + // Create array of sextuple with population data for three U.S. + // cities, 1960-2000. + Tuple[] cities = + [ Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820), Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) }; + Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ]; - // Display array in unsorted order. - Console.WriteLine("In unsorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); + // Display array in unsorted order. + Console.WriteLine("In unsorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); - Array.Sort(cities, new PopulationComparer(3)); + Array.Sort(cities, new PopulationComparer(3)); - // Display array in sorted order. - Console.WriteLine("Sorted by population in 1960:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); + // Display array in sorted order. + Console.WriteLine("Sorted by population in 1960:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); - Array.Sort(cities, new PopulationComparer(6)); + Array.Sort(cities, new PopulationComparer(6)); - // Display array in sorted order. - Console.WriteLine("Sorted by population in 1990:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - } + // Display array in sorted order. + Console.WriteLine("Sorted by population in 1990:"); + foreach (var city in cities) + Console.WriteLine(city); + } } // The example displays the following output: // In unsorted order: // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) -// +// // Sorted by population in 1960: // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) -// +// // Sorted by population in 1990: // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) // (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs index 82c8f897b7e..6d5a9ad88cc 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs @@ -3,13 +3,13 @@ public class Example { - public static void Main() - { - // Get population data for New York City, 1960-2000. - var population = Tuple.Create("New York", 7891957, 7781984, - 7894862, 7071639, 7322564, 8008278); - Console.WriteLine(population.ToString()); - } + public static void Main() + { + // Get population data for New York City, 1960-2000. + var population = Tuple.Create("New York", 7891957, 7781984, + 7894862, 7071639, 7322564, 8008278); + Console.WriteLine(population.ToString()); + } } // The example displays the following output: // (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs new file mode 100644 index 00000000000..76c3e934c0b --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsExample1.Run(); +EqualsExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs index 38c47c0953b..14b70dcd1f5 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs @@ -1,38 +1,37 @@ // using System; -public class Example +public class EqualsExample1 { - public static void Main() - { - // Get population data for New York City and Los Angeles, 1960-2000. - Tuple[] urbanPopulations = - { Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), + public static void Run() + { + // Get population data for New York City and Los Angeles, 1960-2000. + Tuple[] urbanPopulations = + [ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), Tuple.Create("New York City", 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278) }; - // Compare each tuple with every other tuple for equality. - for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++) - { - var urbanPopulation = urbanPopulations[ctr]; - Console.WriteLine(urbanPopulation.ToString() + " = "); - for (int innerCtr = ctr +1; innerCtr <= urbanPopulations.Length - 1; innerCtr++) - Console.WriteLine(" {0}: {1}", urbanPopulations[innerCtr], - urbanPopulation.Equals(urbanPopulations[innerCtr])); - Console.WriteLine(); - } - } + Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278) ]; + // Compare each tuple with every other tuple for equality. + for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++) + { + var urbanPopulation = urbanPopulations[ctr]; + Console.WriteLine(urbanPopulation + " = "); + for (int innerCtr = ctr + 1; innerCtr <= urbanPopulations.Length - 1; innerCtr++) + Console.WriteLine($" {urbanPopulations[innerCtr]}: {urbanPopulation.Equals(urbanPopulations[innerCtr])}"); + Console.WriteLine(); + } + } } // The example displays the following output: // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) = // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820): False // (New York City, 7781984, 7894862, 7071639, 7322564, 8008278): False // (New York, 7781984, 7894862, 7071639, 7322564, 8008278): True -// +// // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) = // (New York City, 7781984, 7894862, 7071639, 7322564, 8008278): False // (New York, 7781984, 7894862, 7071639, 7322564, 8008278): False -// +// // (New York City, 7781984, 7894862, 7071639, 7322564, 8008278) = // (New York, 7781984, 7894862, 7071639, 7322564, 8008278): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs index 1714585fed3..af2fec23ed5 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs @@ -4,61 +4,58 @@ public class RateComparer : IEqualityComparer { - private int argument = 0; + private int argument = 0; - public new bool Equals(object x, object y) - { - argument++; - if (argument == 1) return true; + public new bool Equals(object x, object y) + { + argument++; + if (argument == 1) return true; - double fx, fy; - if (x is Double || x is Single) - { - fx = (double) x; - fy = (double) y; + double fx, fy; + if (x is double || x is float) + { + fx = (double)x; + fy = (double)y; return Math.Round(fx * 1000).Equals(Math.Round(fy * 1000)); - } - else - { - return x.Equals(y); - } - } - - public int GetHashCode(object obj) - { - if (obj is Single || obj is Double) - return Math.Round(((double) obj) * 1000).GetHashCode(); - else - return obj.GetHashCode(); - } + } + else + { + return x.Equals(y); + } + } + + public int GetHashCode(object obj) + { + if (obj is float || obj is double) + return Math.Round(((double)obj) * 1000).GetHashCode(); + else + return obj.GetHashCode(); + } } -public class Example +public class EqualsExample2 { - public static void Main() - { - var rate1 = Tuple.Create("New York", .014505, -.1042733, - .0354833, .093644, .0290792); - var rate2 = Tuple.Create("Unknown City", .014505, -.1042733, - .0354833, .093644, .0290792); - var rate3 = Tuple.Create("Unknown City", .014505, -.1042733, - .0354833, .093644, .029079); - var rate4 = Tuple.Create("San Francisco", -.0332858, -.0512803, - .0662544, .0728964, .0491912); - IStructuralEquatable eq = rate1; - // Compare first tuple with remaining two tuples. - Console.WriteLine("{0} = ", rate1.ToString()); - Console.WriteLine(" {0} : {1}", rate2, - eq.Equals(rate2, new RateComparer())); - Console.WriteLine(" {0} : {1}", rate3, - eq.Equals(rate3, new RateComparer())); - Console.WriteLine(" {0} : {1}", rate4, - eq.Equals(rate4, new RateComparer())); - } + public static void Run() + { + var rate1 = Tuple.Create("New York", .014505, -.1042733, + .0354833, .093644, .0290792); + var rate2 = Tuple.Create("Unknown City", .014505, -.1042733, + .0354833, .093644, .0290792); + var rate3 = Tuple.Create("Unknown City", .014505, -.1042733, + .0354833, .093644, .029079); + var rate4 = Tuple.Create("San Francisco", -.0332858, -.0512803, + .0662544, .0728964, .0491912); + IStructuralEquatable eq = rate1; + // Compare first tuple with remaining two tuples. + Console.WriteLine($"{rate1} = "); + Console.WriteLine($" {rate2} : {eq.Equals(rate2, new RateComparer())}"); + Console.WriteLine($" {rate3} : {eq.Equals(rate3, new RateComparer())}"); + Console.WriteLine($" {rate4} : {eq.Equals(rate4, new RateComparer())}"); + } } // The example displays the following output: // (New York, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) = // (Unknown City, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) : True // (Unknown City, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.029079) : True // (San Francisco, -0.0332858, -0.0512803, 0.0662544, 0.0728964, 0.0491912) : False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs index 39873aa49e6..4cf8e038e53 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs @@ -1,37 +1,33 @@ // using System; -using System.Text.RegularExpressions; + public class Class1 { - public static void Main() - { - // Create tuples containing population data for New York, Chicago, - // and Los Angeles, 1960-2000. - Tuple[] cities = - { Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), + public static void Main() + { + // Create tuples containing population data for New York, Chicago, + // and Los Angeles, 1960-2000. + Tuple[] cities = + [ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), - Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) }; + Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ]; - // Display tuple data in table. - string header = "Population in"; - Console.WriteLine("{0,-12} {1,60}", - "City", new String('-',(60-header.Length)/2) + header + - new String('-', (60-header.Length)/2)); - Console.WriteLine("{0,25}{1,12}{2,12}{3,12}{4,12}\n", - "1960", "1970", "1980", "1990", "2000"); + // Display tuple data in table. + string header = "Population in"; + Console.WriteLine($"{"City",-12} {new string('-', (60 - header.Length) / 2) + header + + new string('-', (60 - header.Length) / 2),60}"); + Console.WriteLine($"{"1960",25}{"1970",12}{"1980",12}{"1990",12}{"2000",12}\n"); - foreach (var city in cities) - Console.WriteLine("{0,-12} {1,12:N0}{2,12:N0}{3,12:N0}{4,12:N0}{5,12:N0}", - city.Item1, city.Item2, city.Item3, city.Item4, - city.Item5, city.Item6); - } + foreach (var city in cities) + Console.WriteLine($"{city.Item1,-12} {city.Item2,12:N0}{city.Item3,12:N0}{city.Item4,12:N0}{city.Item5,12:N0}{city.Item6,12:N0}"); + } } // The example displays the following output: // City -----------------------Population in----------------------- // 1960 1970 1980 1990 2000 -// +// // New York 7,781,984 7,894,862 7,071,639 7,322,564 8,008,278 // Los Angeles 2,479,015 2,816,061 2,966,850 3,485,398 3,694,820 // Chicago 3,550,904 3,366,957 3,005,072 2,783,726 2,896,016 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs index 6bf08fde43e..a09e91f460a 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs @@ -3,38 +3,38 @@ public class Example { - public static void Main() - { - // Get population data for New York City, 1960-2000. - var population = - Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278); - var rate = ComputePopulationChange(population); - // Display results. - Console.WriteLine("Population Change, {0}, 1960-2000\n", population.Item1); - Console.WriteLine("Year {0,10} {1,9}", "Population", "Annual Rate"); - Console.WriteLine("1960 {0,10:N0} {1,11}", population.Item2, "NA"); - Console.WriteLine("1970 {0,10:N0} {1,11:P2}", population.Item3, rate.Item2/10); - Console.WriteLine("1980 {0,10:N0} {1,11:P2}", population.Item4, rate.Item3/10); - Console.WriteLine("1990 {0,10:N0} {1,11:P2}", population.Item5, rate.Item4/10); - Console.WriteLine("2000 {0,10:N0} {1,11:P2}", population.Item6, rate.Item5/10); - Console.WriteLine("1960-2000 {0,10:N0} {1,11:P2}", "", rate.Item6/50); - } + public static void Main() + { + // Get population data for New York City, 1960-2000. + var population = + Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278); + var rate = ComputePopulationChange(population); + // Display results. + Console.WriteLine($"Population Change, {population.Item1}, 1960-2000\n"); + Console.WriteLine($"Year {"Population",10} {"Annual Rate",9}"); + Console.WriteLine($"1960 {population.Item2,10:N0} {"NA",11}"); + Console.WriteLine($"1970 {population.Item3,10:N0} {rate.Item2 / 10,11:P2}"); + Console.WriteLine($"1980 {population.Item4,10:N0} {rate.Item3 / 10,11:P2}"); + Console.WriteLine($"1990 {population.Item5,10:N0} {rate.Item4 / 10,11:P2}"); + Console.WriteLine($"2000 {population.Item6,10:N0} {rate.Item5 / 10,11:P2}"); + Console.WriteLine($"1960-2000 {"",10:N0} {rate.Item6 / 50,11:P2}"); + } - private static Tuple ComputePopulationChange( - Tuple data) - { - var rate = Tuple.Create(data.Item1, - (double)(data.Item3 - data.Item2)/data.Item2, - (double)(data.Item4 - data.Item3)/data.Item3, - (double)(data.Item5 - data.Item4)/data.Item4, - (double)(data.Item6 - data.Item5)/data.Item5, - (double)(data.Item6 - data.Item2)/data.Item2 ); - return rate; - } + private static Tuple ComputePopulationChange( + Tuple data) + { + var rate = Tuple.Create(data.Item1, + (double)(data.Item3 - data.Item2) / data.Item2, + (double)(data.Item4 - data.Item3) / data.Item3, + (double)(data.Item5 - data.Item4) / data.Item4, + (double)(data.Item6 - data.Item5) / data.Item5, + (double)(data.Item6 - data.Item2) / data.Item2); + return rate; + } } // The example displays the following output: // Population Change, New York, 1960-2000 -// +// // Year Population Annual Rate // 1960 7,781,984 NA // 1970 7,894,862 0.15 % @@ -42,4 +42,4 @@ private static Tuple ComputePopu // 1990 7,322,564 0.35 % // 2000 8,008,278 0.94 % // 1960-2000 0.06 % -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index a52c2493602..c71795a8bdf 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,40 +1,40 @@ // using System; -public class Example +public class CompareToExample1 { - public static void Main() - { - // Create array of sextuple with population data for three U.S. - // cities, 1960-2000. - Tuple[] cities = - { Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), - Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) }; - - // Display array in unsorted order. - Console.WriteLine("In unsorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); + public static void Run() + { + // Create array of sextuple with population data for three U.S. + // cities, 1960-2000. + Tuple[] cities = + [ Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), + Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), + Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ]; - Console.WriteLine(); - - Array.Sort(cities); - - // Display array in sorted order. - Console.WriteLine("In sorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - } + // Display array in unsorted order. + Console.WriteLine("In unsorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + + Console.WriteLine(); + + Array.Sort(cities); + + // Display array in sorted order. + Console.WriteLine("In sorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + } } // The example displays the following output: // In unsorted order: // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016) -// +// // In sorted order: // (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016) // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 8bd3fa29ccf..6808606184a 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,97 +5,90 @@ public class PopulationComparer : IComparer { - private int itemPosition; - private int multiplier = -1; + private int itemPosition; + private int multiplier = -1; - public PopulationComparer(int component) : this(component, true) - { } + public PopulationComparer(int component) : this(component, true) + { } - public PopulationComparer(int component, bool descending) - { - if (!descending) multiplier = 1; + public PopulationComparer(int component, bool descending) + { + if (!descending) multiplier = 1; - if (component <= 0 || component > 6) - throw new ArgumentException("The component argument is out of range."); + if (component <= 0 || component > 6) + throw new ArgumentException("The component argument is out of range."); - itemPosition = component; - } + itemPosition = component; + } - public int Compare(object x, object y) - { - var tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - var tY = y as Tuple; - switch (itemPosition) - { - case 1: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - case 2: - return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier; - case 3: - return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier; - case 4: - return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier; - case 5: - return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier; - case 6: - return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier; - default: - return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier; - } - } - } + public int Compare(object x, object y) + { + var tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + var tY = y as Tuple; + return itemPosition switch + { + 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier, + 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier, + 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier, + 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier, + 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier, + 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier, + _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier + }; + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - // Create array of sextuple with population data for three U.S. - // cities, 1960-2000. - Tuple[] cities = - { Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), + public static void Run() + { + // Create array of sextuple with population data for three U.S. + // cities, 1960-2000. + Tuple[] cities = + [ Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820), Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278), - Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) }; + Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ]; - // Display array in unsorted order. - Console.WriteLine("In unsorted order:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); + // Display array in unsorted order. + Console.WriteLine("In unsorted order:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); - Array.Sort(cities, new PopulationComparer(3)); + Array.Sort(cities, new PopulationComparer(3)); - // Display array in sorted order. - Console.WriteLine("Sorted by population in 1970:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - Console.WriteLine(); + // Display array in sorted order. + Console.WriteLine("Sorted by population in 1970:"); + foreach (var city in cities) + Console.WriteLine(city); + Console.WriteLine(); - Array.Sort(cities, new PopulationComparer(6)); + Array.Sort(cities, new PopulationComparer(6)); - // Display array in sorted order. - Console.WriteLine("Sorted by population in 2000:"); - foreach (var city in cities) - Console.WriteLine(city.ToString()); - } + // Display array in sorted order. + Console.WriteLine("Sorted by population in 2000:"); + foreach (var city in cities) + Console.WriteLine(city); + } } // The example displays the following output: // In unsorted order: // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016) -// +// // Sorted by population in 1970: // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) // (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016) // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) -// +// // Sorted by population in 2000: // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) // (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs index 4e4d4248140..d8f9ed2e95b 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs @@ -3,13 +3,13 @@ public class Example { - public static void Main() - { - // Get population data for New York City, 1960-2000. - var population = Tuple.Create("New York", 7781984, 7894862, - 7071639, 7322564, 8008278); - Console.WriteLine(population.ToString()); - } + public static void Main() + { + // Get population data for New York City, 1960-2000. + var population = Tuple.Create("New York", 7781984, 7894862, + 7071639, 7322564, 8008278); + Console.WriteLine(population.ToString()); + } } // The example displays the following output: // (New York, 7781984, 7894862, 7071639, 7322564, 8008278) diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs index cb0a1aa1032..210a0263836 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs @@ -3,25 +3,24 @@ public class Class1 { - public static void Main() - { - Tuple[] temperatureInfos = - { Tuple.Create(2, 97.9, 97.8, 98.0, 98.2), - Tuple.Create(1, 98.6, 98.8, 98.8, 99.0), + public static void Main() + { + Tuple[] temperatureInfos = + [ Tuple.Create(2, 97.9, 97.8, 98.0, 98.2), + Tuple.Create(1, 98.6, 98.8, 98.8, 99.0), Tuple.Create(2, 98.6, 98.6, 98.6, 98.4), Tuple.Create(1, 98.4, 98.6, 99.0, 99.2), Tuple.Create(2, 98.6, 98.6, 98.6, 98.4), - Tuple.Create(1, 98.6, 98.8, 98.8, 99.0) }; - // Compare each item with every other item for equality. - for (int ctr = 0; ctr < temperatureInfos.Length; ctr++) - { - var temperatureInfo = temperatureInfos[ctr]; - for (int ctr2 = ctr + 1; ctr2 < temperatureInfos.Length; ctr2++) - Console.WriteLine("{0} = {1}: {2}", temperatureInfo, temperatureInfos[ctr2], - temperatureInfo.Equals(temperatureInfos[ctr2])); - Console.WriteLine(); - } - } + Tuple.Create(1, 98.6, 98.8, 98.8, 99.0) ]; + // Compare each item with every other item for equality. + for (int ctr = 0; ctr < temperatureInfos.Length; ctr++) + { + var temperatureInfo = temperatureInfos[ctr]; + for (int ctr2 = ctr + 1; ctr2 < temperatureInfos.Length; ctr2++) + Console.WriteLine($"{temperatureInfo} = {temperatureInfos[ctr2]}: {temperatureInfo.Equals(temperatureInfos[ctr2])}"); + Console.WriteLine(); + } + } } // The example displays the following output: // (2, 97.9, 97.8, 98, 98.2) = (1, 98.6, 98.8, 98.8, 99): False @@ -29,18 +28,18 @@ public static void Main() // (2, 97.9, 97.8, 98, 98.2) = (1, 98.4, 98.6, 99, 99.2): False // (2, 97.9, 97.8, 98, 98.2) = (2, 98.6, 98.6, 98.6, 98.4): False // (2, 97.9, 97.8, 98, 98.2) = (1, 98.6, 98.8, 98.8, 99): False -// +// // (1, 98.6, 98.8, 98.8, 99) = (2, 98.6, 98.6, 98.6, 98.4): False // (1, 98.6, 98.8, 98.8, 99) = (1, 98.4, 98.6, 99, 99.2): False // (1, 98.6, 98.8, 98.8, 99) = (2, 98.6, 98.6, 98.6, 98.4): False // (1, 98.6, 98.8, 98.8, 99) = (1, 98.6, 98.8, 98.8, 99): True -// +// // (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.4, 98.6, 99, 99.2): False // (2, 98.6, 98.6, 98.6, 98.4) = (2, 98.6, 98.6, 98.6, 98.4): True // (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.6, 98.8, 98.8, 99): False -// +// // (1, 98.4, 98.6, 99, 99.2) = (2, 98.6, 98.6, 98.6, 98.4): False // (1, 98.4, 98.6, 99, 99.2) = (1, 98.6, 98.8, 98.8, 99): False -// +// // (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.6, 98.8, 98.8, 99): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs index 210eae5e9b4..99b8ce06a56 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs @@ -4,63 +4,59 @@ public class DoubleComparer : IEqualityComparer { - private double difference; - private int argument = 0; - - public DoubleComparer(double difference) - { - this.difference = difference; - } - - new public bool Equals(object x, object y) - { - argument += 1; - - // Return true for Item1. - if (argument == 1) return true; + private double difference; + private int argument = 0; - double d1 = (double) x; - double d2 = (double) y; + public DoubleComparer(double difference) => this.difference = difference; - if (d1 - d2 < d1 * difference) - return true; - else - return false; - } - - public int GetHashCode(object obj) - { - if (obj is T1) - return ((T1) obj).GetHashCode(); - else if (obj is T2) - return ((T2) obj).GetHashCode(); - else if (obj is T3) - return ((T3) obj).GetHashCode(); - else if (obj is T4) - return ((T4) obj).GetHashCode(); - else - return ((T5) obj).GetHashCode(); - } + new public bool Equals(object x, object y) + { + argument += 1; + + // Return true for Item1. + if (argument == 1) return true; + + double d1 = (double)x; + double d2 = (double)y; + + if (d1 - d2 < d1 * difference) + return true; + else + return false; + } + + public int GetHashCode(object obj) + { + if (obj is T1) + return ((T1)obj).GetHashCode(); + else if (obj is T2) + return ((T2)obj).GetHashCode(); + else if (obj is T3) + return ((T3)obj).GetHashCode(); + else if (obj is T4) + return ((T4)obj).GetHashCode(); + else + return ((T5)obj).GetHashCode(); + } } public class Example { - public static void Main() - { - var value1 = GetValues(1); - var value2 = GetValues(2); - IStructuralEquatable iValue1 = value1; - Console.WriteLine("{0} =\n{1} :\n{2}", value1, value2, - iValue1.Equals(value2, - new DoubleComparer(.01))); - } + public static void Main() + { + var value1 = GetValues(1); + var value2 = GetValues(2); + IStructuralEquatable iValue1 = value1; + Console.WriteLine($"{value1} =\n{value2} :\n{iValue1.Equals(value2, + new DoubleComparer(.01))}"); + } - private static Tuple GetValues(int ctr) - { - // Generate four random numbers between 0 and 1 - Random rnd = new Random((int)DateTime.Now.Ticks >> 32 >> ctr); - return Tuple.Create(ctr, rnd.NextDouble(), rnd.NextDouble(), - rnd.NextDouble(), rnd.NextDouble()); - } + private static Tuple GetValues(int ctr) + { + // Generate four random numbers between 0 and 1 + Random rnd = new((int)DateTime.Now.Ticks >> 32 >> ctr); + return Tuple.Create(ctr, rnd.NextDouble(), rnd.NextDouble(), + rnd.NextDouble(), rnd.NextDouble()); + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs index b8c1131213d..5916cb1bdb4 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs @@ -3,28 +3,24 @@ public class Example { - public static void Main() - { - // Define array of tuples reflecting population change by state, 1990-2000. - Tuple[] statesData = - { Tuple.Create("California", 29760021, 33871648, 4111627, 13.8), - Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6), - Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) }; + public static void Main() + { + // Define array of tuples reflecting population change by state, 1990-2000. + Tuple[] statesData = + [ Tuple.Create("California", 29760021, 33871648, 4111627, 13.8), + Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6), + Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) ]; - // Display the items of each tuple - Console.WriteLine("{0,-12}{1,18}{2,18}{3,15}{4,12}\n", "State", - "Population 1990", "Population 2000", "Change", - "% Change"); - foreach(Tuple stateData in statesData) - Console.WriteLine("{0,-12}{1,18:N0}{2,18:N0}{3,15:N0}{4,12:P1}", - stateData.Item1, stateData.Item2, - stateData.Item3, stateData.Item4, stateData.Item5/100); - } + // Display the items of each tuple + Console.WriteLine($"{"State",-12}{"Population 1990",18}{"Population 2000",18}{"Change",15}{"% Change",12}\n"); + foreach (Tuple stateData in statesData) + Console.WriteLine($"{stateData.Item1,-12}{stateData.Item2,18:N0}{stateData.Item3,18:N0}{stateData.Item4,15:N0}{stateData.Item5 / 100,12:P1}"); + } } // The example displays the following output: // State Population 1990 Population 2000 Change % Change -// +// // California 29,760,021 33,871,648 4,111,627 13.8 % // Illinois 11,430,602 12,419,293 988,691 8.6 % // Washington 4,866,692 5,894,121 1,027,429 21.1 % -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs index f90ff6e9b47..71931116b33 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs @@ -4,70 +4,65 @@ public class Example { - public static void Main() - { - // Organization of runningBacks 5-tuple: - // Component 1: Player name - // Component 2: Number of games played - // Component 3: Number of attempts (carries) - // Component 4: Number of yards gained - // Component 5: Number of touchdowns - Tuple[] runningBacks = - { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), - Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), - Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), - Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), - Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) }; - // Calculate statistics. - // Organization of runningStats 5-tuple: - // Component 1: Player name - // Component 2: Number of attempts per game - // Component 3: Number of yards per game - // Component 4: Number of yards per attempt - // Component 5: Number of touchdowns per attempt - Tuple[] runningStats = - ComputeStatistics(runningBacks); + public static void Main() + { + // Organization of runningBacks 5-tuple: + // Component 1: Player name + // Component 2: Number of games played + // Component 3: Number of attempts (carries) + // Component 4: Number of yards gained + // Component 5: Number of touchdowns + Tuple[] runningBacks = + [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), + Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), + Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), + Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), + Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ]; + // Calculate statistics. + // Organization of runningStats 5-tuple: + // Component 1: Player name + // Component 2: Number of attempts per game + // Component 3: Number of yards per game + // Component 4: Number of yards per attempt + // Component 5: Number of touchdowns per attempt + Tuple[] runningStats = + ComputeStatistics(runningBacks); - // Display the result. - Console.WriteLine("{0,-16} {1,5} {2,6} {3,7} {4,7} {5,7} {6,7} {7,5} {8,7}\n", - "Name", "Games", "Att", "Att/Gm", "Yards", "Yds/Gm", - "Yds/Att", "TD", "TD/Att"); - for (int ctr = 0; ctr < runningBacks.Length; ctr++) - Console.WriteLine("{0,-16} {1,5} {2,6:N0} {3,7:N1} {4,7:N0} {5,7:N1} {6,7:N2} {7,5} {8,7:N3}\n", - runningBacks[ctr].Item1, runningBacks[ctr].Item2, runningBacks[ctr].Item3, - runningStats[ctr].Item2, runningBacks[ctr].Item4, runningStats[ctr].Item3, - runningStats[ctr].Item4, runningBacks[ctr].Item5, runningStats[ctr].Item5); - } + // Display the result. + Console.WriteLine($"{"Name",-16} {"Games",5} {"Att",6} {"Att/Gm",7} {"Yards",7} {"Yds/Gm",7} {"Yds/Att",7} {"TD",5} {"TD/Att",7}\n"); + for (int ctr = 0; ctr < runningBacks.Length; ctr++) + Console.WriteLine($"{runningBacks[ctr].Item1,-16} {runningBacks[ctr].Item2,5} {runningBacks[ctr].Item3,6:N0} {runningStats[ctr].Item2,7:N1} {runningBacks[ctr].Item4,7:N0} {runningStats[ctr].Item3,7:N1} {runningStats[ctr].Item4,7:N2} {runningBacks[ctr].Item5,5} {runningStats[ctr].Item5,7:N3}\n"); + } - private static Tuple[] ComputeStatistics( - Tuple[] players) - { - Tuple result; - var list = new List>(); - - foreach (var player in players) - { - // Create result object containing player name and statistics. - result = Tuple.Create(player.Item1, - player.Item3/((double)player.Item2), - player.Item4/((double)player.Item2), - player.Item4/((double)player.Item3), - player.Item5/((double)player.Item3)); - list.Add(result); - } - return list.ToArray(); - } + private static Tuple[] ComputeStatistics( + Tuple[] players) + { + Tuple result; + List> list = []; + + foreach (var player in players) + { + // Create result object containing player name and statistics. + result = Tuple.Create(player.Item1, + player.Item3 / ((double)player.Item2), + player.Item4 / ((double)player.Item2), + player.Item4 / ((double)player.Item3), + player.Item5 / ((double)player.Item3)); + list.Add(result); + } + return list.ToArray(); + } } // The example displays the following output: // Name Games Att Att/Gm Yards Yds/Gm Yds/Att TD TD/Att -// +// // Payton, Walter 190 3,838 20.2 16,726 88.0 4.36 110 0.029 -// +// // Sanders, Barry 153 3,062 20.0 15,269 99.8 4.99 99 0.032 -// +// // Brown, Jim 118 2,359 20.0 12,312 104.3 5.22 106 0.045 -// +// // Dickerson, Eric 144 2,996 20.8 13,259 92.1 4.43 90 0.030 -// +// // Faulk, Marshall 176 2,836 16.1 12,279 69.8 4.33 100 0.035 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index 44ae3b18e8c..539d8161455 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,38 +1,38 @@ // using System; -using System.Collections.Generic; -public class Example + +public class CompareToExample1 { - public static void Main() - { - // Organization of runningBacks 5-tuple: - // Component 1: Player name - // Component 2: Number of games played - // Component 3: Number of attempts (carries) - // Component 4: Number of yards gained - // Component 5: Number of touchdowns - Tuple[] runningBacks = - { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), - Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), - Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), - Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), - Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) }; + public static void Run() + { + // Organization of runningBacks 5-tuple: + // Component 1: Player name + // Component 2: Number of games played + // Component 3: Number of attempts (carries) + // Component 4: Number of yards gained + // Component 5: Number of touchdowns + Tuple[] runningBacks = + [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), + Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), + Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), + Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), + Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ]; + + // Display the array in unsorted order. + Console.WriteLine("The values in unsorted order:"); + foreach (var runningBack in runningBacks) + Console.WriteLine(runningBack); + Console.WriteLine(); + + // Sort the array + Array.Sort(runningBacks); - // Display the array in unsorted order. - Console.WriteLine("The values in unsorted order:"); - foreach (var runningBack in runningBacks) - Console.WriteLine(runningBack.ToString()); - Console.WriteLine(); - - // Sort the array - Array.Sort(runningBacks); - - // Display the array in sorted order. - Console.WriteLine("The values in sorted order:"); - foreach (var runningBack in runningBacks) - Console.WriteLine(runningBack.ToString()); - } + // Display the array in sorted order. + Console.WriteLine("The values in sorted order:"); + foreach (var runningBack in runningBacks) + Console.WriteLine(runningBack); + } } // The example displays the following output: // The values in unsorted order: @@ -41,11 +41,11 @@ public static void Main() // (Brown, Jim, 118, 2359, 12312, 106) // (Dickerson, Eric, 144, 2996, 13259, 90) // (Faulk, Marshall, 176, 2836, 12279, 100) -// +// // The values in sorted order: // (Brown, Jim, 118, 2359, 12312, 106) // (Dickerson, Eric, 144, 2996, 13259, 90) // (Faulk, Marshall, 176, 2836, 12279, 100) // (Payton, Walter, 190, 3838, 16726, 110) // (Sanders, Barry, 153, 3062, 15269, 99) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index a1f9c1c7da2..bf0742d5aeb 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,52 +5,52 @@ public class YardsGained : IComparer { - public int Compare(object x, object y) - { - Tuple tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - Tuple tY = y as Tuple; - return -1 * Comparer.Default.Compare(tX.Item4, tY.Item4); - } - } + public int Compare(object x, object y) + { + Tuple tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + Tuple tY = y as Tuple; + return -1 * Comparer.Default.Compare(tX.Item4, tY.Item4); + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - // Organization of runningBacks 5-tuple: - // Component 1: Player name - // Component 2: Number of games played - // Component 3: Number of attempts (carries) - // Component 4: Number of yards gained - // Component 5: Number of touchdowns - Tuple[] runningBacks = - { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), - Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), - Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), - Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), - Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) }; + public static void Run() + { + // Organization of runningBacks 5-tuple: + // Component 1: Player name + // Component 2: Number of games played + // Component 3: Number of attempts (carries) + // Component 4: Number of yards gained + // Component 5: Number of touchdowns + Tuple[] runningBacks = + [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110), + Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99), + Tuple.Create("Brown, Jim", 118, 2359, 12312, 106), + Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90), + Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ]; - // Display the array in unsorted order. - Console.WriteLine("The values in unsorted order:"); - foreach (var runningBack in runningBacks) - Console.WriteLine(runningBack.ToString()); - Console.WriteLine(); - - // Sort the array - Array.Sort(runningBacks, new YardsGained()); - - // Display the array in sorted order. - Console.WriteLine("The values in sorted order:"); - foreach (var runningBack in runningBacks) - Console.WriteLine(runningBack.ToString()); - } + // Display the array in unsorted order. + Console.WriteLine("The values in unsorted order:"); + foreach (var runningBack in runningBacks) + Console.WriteLine(runningBack); + Console.WriteLine(); + + // Sort the array + Array.Sort(runningBacks, new YardsGained()); + + // Display the array in sorted order. + Console.WriteLine("The values in sorted order:"); + foreach (var runningBack in runningBacks) + Console.WriteLine(runningBack); + } } // The example displays the following output: // The values in unsorted order: @@ -59,11 +59,11 @@ public static void Main() // (Brown, Jim, 118, 2359, 12312, 106) // (Dickerson, Eric, 144, 2996, 13259, 90) // (Faulk, Marshall, 176, 2836, 12279, 100) -// +// // The values in sorted order: // (Brown, Jim, 118, 2359, 12312, 106) // (Dickerson, Eric, 144, 2996, 13259, 90) // (Faulk, Marshall, 176, 2836, 12279, 100) // (Payton, Walter, 190, 3838, 16726, 110) // (Sanders, Barry, 153, 3062, 15269, 99) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs index 5354516ce78..1aa649bc5b1 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs @@ -3,20 +3,20 @@ public class Example { - public static void Main() - { - // Define array of tuples reflecting population change by state, 1990-2000. - Tuple[] populationChanges = - { Tuple.Create("California", 29760021, 33871648, 4111627, 13.8), - Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6), - Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) }; - // Display each tuple. - foreach (var item in populationChanges) - Console.WriteLine(item.ToString()); - } + public static void Main() + { + // Define array of tuples reflecting population change by state, 1990-2000. + Tuple[] populationChanges = + [ Tuple.Create("California", 29760021, 33871648, 4111627, 13.8), + Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6), + Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) ]; + // Display each tuple. + foreach (var item in populationChanges) + Console.WriteLine(item.ToString()); + } } // The example displays the following output: // (California, 29760021, 33871648, 4111627, 13.8) // (Illinois, 11430602, 12419293, 988691, 8.6) // (Washington, 4866692, 5894121, 1027429, 21.1) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs index b7bd2128f39..ff7b5fab1a3 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs @@ -3,25 +3,24 @@ public class Class1 { - public static void Main() - { - Tuple[] temperatures = - { Tuple.Create(new DateTime(2009, 1, 16), 3.0, 5.0, 4.0), - Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0), + public static void Main() + { + Tuple[] temperatures = + [ Tuple.Create(new DateTime(2009, 1, 16), 3.0, 5.0, 4.0), + Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0), Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 10.0), Tuple.Create(new DateTime(2009, 6, 1), 23.0, 28.0, 21.0), Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0), - Tuple.Create(new DateTime(2009, 9, 6), 25.0, 30.0, 25.0) }; - // Compare each item with every other item for equality. - for (int ctr = 0; ctr < temperatures.Length; ctr++) - { - var temperatureInfo = temperatures[ctr]; - for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++) - Console.WriteLine("{0} = {1}: {2}", temperatureInfo, temperatures[ctr2], - temperatureInfo.Equals(temperatures[ctr2])); - Console.WriteLine(); - } - } + Tuple.Create(new DateTime(2009, 9, 6), 25.0, 30.0, 25.0) ]; + // Compare each item with every other item for equality. + for (int ctr = 0; ctr < temperatures.Length; ctr++) + { + var temperatureInfo = temperatures[ctr]; + for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++) + Console.WriteLine($"{temperatureInfo} = {temperatures[ctr2]}: {temperatureInfo.Equals(temperatures[ctr2])}"); + Console.WriteLine(); + } + } } // The example displays the following output: // (1/16/2009 12:00:00 AM, 3, 5, 4) = (4/22/2009 12:00:00 AM, 9, 14, 11): False @@ -29,18 +28,18 @@ public static void Main() // (1/16/2009 12:00:00 AM, 3, 5, 4) = (6/1/2009 12:00:00 AM, 23, 28, 21): False // (1/16/2009 12:00:00 AM, 3, 5, 4) = (4/22/2009 12:00:00 AM, 9, 14, 11): False // (1/16/2009 12:00:00 AM, 3, 5, 4) = (9/6/2009 12:00:00 AM, 25, 30, 25): False -// +// // (4/22/2009 12:00:00 AM, 9, 14, 11) = (4/22/2009 12:00:00 AM, 9, 14, 10): False // (4/22/2009 12:00:00 AM, 9, 14, 11) = (6/1/2009 12:00:00 AM, 23, 28, 21): False // (4/22/2009 12:00:00 AM, 9, 14, 11) = (4/22/2009 12:00:00 AM, 9, 14, 11): True // (4/22/2009 12:00:00 AM, 9, 14, 11) = (9/6/2009 12:00:00 AM, 25, 30, 25): False -// +// // (4/22/2009 12:00:00 AM, 9, 14, 10) = (6/1/2009 12:00:00 AM, 23, 28, 21): False // (4/22/2009 12:00:00 AM, 9, 14, 10) = (4/22/2009 12:00:00 AM, 9, 14, 11): False // (4/22/2009 12:00:00 AM, 9, 14, 10) = (9/6/2009 12:00:00 AM, 25, 30, 25): False -// +// // (6/1/2009 12:00:00 AM, 23, 28, 21) = (4/22/2009 12:00:00 AM, 9, 14, 11): False // (6/1/2009 12:00:00 AM, 23, 28, 21) = (9/6/2009 12:00:00 AM, 25, 30, 25): False -// +// // (4/22/2009 12:00:00 AM, 9, 14, 11) = (9/6/2009 12:00:00 AM, 25, 30, 25): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs index d660b7a65cf..96e453de0f1 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs @@ -4,56 +4,54 @@ public class Item3And4Comparer : IEqualityComparer { - private int argument = 0; - - new public bool Equals(object x, object y) - { - argument++; - - // Return true for all values of Item1, Item2. - if (argument <= 2) - return true; - else - return x.Equals(y); - } - - public int GetHashCode(object obj) - { - if (obj is T1) - return ((T1) obj).GetHashCode(); - else if (obj is T2) - return ((T2) obj).GetHashCode(); - else if (obj is T3) - return ((T3) obj).GetHashCode(); - else - return ((T4) obj).GetHashCode(); - } + private int argument = 0; + + new public bool Equals(object x, object y) + { + argument++; + + // Return true for all values of Item1, Item2. + if (argument <= 2) + return true; + else + return x.Equals(y); + } + + public int GetHashCode(object obj) + { + if (obj is T1) + return ((T1)obj).GetHashCode(); + else if (obj is T2) + return ((T2)obj).GetHashCode(); + else if (obj is T3) + return ((T3)obj).GetHashCode(); + else + return ((T4)obj).GetHashCode(); + } } public class Example { - public static void Main() - { - Tuple[] temperatures = - { Tuple.Create("New York, NY", 4, 61.0, 43.0), - Tuple.Create("Chicago, IL", 2, 34.0, 18.0), + public static void Main() + { + Tuple[] temperatures = + [ Tuple.Create("New York, NY", 4, 61.0, 43.0), + Tuple.Create("Chicago, IL", 2, 34.0, 18.0), Tuple.Create("Newark, NJ", 4, 61.0, 43.0), Tuple.Create("Boston, MA", 6, 77.0, 59.0), Tuple.Create("Detroit, MI", 9, 74.0, 53.0), - Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) }; - // Compare each item with every other item for equality. - for (int ctr = 0; ctr < temperatures.Length; ctr++) - { - IStructuralEquatable temperatureInfo = temperatures[ctr]; - for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++) - Console.WriteLine("{0} = {1}: {2}", - temperatureInfo, temperatures[ctr2], - temperatureInfo.Equals(temperatures[ctr2], - new Item3And4Comparer())); + Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) ]; + // Compare each item with every other item for equality. + for (int ctr = 0; ctr < temperatures.Length; ctr++) + { + IStructuralEquatable temperatureInfo = temperatures[ctr]; + for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++) + Console.WriteLine($"{temperatureInfo} = {temperatures[ctr2]}: {temperatureInfo.Equals(temperatures[ctr2], + new Item3And4Comparer())}"); - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output: // (New York, NY, 4, 61, 43) = (Chicago, IL, 2, 34, 18): False @@ -61,18 +59,18 @@ public static void Main() // (New York, NY, 4, 61, 43) = (Boston, MA, 6, 77, 59): False // (New York, NY, 4, 61, 43) = (Detroit, MI, 9, 74, 53): False // (New York, NY, 4, 61, 43) = (Minneapolis, MN, 8, 81, 61): False -// +// // (Chicago, IL, 2, 34, 18) = (Newark, NJ, 4, 61, 43): False // (Chicago, IL, 2, 34, 18) = (Boston, MA, 6, 77, 59): False // (Chicago, IL, 2, 34, 18) = (Detroit, MI, 9, 74, 53): False // (Chicago, IL, 2, 34, 18) = (Minneapolis, MN, 8, 81, 61): False -// +// // (Newark, NJ, 4, 61, 43) = (Boston, MA, 6, 77, 59): False // (Newark, NJ, 4, 61, 43) = (Detroit, MI, 9, 74, 53): False // (Newark, NJ, 4, 61, 43) = (Minneapolis, MN, 8, 81, 61): False -// +// // (Boston, MA, 6, 77, 59) = (Detroit, MI, 9, 74, 53): False // (Boston, MA, 6, 77, 59) = (Minneapolis, MN, 8, 81, 61): False -// +// // (Detroit, MI, 9, 74, 53) = (Minneapolis, MN, 8, 81, 61): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs index 74b42593592..c4f2a8aaab0 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs @@ -4,34 +4,30 @@ public class Example { - public static void Main() - { - Tuple[] temperatures = - { Tuple.Create("New York, NY", 4, 61.0, 43.0), - Tuple.Create("Chicago, IL", 2, 34.0, 18.0), + public static void Main() + { + Tuple[] temperatures = + [ Tuple.Create("New York, NY", 4, 61.0, 43.0), + Tuple.Create("Chicago, IL", 2, 34.0, 18.0), Tuple.Create("Newark, NJ", 4, 61.0, 43.0), Tuple.Create("Boston, MA", 6, 77.0, 59.0), Tuple.Create("Detroit, MI", 9, 74.0, 53.0), - Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) }; - // Display the array of 4-tuple objects. - Console.WriteLine("{0,41}", "Temperatures"); - Console.WriteLine("{0,-20} {1,5} {2,4} {3,4}\n", - "City", "Month", "High", "Low"); - foreach (var temperature in temperatures) - Console.WriteLine("{0,-20} {1,5} {2,4:N1} {3,4:N1}", - temperature.Item1, - DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(temperature.Item2 - 1), - temperature.Item3, temperature.Item4); - } + Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) ]; + // Display the array of 4-tuple objects. + Console.WriteLine($"{"Temperatures",41}"); + Console.WriteLine($"{"City",-20} {"Month",5} {"High",4} {"Low",4}\n"); + foreach (var temperature in temperatures) + Console.WriteLine($"{temperature.Item1,-20} {DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(temperature.Item2 - 1),5} {temperature.Item3,4:N1} {temperature.Item4,4:N1}"); + } } // The example displays the following output: // Temperatures // City Month High Low -// +// // New York, NY Mar 61.0 43.0 // Chicago, IL Jan 34.0 18.0 // Newark, NJ Mar 61.0 43.0 // Boston, MA May 77.0 59.0 // Detroit, MI Aug 74.0 53.0 // Minneapolis, MN Jul 81.0 61.0 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs index 503e29b5222..4f0eb494b13 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs @@ -4,50 +4,47 @@ public class Example { - public static void Main() - { - Tuple[] pitchers = - { Tuple.Create("McHale, Joe", 240.1m, 221, 96), - Tuple.Create("Paul, Dave", 233.1m, 231, 84), + public static void Main() + { + Tuple[] pitchers = + [ Tuple.Create("McHale, Joe", 240.1m, 221, 96), + Tuple.Create("Paul, Dave", 233.1m, 231, 84), Tuple.Create("Williams, Mike", 193.2m, 183, 86), - Tuple.Create("Blair, Jack", 168.1m, 146, 65), + Tuple.Create("Blair, Jack", 168.1m, 146, 65), Tuple.Create("Henry, Walt", 140.1m, 96, 30), Tuple.Create("Lee, Adam", 137.2m, 109, 45), - Tuple.Create("Rohr, Don", 101.0m, 110, 42) }; - Tuple[] results= ComputeStatistics(pitchers); + Tuple.Create("Rohr, Don", 101.0m, 110, 42) ]; + Tuple[] results = ComputeStatistics(pitchers); - // Display the results. - Console.WriteLine("{0,-20} {1,9} {2,11} {3,15}\n", - "Pitcher", "ERA", "Hits/Inn.", "Effectiveness"); - foreach (var result in results) - Console.WriteLine("{0,-20} {1,9:F2} {2,11:F2} {3,15:F2}", - result.Item1, result.Item2, result.Item3, result.Item4); - } + // Display the results. + Console.WriteLine($"{"Pitcher",-20} {"ERA",9} {"Hits/Inn.",11} {"Effectiveness",15}\n"); + foreach (var result in results) + Console.WriteLine($"{result.Item1,-20} {result.Item2,9:F2} {result.Item3,11:F2} {result.Item4,15:F2}"); + } - private static Tuple[] ComputeStatistics(Tuple[] pitchers) - { - var list = new List>(); - Tuple result; + private static Tuple[] ComputeStatistics(Tuple[] pitchers) + { + List> list = []; + Tuple result; - foreach (var pitcher in pitchers) - { - // Decimal portion of innings pitched represents 1/3 of an inning - double innings = (double) Math.Truncate(pitcher.Item2); - innings = innings + (((double)pitcher.Item2 - innings) * .33); - - double ERA = pitcher.Item4/innings * 9; - double hitsPerInning = pitcher.Item3/innings; - double EI = (ERA * 2 + hitsPerInning * 9)/3; - result = new Tuple - (pitcher.Item1, ERA, hitsPerInning, EI); - list.Add(result); - } - return list.ToArray(); - } + foreach (var pitcher in pitchers) + { + // Decimal portion of innings pitched represents 1/3 of an inning + double innings = (double)Math.Truncate(pitcher.Item2); + innings = innings + (((double)pitcher.Item2 - innings) * .33); + + double ERA = pitcher.Item4 / innings * 9; + double hitsPerInning = pitcher.Item3 / innings; + double EI = (ERA * 2 + hitsPerInning * 9) / 3; + result = new(pitcher.Item1, ERA, hitsPerInning, EI); + list.Add(result); + } + return list.ToArray(); + } } // The example displays the following output; // Pitcher ERA Hits/Inn. Effectiveness -// +// // McHale, Joe 3.60 0.92 5.16 // Paul, Dave 3.24 0.99 5.14 // Williams, Mike 4.01 0.95 5.52 @@ -55,4 +52,4 @@ private static Tuple[] ComputeStatistics(Tuple \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index 81c29e178a4..507cec4e02d 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,34 +1,34 @@ // using System; -using System.Collections.Generic; -public class Example + +public class CompareToExample1 { - public static void Main() - { - Tuple[] pitchers = - { Tuple.Create("McHale, Joe", 240.1m, 221, 96), - Tuple.Create("Paul, Dave", 233.1m, 231, 84), + public static void Run() + { + Tuple[] pitchers = + [ Tuple.Create("McHale, Joe", 240.1m, 221, 96), + Tuple.Create("Paul, Dave", 233.1m, 231, 84), Tuple.Create("Williams, Mike", 193.2m, 183, 86), - Tuple.Create("Blair, Jack", 168.1m, 146, 65), + Tuple.Create("Blair, Jack", 168.1m, 146, 65), Tuple.Create("Henry, Walt", 140.1m, 96, 30), Tuple.Create("Lee, Adam", 137.2m, 109, 45), - Tuple.Create("Rohr, Don", 101.0m, 110, 42) }; + Tuple.Create("Rohr, Don", 101.0m, 110, 42) ]; + + // Display the array in unsorted order. + Console.WriteLine("The values in unsorted order:"); + foreach (var pitcher in pitchers) + Console.WriteLine(pitcher); + Console.WriteLine(); + + // Sort the array + Array.Sort(pitchers); - // Display the array in unsorted order. - Console.WriteLine("The values in unsorted order:"); - foreach (var pitcher in pitchers) - Console.WriteLine(pitcher.ToString()); - Console.WriteLine(); - - // Sort the array - Array.Sort(pitchers); - - // Display the array in sorted order. - Console.WriteLine("The values in sorted order:"); - foreach (var pitcher in pitchers) - Console.WriteLine(pitcher.ToString()); - } + // Display the array in sorted order. + Console.WriteLine("The values in sorted order:"); + foreach (var pitcher in pitchers) + Console.WriteLine(pitcher); + } } // The example displays the following output; // The values in unsorted order: @@ -39,7 +39,7 @@ public static void Main() // (Henry, Walt, 140.1, 96, 30) // (Lee, Adam, 137.2, 109, 45) // (Rohr, Don, 101, 110, 42) -// +// // The values in sorted order: // (Blair, Jack, 168.1, 146, 65) // (Henry, Walt, 140.1, 96, 30) @@ -48,4 +48,4 @@ public static void Main() // (Paul, Dave, 233.1, 231, 84) // (Rohr, Don, 101, 110, 42) // (Williams, Mike, 193.2, 183, 86) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 63ac793f8b2..e865230ce19 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,46 +5,46 @@ public class PitcherComparer : IComparer { - public int Compare(object x, object y) - { - Tuple tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - Tuple tY = y as Tuple; - return Comparer.Default.Compare(tX.Item3, tY.Item3); - } - } + public int Compare(object x, object y) + { + Tuple tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + Tuple tY = y as Tuple; + return Comparer.Default.Compare(tX.Item3, tY.Item3); + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - Tuple[] pitchers = - { Tuple.Create("McHale, Joe", 240.1, 3.60, 221), - Tuple.Create("Paul, Dave", 233.1, 3.24, 231), + public static void Run() + { + Tuple[] pitchers = + [ Tuple.Create("McHale, Joe", 240.1, 3.60, 221), + Tuple.Create("Paul, Dave", 233.1, 3.24, 231), Tuple.Create("Williams, Mike", 193.2, 4.00, 183), - Tuple.Create("Blair, Jack", 168.1, 3.48, 146), + Tuple.Create("Blair, Jack", 168.1, 3.48, 146), Tuple.Create("Henry, Walt", 140.1, 1.92, 96), Tuple.Create("Lee, Adam", 137.2, 2.94, 109), - Tuple.Create("Rohr, Don", 101.0, 3.74, 110) }; + Tuple.Create("Rohr, Don", 101.0, 3.74, 110) ]; - Console.WriteLine("The values in unsorted order:"); - foreach (var pitcher in pitchers) - Console.WriteLine(pitcher.ToString()); + Console.WriteLine("The values in unsorted order:"); + foreach (var pitcher in pitchers) + Console.WriteLine(pitcher); - Console.WriteLine(); + Console.WriteLine(); - Array.Sort(pitchers, new PitcherComparer()); + Array.Sort(pitchers, new PitcherComparer()); - Console.WriteLine("The values sorted by earned run average (component 3):"); - foreach (var pitcher in pitchers) - Console.WriteLine(pitcher.ToString()); - } + Console.WriteLine("The values sorted by earned run average (component 3):"); + foreach (var pitcher in pitchers) + Console.WriteLine(pitcher); + } } // The example displays the following output; // The values in unsorted order: @@ -55,7 +55,7 @@ public static void Main() // (Henry, Walt, 140.1, 1.92, 96) // (Lee, Adam, 137.2, 2.94, 109) // (Rohr, Don, 101, 3.74, 110) -// +// // The values sorted by earned run average (component 3): // (Henry, Walt, 140.1, 1.92, 96) // (Lee, Adam, 137.2, 2.94, 109) diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs index 009918fab0a..d2763f2aa90 100644 --- a/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs @@ -3,19 +3,19 @@ public class Example { - public static void Main() - { - Tuple[] temperatures = - { Tuple.Create("New York, NY", 4, 61, 43), - Tuple.Create("Chicago, IL", 2, 34, 18), + public static void Main() + { + Tuple[] temperatures = + [ Tuple.Create("New York, NY", 4, 61, 43), + Tuple.Create("Chicago, IL", 2, 34, 18), Tuple.Create("Newark, NJ", 4, 61, 43), Tuple.Create("Boston, MA", 6, 77, 59), Tuple.Create("Detroit, MI", 9, 74, 53), - Tuple.Create("Minneapolis, MN", 8, 81, 61) }; - // Display the array of 4-tuple objects. - foreach (var temperature in temperatures) - Console.WriteLine(temperature.ToString()); - } + Tuple.Create("Minneapolis, MN", 8, 81, 61) ]; + // Display the array of 4-tuple objects. + foreach (var temperature in temperatures) + Console.WriteLine(temperature.ToString()); + } } // The example displays the following output: // (New York, NY, 4, 61, 43) @@ -24,4 +24,4 @@ public static void Main() // (Boston, MA, 6, 77, 59) // (Detroit, MI, 9, 74, 53) // (Minneapolis, MN, 8, 81, 61) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs new file mode 100644 index 00000000000..76c3e934c0b --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsExample1.Run(); +EqualsExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs index 24aec55f956..8ba5dddad3e 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs @@ -1,31 +1,30 @@ // using System; -public class Example +public class EqualsExample1 { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Ed", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + public static void Run() + { + Tuple[] scores = + [ Tuple.Create("Ed", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Ed", 71.2, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Ed", 71.2, 9), - Tuple.Create("Judith", 84.3, 9) }; + Tuple.Create("Judith", 84.3, 9) ]; - // Test each tuple object for equality with every other tuple. - for (int ctr = 0; ctr < scores.Length; ctr++) - { - var currentTuple = scores[ctr]; - for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++) - Console.WriteLine("{0} = {1}: {2}", currentTuple, scores[ctr2], - currentTuple.Equals(scores[ctr2])); + // Test each tuple object for equality with every other tuple. + for (int ctr = 0; ctr < scores.Length; ctr++) + { + var currentTuple = scores[ctr]; + for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++) + Console.WriteLine($"{currentTuple} = {scores[ctr2]}: {currentTuple.Equals(scores[ctr2])}"); - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output; // (Ed, 78.8, 8) = (Abbey, 92.1, 9): False @@ -35,31 +34,31 @@ public static void Main() // (Ed, 78.8, 8) = (Penelope, 82.9, 8): False // (Ed, 78.8, 8) = (Ed, 71.2, 9): False // (Ed, 78.8, 8) = (Judith, 84.3, 9): False -// +// // (Abbey, 92.1, 9) = (Ed, 71.2, 9): False // (Abbey, 92.1, 9) = (Sam, 91.7, 8): False // (Abbey, 92.1, 9) = (Ed, 71.2, 5): False // (Abbey, 92.1, 9) = (Penelope, 82.9, 8): False // (Abbey, 92.1, 9) = (Ed, 71.2, 9): False // (Abbey, 92.1, 9) = (Judith, 84.3, 9): False -// +// // (Ed, 71.2, 9) = (Sam, 91.7, 8): False // (Ed, 71.2, 9) = (Ed, 71.2, 5): False // (Ed, 71.2, 9) = (Penelope, 82.9, 8): False // (Ed, 71.2, 9) = (Ed, 71.2, 9): True // (Ed, 71.2, 9) = (Judith, 84.3, 9): False -// +// // (Sam, 91.7, 8) = (Ed, 71.2, 5): False // (Sam, 91.7, 8) = (Penelope, 82.9, 8): False // (Sam, 91.7, 8) = (Ed, 71.2, 9): False // (Sam, 91.7, 8) = (Judith, 84.3, 9): False -// +// // (Ed, 71.2, 5) = (Penelope, 82.9, 8): False // (Ed, 71.2, 5) = (Ed, 71.2, 9): False // (Ed, 71.2, 5) = (Judith, 84.3, 9): False -// +// // (Penelope, 82.9, 8) = (Ed, 71.2, 9): False // (Penelope, 82.9, 8) = (Judith, 84.3, 9): False -// +// // (Ed, 71.2, 9) = (Judith, 84.3, 9): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs index dff73822973..23b181ee11c 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs @@ -4,55 +4,53 @@ public class Item2Comparer : IEqualityComparer { - new public bool Equals(object x, object y) - { - // Return true for all values of Item1. - if (x is T1) - return true; - else if (x is T2) - return x.Equals(y); - else - return true; - } - - public int GetHashCode(object obj) - { - if (obj is T1) - return ((T1) obj).GetHashCode(); - else if (obj is T2) - return ((T2) obj).GetHashCode(); - else - return ((T3) obj).GetHashCode(); - } + new public bool Equals(object x, object y) + { + // Return true for all values of Item1. + if (x is T1) + return true; + else if (x is T2) + return x.Equals(y); + else + return true; + } + + public int GetHashCode(object obj) + { + if (obj is T1) + return ((T1)obj).GetHashCode(); + else if (obj is T2) + return ((T2)obj).GetHashCode(); + else + return ((T3)obj).GetHashCode(); + } } -public class Example +public class EqualsExample2 { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Ed", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + public static void Run() + { + Tuple[] scores = + [ Tuple.Create("Ed", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Jim", 71.2, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Sandy", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Serena", 71.2, 9), - Tuple.Create("Judith", 84.3, 9) }; + Tuple.Create("Judith", 84.3, 9) ]; - for (int ctr = 0; ctr < scores.Length; ctr++) - { - IStructuralEquatable score = scores[ctr]; - for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++) - { - Console.WriteLine("{0} = {1}: {2}", score, - scores[ctr2], - score.Equals(scores[ctr2], - new Item2Comparer())); - } - Console.WriteLine(); - } - } + for (int ctr = 0; ctr < scores.Length; ctr++) + { + IStructuralEquatable score = scores[ctr]; + for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++) + { + Console.WriteLine($"{score} = {scores[ctr2]}: {score.Equals(scores[ctr2], + new Item2Comparer())}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // (Ed, 78.8, 8) = (Abbey, 92.1, 9): False @@ -69,7 +67,7 @@ public static void Main() // (Abbey, 92.1, 9) = (Penelope, 82.9, 8): False // (Abbey, 92.1, 9) = (Serena, 71.2, 9): False // (Abbey, 92.1, 9) = (Judith, 84.3, 9): False -// +// // (Jim, 71.2, 9) = (Sam, 91.7, 8): False // (Jim, 71.2, 9) = (Sandy, 71.2, 5): True // (Jim, 71.2, 9) = (Penelope, 82.9, 8): False @@ -89,4 +87,4 @@ public static void Main() // (Penelope, 82.9, 8) = (Judith, 84.3, 9): False // // (Serena, 71.2, 9) = (Judith, 84.3, 9): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs index 9a557df905a..1a54d079df8 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs @@ -1,47 +1,48 @@ -// -using System; +using System; public class Example { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Jack", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + // + public static void Main() + { + Tuple[] scores = + [ Tuple.Create("Jack", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Dave", 88.3, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Linda", 99.0, 9), - Tuple.Create("Judith", 84.3, 9) }; - var result = ComputeStatistics(scores); - Console.WriteLine("Mean score: {0:N2} (SD={1:N2}) (n={2})", - result.Item2, result.Item3, result.Item1); - } + Tuple.Create("Judith", 84.3, 9) ]; + var result = ComputeStatistics(scores); + Console.WriteLine($"Mean score: {result.Item2:N2} (SD={result.Item3:N2}) (n={result.Item1})"); + } - private static Tuple ComputeStatistics(Tuple[] scores) - { - int n = 0; - double sum = 0; + private static Tuple ComputeStatistics(Tuple[] scores) + { + int n = 0; + double sum = 0; - // Compute the mean. - foreach (var score in scores) - { - n += score.Item3; - sum += score.Item2 * score.Item3; - } - double mean = sum / n; - - // Compute the standard deviation. - double ss = 0; - foreach (var score in scores) - { - ss = Math.Pow(score.Item2 - mean, 2); - } - double sd = Math.Sqrt(ss/scores.Length); - return Tuple.Create(scores.Length, mean, sd); - } + // Compute the mean. + foreach (Tuple score in scores) + { + n += score.Item3; + sum += score.Item2 * score.Item3; + } + double mean = sum / n; + + // Compute the standard deviation. + double ss = 0; + foreach (Tuple score in scores) + { + ss += Math.Pow(score.Item2 - mean, 2); + } + double sd = Math.Sqrt(ss / scores.Length); + return Tuple.Create(scores.Length, mean, sd); + } + + // The example displays the following output: + // Mean score: 87.02 (SD=8.18) (n=8) + + // } -// The example displays the following output: -// Mean score: 87.02 (SD=0.96) (n=8) -// \ No newline at end of file diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index a1ad9e789f0..d708ac6b3fb 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,32 +1,32 @@ // using System; -public class Example +public class CompareToExample1 { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Jack", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + public static void Run() + { + Tuple[] scores = + [ Tuple.Create("Jack", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Dave", 88.3, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Linda", 99.0, 9), - Tuple.Create("Judith", 84.3, 9) }; + Tuple.Create("Judith", 84.3, 9) ]; - Console.WriteLine("The values in unsorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); + Console.WriteLine("The values in unsorted order:"); + foreach (var score in scores) + Console.WriteLine(score); - Console.WriteLine(); + Console.WriteLine(); - Array.Sort(scores); + Array.Sort(scores); - Console.WriteLine("The values in sorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); - } + Console.WriteLine("The values in sorted order:"); + foreach (var score in scores) + Console.WriteLine(score); + } } // The example displays the following output; // The values in unsorted order: @@ -38,7 +38,7 @@ public static void Main() // (Penelope, 82.9, 8) // (Linda, 99, 9) // (Judith, 84.3, 9) -// +// // The values in sorted order: // (Abbey, 92.1, 9) // (Dave, 88.3, 9) diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 1af88bd54ed..0b9b3e25782 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,47 +5,47 @@ public class ScoreComparer : IComparer { - public int Compare(object x, object y) - { - Tuple tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - Tuple tY = y as Tuple; - return Comparer.Default.Compare(tX.Item2, tY.Item2); - } - } + public int Compare(object x, object y) + { + Tuple tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + Tuple tY = y as Tuple; + return Comparer.Default.Compare(tX.Item2, tY.Item2); + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Jack", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + public static void Run() + { + Tuple[] scores = + [ Tuple.Create("Jack", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Dave", 88.3, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Linda", 99.0, 9), - Tuple.Create("Judith", 84.3, 9) }; + Tuple.Create("Judith", 84.3, 9) ]; - Console.WriteLine("The values in unsorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); + Console.WriteLine("The values in unsorted order:"); + foreach (var score in scores) + Console.WriteLine(score); - Console.WriteLine(); + Console.WriteLine(); - Array.Sort(scores, new ScoreComparer()); + Array.Sort(scores, new ScoreComparer()); - Console.WriteLine("The values in sorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); - } + Console.WriteLine("The values in sorted order:"); + foreach (var score in scores) + Console.WriteLine(score); + } } // The example displays the following output; // The values in unsorted order: @@ -57,7 +57,7 @@ public static void Main() // (Penelope, 82.9, 8) // (Linda, 99, 9) // (Judith, 84.3, 9) -// +// // The values in sorted order: // (Ed, 71.2, 5) // (Jack, 78.8, 8) diff --git a/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs index a42543f6550..832c29ade58 100644 --- a/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs @@ -3,21 +3,21 @@ public class Example { - public static void Main() - { - Tuple[] scores = - { Tuple.Create("Jack", 78.8, 8), - Tuple.Create("Abbey", 92.1, 9), + public static void Main() + { + Tuple[] scores = + [ Tuple.Create("Jack", 78.8, 8), + Tuple.Create("Abbey", 92.1, 9), Tuple.Create("Dave", 88.3, 9), - Tuple.Create("Sam", 91.7, 8), + Tuple.Create("Sam", 91.7, 8), Tuple.Create("Ed", 71.2, 5), Tuple.Create("Penelope", 82.9, 8), Tuple.Create("Linda", 99.0, 9), - Tuple.Create("Judith", 84.3, 9) }; - Array.Sort(scores); - foreach (var score in scores) - Console.WriteLine(score.ToString()); - } + Tuple.Create("Judith", 84.3, 9) ]; + Array.Sort(scores); + foreach (var score in scores) + Console.WriteLine(score.ToString()); + } } // The example displays the following output; // (Abbey, 92.1, 9) diff --git a/snippets/csharp/System/TupleT1,T2/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2/Equals/Program.cs new file mode 100644 index 00000000000..76c3e934c0b --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsExample1.Run(); +EqualsExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs index 9ccf93e354a..0ca2da4557f 100644 --- a/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs @@ -1,30 +1,28 @@ // using System; -public class Example +public class EqualsExample1 { - public static void Main() - { - Tuple>[] scores = - { new Tuple>("Dan", 90), + public static void Run() + { + Tuple>[] scores = + [ new Tuple>("Dan", 90), new Tuple>("Ernie", null), new Tuple>("Jill", 88), - new Tuple>("Ernie", null), - new Tuple>("Nancy", 88), - new Tuple>("Dan", 90) }; + new Tuple>("Ernie", null), + new Tuple>("Nancy", 88), + new Tuple>("Dan", 90) ]; - // Compare the Tuple objects - for (int ctr = 0; ctr < scores.Length; ctr++) - { - for (int innerCtr = ctr + 1; innerCtr < scores.Length; innerCtr++) - { - Console.WriteLine("{0} = {1}: {2}", - scores[ctr], scores[innerCtr], - scores[ctr].Equals(scores[innerCtr])); - } - Console.WriteLine(); - } - } + // Compare the Tuple objects + for (int ctr = 0; ctr < scores.Length; ctr++) + { + for (int innerCtr = ctr + 1; innerCtr < scores.Length; innerCtr++) + { + Console.WriteLine($"{scores[ctr]} = {scores[innerCtr]}: {scores[ctr].Equals(scores[innerCtr])}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // (Dan, 90) = (Ernie, ): False @@ -32,18 +30,18 @@ public static void Main() // (Dan, 90) = (Ernie, ): False // (Dan, 90) = (Nancy, 88): False // (Dan, 90) = (Dan, 90): True -// +// // (Ernie, ) = (Jill, 88): False // (Ernie, ) = (Ernie, ): True // (Ernie, ) = (Nancy, 88): False // (Ernie, ) = (Dan, 90): False -// +// // (Jill, 88) = (Ernie, ): False // (Jill, 88) = (Nancy, 88): False // (Jill, 88) = (Dan, 90): False -// +// // (Ernie, ) = (Nancy, 88): False // (Ernie, ) = (Dan, 90): False -// +// // (Nancy, 88) = (Dan, 90): False // diff --git a/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs index f045c09c1c3..dc343a7d775 100644 --- a/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs @@ -4,61 +4,59 @@ public class Item2Comparer : IEqualityComparer { - new public bool Equals(object x, object y) - { - // Return true for all values of Item1. - if (x is T1) - //if (typeof(x) is string) - return true; - else - return x.Equals(y); - } - - public int GetHashCode(object obj) - { - if (obj is T1) - return ((T1) obj).GetHashCode(); - else - return ((T2) obj).GetHashCode(); - } + new public bool Equals(object x, object y) + { + // Return true for all values of Item1. + if (x is T1) + //if (typeof(x) is string) + return true; + else + return x.Equals(y); + } + + public int GetHashCode(object obj) + { + if (obj is T1) + return ((T1)obj).GetHashCode(); + else + return ((T2)obj).GetHashCode(); + } } -public class Example +public class EqualsExample2 { - public static void Main() - { - Tuple[] distancesWalked = { - Tuple.Create("Jan", Double.NaN), - Tuple.Create("Joe", Double.NaN), - Tuple.Create("Adam", 1.36), + public static void Run() + { + Tuple[] distancesWalked = [ + Tuple.Create("Jan", double.NaN), + Tuple.Create("Joe", double.NaN), + Tuple.Create("Adam", 1.36), Tuple.Create("Selena", 2.01), - Tuple.Create("Jake", 1.36) }; - for (int ctr = 0; ctr < distancesWalked.Length; ctr++) - { - Tuple distanceWalked = distancesWalked[ctr]; - for (int ctr2 = ctr + 1; ctr2 < distancesWalked.Length; ctr2++) - { - Console.WriteLine("{0} = {1}: {2}", distanceWalked, - distancesWalked[ctr2], - ((IStructuralEquatable)distanceWalked).Equals(distancesWalked[ctr2], - new Item2Comparer())); - } - Console.WriteLine(); - } - } + Tuple.Create("Jake", 1.36) ]; + for (int ctr = 0; ctr < distancesWalked.Length; ctr++) + { + Tuple distanceWalked = distancesWalked[ctr]; + for (int ctr2 = ctr + 1; ctr2 < distancesWalked.Length; ctr2++) + { + Console.WriteLine($"{distanceWalked} = {distancesWalked[ctr2]}: {((IStructuralEquatable)distanceWalked).Equals(distancesWalked[ctr2], + new Item2Comparer())}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // (Jan, NaN) = (Joe, NaN): True // (Jan, NaN) = (Adam, 1.36): False // (Jan, NaN) = (Selena, 2.01): False // (Jan, NaN) = (Jake, 1.36): False -// +// // (Joe, NaN) = (Adam, 1.36): False // (Joe, NaN) = (Selena, 2.01): False // (Joe, NaN) = (Jake, 1.36): False -// +// // (Adam, 1.36) = (Selena, 2.01): False // (Adam, 1.36) = (Jake, 1.36): True -// +// // (Selena, 2.01) = (Jake, 1.36): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2/Overview/example1.cs index a1a02fcecdc..02dc697b4e3 100644 --- a/snippets/csharp/System/TupleT1,T2/Overview/example1.cs +++ b/snippets/csharp/System/TupleT1,T2/Overview/example1.cs @@ -3,40 +3,40 @@ public class Example { - public static void Main() - { - Tuple>[] scores = - { new Tuple>("Jack", 78), - new Tuple>("Abbey", 92), + public static void Main() + { + Tuple>[] scores = + [ new Tuple>("Jack", 78), + new Tuple>("Abbey", 92), new Tuple>("Dave", 88), - new Tuple>("Sam", 91), + new Tuple>("Sam", 91), new Tuple>("Ed", null), new Tuple>("Penelope", 82), new Tuple>("Linda", 99), - new Tuple>("Judith", 84) }; - int number; - double mean = ComputeMean(scores, out number); - Console.WriteLine("Average test score: {0:N2} (n={1})", mean, number); - } + new Tuple>("Judith", 84) ]; + int number; + double mean = ComputeMean(scores, out number); + Console.WriteLine($"Average test score: {mean:N2} (n={number})"); + } - private static double ComputeMean(Tuple>[] scores, out int n) - { - n = 0; - int sum = 0; - foreach (var score in scores) - { - if (score.Item2.HasValue) - { - n += 1; - sum += score.Item2.Value; - } - } - if (n > 0) - return sum / (double) n; - else - return 0; - } + private static double ComputeMean(Tuple>[] scores, out int n) + { + n = 0; + int sum = 0; + foreach (var score in scores) + { + if (score.Item2.HasValue) + { + n += 1; + sum += score.Item2.Value; + } + } + if (n > 0) + return sum / (double)n; + else + return 0; + } } // The example displays the following output: // Average test score: 87.71 (n=7) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2/Overview/item1.cs b/snippets/csharp/System/TupleT1,T2/Overview/item1.cs index a57aef25409..c861a905a2d 100644 --- a/snippets/csharp/System/TupleT1,T2/Overview/item1.cs +++ b/snippets/csharp/System/TupleT1,T2/Overview/item1.cs @@ -3,41 +3,41 @@ public class Class1 { - public static void Main() - { - int dividend, divisor; - Tuple result; - - dividend = 136945; divisor = 178; - result = IntegerDivide(dividend, divisor); - if (result != null) - Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", - dividend, divisor, result.Item1, result.Item2); - else - Console.WriteLine(@"{0} \ {1} = ", dividend, divisor); - - dividend = Int32.MaxValue; divisor = -2073; - result = IntegerDivide(dividend, divisor); - if (result != null) - Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", - dividend, divisor, result.Item1, result.Item2); - else - Console.WriteLine(@"{0} \ {1} = ", dividend, divisor); - } + public static void Main() + { + int dividend, divisor; + Tuple result; - private static Tuple IntegerDivide(int dividend, int divisor) - { - try { - int remainder; - int quotient = Math.DivRem(dividend, divisor, out remainder); - return new Tuple(quotient, remainder); - } - catch (DivideByZeroException) { - return null; - } - } + dividend = 136945; divisor = 178; + result = IntegerDivide(dividend, divisor); + if (result != null) + Console.WriteLine($"{dividend} \\ {divisor} = {result.Item1}, remainder {result.Item2}"); + else + Console.WriteLine($"{dividend} \\ {divisor} = "); + + dividend = int.MaxValue; divisor = -2073; + result = IntegerDivide(dividend, divisor); + if (result != null) + Console.WriteLine($"{dividend} \\ {divisor} = {result.Item1}, remainder {result.Item2}"); + else + Console.WriteLine($"{dividend} \\ {divisor} = "); + } + + private static Tuple IntegerDivide(int dividend, int divisor) + { + try + { + int remainder; + int quotient = Math.DivRem(dividend, divisor, out remainder); + return new Tuple(quotient, remainder); + } + catch (DivideByZeroException) + { + return null; + } + } } // The example displays the following output: // 136945 \ 178 = 769, remainder 63 // 2147483647 \ -2073 = -1035930, remainder 757 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs new file mode 100644 index 00000000000..e84b3c44eae --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs @@ -0,0 +1,2 @@ +CompareToExample1.Run(); +CompareToExample2.Run(); diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index d0996174ea7..73b2143e66d 100644 --- a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -1,32 +1,32 @@ // using System; -public class Example +public class CompareToExample1 { - public static void Main() - { - Tuple>[] scores = - { new Tuple>("Jack", 78), - new Tuple>("Abbey", 92), + public static void Run() + { + Tuple>[] scores = + [ new Tuple>("Jack", 78), + new Tuple>("Abbey", 92), new Tuple>("Dave", 88), - new Tuple>("Sam", 91), + new Tuple>("Sam", 91), new Tuple>("Ed", null), new Tuple>("Penelope", 82), new Tuple>("Linda", 99), - new Tuple>("Judith", 84) }; + new Tuple>("Judith", 84) ]; - Console.WriteLine("The values in unsorted order:"); - foreach (Tuple> score in scores) - Console.WriteLine(score.ToString()); + Console.WriteLine("The values in unsorted order:"); + foreach (Tuple> score in scores) + Console.WriteLine(score); - Console.WriteLine(); + Console.WriteLine(); - Array.Sort(scores); + Array.Sort(scores); - Console.WriteLine("The values in sorted order:"); - foreach (Tuple> score in scores) - Console.WriteLine(score.ToString()); - } + Console.WriteLine("The values in sorted order:"); + foreach (Tuple> score in scores) + Console.WriteLine(score); + } } // The example displays the following output; // The values in unsorted order: @@ -38,7 +38,7 @@ public static void Main() // (Penelope, 82) // (Linda, 99) // (Judith, 84) -// +// // The values in sorted order: // (Abbey, 92) // (Dave, 88) diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 10f13edf8ca..7cc9e07b8c3 100644 --- a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -5,47 +5,47 @@ public class ScoreComparer : IComparer { - public int Compare(object x, object y) - { - Tuple tX = x as Tuple; - if (tX == null) - { - return 0; - } - else - { - Tuple tY = y as Tuple; - return Comparer.Default.Compare(tX.Item2, tY.Item2); - } - } + public int Compare(object x, object y) + { + Tuple tX = x as Tuple; + if (tX == null) + { + return 0; + } + else + { + Tuple tY = y as Tuple; + return Comparer.Default.Compare(tX.Item2, tY.Item2); + } + } } -public class Example +public class CompareToExample2 { - public static void Main() - { - Tuple>[] scores = - { new Tuple>("Jack", 78), - new Tuple>("Abbey", 92), + public static void Run() + { + Tuple>[] scores = + [ new Tuple>("Jack", 78), + new Tuple>("Abbey", 92), new Tuple>("Dave", 88), - new Tuple>("Sam", 91), + new Tuple>("Sam", 91), new Tuple>("Ed", null), new Tuple>("Penelope", 82), new Tuple>("Linda", 99), - new Tuple>("Judith", 84) }; + new Tuple>("Judith", 84) ]; - Console.WriteLine("The values in unsorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); + Console.WriteLine("The values in unsorted order:"); + foreach (var score in scores) + Console.WriteLine(score); - Console.WriteLine(); + Console.WriteLine(); - Array.Sort(scores, new ScoreComparer>()); + Array.Sort(scores, new ScoreComparer>()); - Console.WriteLine("The values in sorted order:"); - foreach (var score in scores) - Console.WriteLine(score.ToString()); - } + Console.WriteLine("The values in sorted order:"); + foreach (var score in scores) + Console.WriteLine(score); + } } // The example displays the following output; // The values in unsorted order: @@ -57,7 +57,7 @@ public static void Main() // (Penelope, 82) // (Linda, 99) // (Judith, 84) -// +// // The values in sorted order: // (Ed, ) // (Jack, 78) diff --git a/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs index 47d86b30856..0356a33334f 100644 --- a/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs @@ -3,20 +3,20 @@ public class Class1 { - public static void Main() - { - Tuple>[] scores = - { new Tuple>("Abbey", 92), + public static void Main() + { + Tuple>[] scores = + [ new Tuple>("Abbey", 92), new Tuple>("Dave", 88), new Tuple>("Ed", null), new Tuple>("Jack", 78), new Tuple>("Linda", 99), - new Tuple>("Judith", 84), + new Tuple>("Judith", 84), new Tuple>("Penelope", 82), - new Tuple>("Sam", 91) }; - foreach (var score in scores) - Console.WriteLine(score.ToString()); - } + new Tuple>("Sam", 91) ]; + foreach (var score in scores) + Console.WriteLine(score.ToString()); + } } // The example displays the following output: // (Abbey, 92) @@ -27,4 +27,4 @@ public static void Main() // (Judith, 84) // (Penelope, 82) // (Sam, 91) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1/Equals/Program.cs b/snippets/csharp/System/TupleT1/Equals/Program.cs new file mode 100644 index 00000000000..76c3e934c0b --- /dev/null +++ b/snippets/csharp/System/TupleT1/Equals/Program.cs @@ -0,0 +1,2 @@ +EqualsExample1.Run(); +EqualsExample2.Run(); diff --git a/snippets/csharp/System/TupleT1/Equals/Project.csproj b/snippets/csharp/System/TupleT1/Equals/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System/TupleT1/Equals/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System/TupleT1/Equals/equals1.cs b/snippets/csharp/System/TupleT1/Equals/equals1.cs index 5a365c682c9..2c60f157b24 100644 --- a/snippets/csharp/System/TupleT1/Equals/equals1.cs +++ b/snippets/csharp/System/TupleT1/Equals/equals1.cs @@ -1,36 +1,31 @@ // using System; -public class Example +public class EqualsExample1 { - public static void Main() - { - var doubleTuple1 = Tuple.Create(12.3455); - var doubleTuple2 = Tuple.Create(16.8912); - var doubleTuple3 = Tuple.Create(12.3455); - var singleTuple1 = Tuple.Create(12.3455f); - var tuple2 = Tuple.Create("James", 97.3); - - // Compare first tuple with a Tuple(Of Double) with a different value. - TestEquality(doubleTuple1, doubleTuple2); - // Compare first tuple with a Tuple(Of Double) with the same value. - TestEquality(doubleTuple1, doubleTuple3); - // Compare first tuple with a Tuple(Of Single) with the same value. - TestEquality(doubleTuple1, singleTuple1); - // Compare a 1-tuple with a 2-tuple. - TestEquality(doubleTuple1, tuple2); - } + public static void Run() + { + var doubleTuple1 = Tuple.Create(12.3455); + var doubleTuple2 = Tuple.Create(16.8912); + var doubleTuple3 = Tuple.Create(12.3455); + var singleTuple1 = Tuple.Create(12.3455f); + var tuple2 = Tuple.Create("James", 97.3); - private static void TestEquality(Tuple tuple, object obj) - { - Console.WriteLine("{0} = {1}: {2}", tuple.ToString(), - obj.ToString(), - tuple.Equals(obj)); - } + // Compare first tuple with a Tuple(Of Double) with a different value. + TestEquality(doubleTuple1, doubleTuple2); + // Compare first tuple with a Tuple(Of Double) with the same value. + TestEquality(doubleTuple1, doubleTuple3); + // Compare first tuple with a Tuple(Of Single) with the same value. + TestEquality(doubleTuple1, singleTuple1); + // Compare a 1-tuple with a 2-tuple. + TestEquality(doubleTuple1, tuple2); + } + + private static void TestEquality(Tuple tuple, object obj) => Console.WriteLine($"{tuple} = {obj}: {tuple.Equals(obj)}"); } // The example displays the following output: // (12.3455) = (16.8912): False // (12.3455) = (12.3455): True // (12.3455) = (12.3455): False // (12.3455) = (James, 97.3): False -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1/Equals/equals2.cs b/snippets/csharp/System/TupleT1/Equals/equals2.cs index cc3bfa89197..24acf28869f 100644 --- a/snippets/csharp/System/TupleT1/Equals/equals2.cs +++ b/snippets/csharp/System/TupleT1/Equals/equals2.cs @@ -4,55 +4,47 @@ public class Tuple1Comparer : IEqualityComparer { - new public bool Equals(object x, object y) - { - // Check if x is a floating point type. If x is, then y is. - if (x is double | x is float) - { - // Convert to Double values. - double dblX = (double) x; - double dblY = (double) y; - if (Double.IsNaN(dblX) | Double.IsInfinity(dblX) | - Double.IsNaN(dblY) | Double.IsInfinity(dblY)) - return dblX.Equals(dblY); - else - return Math.Abs(dblX - dblY) <= dblX * .0001; - } - else - { - return x.Equals(y); - } - } - - public int GetHashCode(object obj) - { - return obj.GetHashCode(); - } + new public bool Equals(object x, object y) + { + // Check if x is a floating point type. If x is, then y is. + if (x is double | x is float) + { + // Convert to Double values. + double dblX = (double)x; + double dblY = (double)y; + if (double.IsNaN(dblX) | double.IsInfinity(dblX) | + double.IsNaN(dblY) | double.IsInfinity(dblY)) + return dblX.Equals(dblY); + else + return Math.Abs(dblX - dblY) <= dblX * .0001; + } + else + { + return x.Equals(y); + } + } + + public int GetHashCode(object obj) => obj.GetHashCode(); } -public class Example +public class EqualsExample2 { - public static void Main() - { - var doubleTuple1 = Tuple.Create(12.3455); + public static void Run() + { + var doubleTuple1 = Tuple.Create(12.3455); - var doubleTuple2 = Tuple.Create(16.8912); - var doubleTuple3 = Tuple.Create(12.3449599); + var doubleTuple2 = Tuple.Create(16.8912); + var doubleTuple3 = Tuple.Create(12.3449599); - // Compare first tuple with a Tuple with a different value. - TestEquality(doubleTuple1, doubleTuple2); - //Compare first tuple with a Tuple with the same value. - TestEquality(doubleTuple1, doubleTuple3); - } + // Compare first tuple with a Tuple with a different value. + TestEquality(doubleTuple1, doubleTuple2); + //Compare first tuple with a Tuple with the same value. + TestEquality(doubleTuple1, doubleTuple3); + } - private static void TestEquality(Tuple tuple, object obj) - { - Console.WriteLine("{0} = {1}: {2}", tuple.ToString(), - obj.ToString(), - ((IStructuralEquatable)tuple).Equals(obj, new Tuple1Comparer())); - } + private static void TestEquality(Tuple tuple, object obj) => Console.WriteLine($"{tuple} = {obj}: {((IStructuralEquatable)tuple).Equals(obj, new Tuple1Comparer())}"); } // The example displays the following output: // (12.3455) = (16.8912): False // (12.3455) = (12.3449599): True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1/Item1/item1.cs b/snippets/csharp/System/TupleT1/Item1/item1.cs index d5d736a519c..95686fa2c6d 100644 --- a/snippets/csharp/System/TupleT1/Item1/item1.cs +++ b/snippets/csharp/System/TupleT1/Item1/item1.cs @@ -4,31 +4,27 @@ public class Example { - public static void Main() - { - var tuple1 = Tuple.Create(-1.23445e-32); - // Display information about this singleton. - Type tuple1Type = tuple1.GetType(); - Console.WriteLine("First 1-Tuple:"); - Console.WriteLine(" Type: {0}", tuple1Type.Name); - Console.WriteLine(" Generic Parameter Type: {0}", - tuple1Type.GetGenericArguments()[0]); - Console.WriteLine(" Component Value: {0}", tuple1.Item1); - Console.WriteLine(" Component Value Type: {0}", - tuple1.Item1.GetType().Name); - Console.WriteLine(); - - var tuple2 = Tuple.Create((BigInteger)1.83789322281780983781356676e103); - // Display information about this singleton. - Type tuple2Type = tuple2.GetType(); - Console.WriteLine("Second 1-Tuple:"); - Console.WriteLine(" Type: {0}", tuple2Type.Name); - Console.WriteLine(" Generic Parameter Type: {0}", - tuple2Type.GetGenericArguments()[0]); - Console.WriteLine(" Component Value: {0}", tuple2.Item1); - Console.WriteLine(" Component Value Type: {0}", - tuple2.Item1.GetType().Name); - } + public static void Main() + { + var tuple1 = Tuple.Create(-1.23445e-32); + // Display information about this singleton. + Type tuple1Type = tuple1.GetType(); + Console.WriteLine("First 1-Tuple:"); + Console.WriteLine($" Type: {tuple1Type.Name}"); + Console.WriteLine($" Generic Parameter Type: {tuple1Type.GetGenericArguments()[0]}"); + Console.WriteLine($" Component Value: {tuple1.Item1}"); + Console.WriteLine($" Component Value Type: {tuple1.Item1.GetType().Name}"); + Console.WriteLine(); + + var tuple2 = Tuple.Create((BigInteger)1.83789322281780983781356676e103); + // Display information about this singleton. + Type tuple2Type = tuple2.GetType(); + Console.WriteLine("Second 1-Tuple:"); + Console.WriteLine($" Type: {tuple2Type.Name}"); + Console.WriteLine($" Generic Parameter Type: {tuple2Type.GetGenericArguments()[0]}"); + Console.WriteLine($" Component Value: {tuple2.Item1}"); + Console.WriteLine($" Component Value Type: {tuple2.Item1.GetType().Name}"); + } } // The example displays the following output: // First 1-Tuple: @@ -36,10 +32,10 @@ public static void Main() // Generic Parameter Type: System.Double // Component Value: -1.23445E-32 // Component Value Type: Double -// +// // Second 1-Tuple: // Type: Tuple`1 // Generic Parameter Type: System.Numerics.BigInteger // Component Value: 1.8378932228178098168858909492E+103 // Component Value Type: BigInteger -// \ No newline at end of file +// diff --git a/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto1.cs index 23cac7f3614..37ac3d25cef 100644 --- a/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto1.cs +++ b/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto1.cs @@ -3,34 +3,34 @@ class Example { - static void Main() - { - Tuple[] values = { Tuple.Create(13.54), - Tuple.Create(Double.NaN), + static void Main() + { + Tuple[] values = [ Tuple.Create(13.54), + Tuple.Create(double.NaN), Tuple.Create(-189.42993), - Tuple.Create(Double.PositiveInfinity), - Tuple.Create(Double.Epsilon), + Tuple.Create(double.PositiveInfinity), + Tuple.Create(double.Epsilon), Tuple.Create(1.934E-17), - Tuple.Create(Double.NegativeInfinity), + Tuple.Create(double.NegativeInfinity), Tuple.Create(-0.000000000003588), - null }; - Console.WriteLine("The values in unsorted order:"); - foreach (var value in values) - if (value != null) - Console.WriteLine(" {0}", value.Item1); - else - Console.WriteLine(" "); - Console.WriteLine(); + null ]; + Console.WriteLine("The values in unsorted order:"); + foreach (var value in values) + if (value != null) + Console.WriteLine($" {value.Item1}"); + else + Console.WriteLine(" "); + Console.WriteLine(); - Array.Sort(values); + Array.Sort(values); - Console.WriteLine("The values in sorted order:"); - foreach (var value in values) - if (value != null) - Console.WriteLine(" {0}", value.Item1); - else - Console.WriteLine(" "); - } + Console.WriteLine("The values in sorted order:"); + foreach (var value in values) + if (value != null) + Console.WriteLine($" {value.Item1}"); + else + Console.WriteLine(" "); + } } // The example displays the following output: // The values in unsorted order: diff --git a/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto2.cs index 430bb392f3e..045e620f409 100644 --- a/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto2.cs +++ b/snippets/csharp/System/TupleT1/System.Collections.IStructuralComparable.CompareTo/compareto2.cs @@ -4,41 +4,38 @@ public class DescendingComparer : IComparer { - public int Compare(T x, T y) - { - return -1 * Comparer.Default.Compare(x, y); - } + public int Compare(T x, T y) => -1 * Comparer.Default.Compare(x, y); } class CompareTo2 { - static void Main() - { - Tuple[] values = { Tuple.Create(13.54), - Tuple.Create(Double.NaN), + static void Main() + { + Tuple[] values = [ Tuple.Create(13.54), + Tuple.Create(double.NaN), Tuple.Create(-189.42993), - Tuple.Create(Double.PositiveInfinity), - Tuple.Create(Double.Epsilon), + Tuple.Create(double.PositiveInfinity), + Tuple.Create(double.Epsilon), Tuple.Create(1.934E-17), - Tuple.Create(Double.NegativeInfinity), + Tuple.Create(double.NegativeInfinity), Tuple.Create(-0.000000000003588), - null }; - Console.WriteLine("The values in unsorted order:"); - foreach (var value in values) - if (value != null) - Console.WriteLine(" {0}", value.Item1); - else - Console.WriteLine(" "); - Console.WriteLine(); + null ]; + Console.WriteLine("The values in unsorted order:"); + foreach (var value in values) + if (value != null) + Console.WriteLine($" {value.Item1}"); + else + Console.WriteLine(" "); + Console.WriteLine(); - Array.Sort(values, new DescendingComparer>()); + Array.Sort(values, new DescendingComparer>()); - Console.WriteLine("The values sorted in descending order:"); - foreach (var value in values) - if (value != null) - Console.WriteLine(" {0}", value.Item1); - else - Console.WriteLine(" "); + Console.WriteLine("The values sorted in descending order:"); + foreach (var value in values) + if (value != null) + Console.WriteLine($" {value.Item1}"); + else + Console.WriteLine(" "); } } // The example displays the following output: diff --git a/snippets/csharp/System/TupleT1/ToString/tostring1.cs b/snippets/csharp/System/TupleT1/ToString/tostring1.cs index ff6f5293107..6136d54443b 100644 --- a/snippets/csharp/System/TupleT1/ToString/tostring1.cs +++ b/snippets/csharp/System/TupleT1/ToString/tostring1.cs @@ -3,29 +3,26 @@ public class Example { - public static void Main() - { - var tuple1Double = Tuple.Create(3.456e-18); - DisplayTuple(tuple1Double); - - var tuple1String = Tuple.Create("Australia"); - DisplayTuple(tuple1String); - - var tuple1Bool = Tuple.Create(true); - DisplayTuple(tuple1Bool); - - var tuple1Char = Tuple.Create('a'); - DisplayTuple(tuple1Char); - } + public static void Main() + { + var tuple1Double = Tuple.Create(3.456e-18); + DisplayTuple(tuple1Double); - private static void DisplayTuple(object obj) - { - Console.WriteLine(obj.ToString()); - } + var tuple1String = Tuple.Create("Australia"); + DisplayTuple(tuple1String); + + var tuple1Bool = Tuple.Create(true); + DisplayTuple(tuple1Bool); + + var tuple1Char = Tuple.Create('a'); + DisplayTuple(tuple1Char); + } + + private static void DisplayTuple(object obj) => Console.WriteLine(obj.ToString()); } // The example displays the following output: // (3.456E-18) // (Australia) // (True) // (a) -// \ No newline at end of file +// From c502949abc226ae399b07596acffa1b34e1e400e Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:57:27 -0700 Subject: [PATCH 6/9] Modernize C# code snippets - System/String (#12971) --- .../csharp/System/String/.ctor/char2_ctor.cs | 43 ++-- .../System/String/.ctor/chptrctor_null.cs | 42 ++-- snippets/csharp/System/String/.ctor/ctor1.cs | 14 +- snippets/csharp/System/String/.ctor/ctor2.cs | 23 +- .../System/String/.ctor/ptrctor_null.cs | 44 ++-- snippets/csharp/System/String/.ctor/source.cs | 66 +++--- snippets/csharp/System/String/Chars/chars1.cs | 20 +- .../System/String/Chars/uri_ishexdigit.cs | 36 ++-- .../System/String/Compare/ArrayListSample.cs | 32 +-- .../csharp/System/String/Compare/Compare18.cs | 15 +- .../csharp/System/String/Compare/Example.cs | 19 +- .../csharp/System/String/Compare/Example1.cs | 6 +- .../csharp/System/String/Compare/cmpcmp.cs | 29 ++- .../csharp/System/String/Compare/comp3.cs | 16 +- .../csharp/System/String/Compare/comp4.cs | 24 +-- .../csharp/System/String/Compare/comp5.cs | 24 +-- .../csharp/System/String/Compare/compare02.cs | 15 +- .../csharp/System/String/Compare/compare21.cs | 3 +- .../csharp/System/String/Compare/compare22.cs | 3 +- .../csharp/System/String/Compare/compare23.cs | 6 +- .../csharp/System/String/Compare/remarks.cs | 87 ++------ .../System/String/Compare/string.comp4.cs | 18 +- .../System/String/CompareOrdinal/comp0.cs | 32 +-- .../CompareOrdinal/stringcompareordinal.cs | 42 ++-- .../csharp/System/String/CompareTo/Program.cs | 4 + .../System/String/CompareTo/Project.csproj | 8 + .../System/String/CompareTo/compareto1.cs | 15 +- .../System/String/CompareTo/compareto2.cs | 17 +- .../System/String/CompareTo/extostring.cs | 44 ++-- .../String/CompareTo/stringcompareto.cs | 50 ++--- .../csharp/System/String/Concat/Concat6.cs | 20 +- .../csharp/System/String/Concat/Program.cs | 9 + .../System/String/Concat/Project.csproj | 8 + .../csharp/System/String/Concat/concat1.cs | 56 ++--- .../csharp/System/String/Concat/concat2.cs | 30 +-- .../csharp/System/String/Concat/concat3.cs | 47 ++-- .../csharp/System/String/Concat/concat4.cs | 64 +++--- .../System/String/Concat/string.concat5.cs | 32 +-- .../System/String/Concat/stringconcat1.cs | 18 +- .../System/String/Concat/stringconcat3.cs | 8 +- .../System/String/Concat/stringconcat4.cs | 10 +- .../System/String/Contains/ContainsExt1.cs | 48 ++--- .../csharp/System/String/Contains/cont.cs | 9 +- .../System/String/CopyTo/stringcopyto.cs | 20 +- .../System/String/EndsWith/EndsWith1.cs | 20 +- .../csharp/System/String/EndsWith/Program.cs | 4 + .../System/String/EndsWith/Project.csproj | 8 + .../csharp/System/String/EndsWith/ewci.cs | 18 +- .../csharp/System/String/EndsWith/ewcmp.cs | 19 +- .../System/String/EndsWith/stringendswith.cs | 33 +-- snippets/csharp/System/String/Equals/eqcmp.cs | 84 ++++---- .../csharp/System/String/Equals/equals.cs | 24 +-- .../csharp/System/String/Equals/equals_ex3.cs | 14 +- .../csharp/System/String/Equals/equalsex1.cs | 6 +- .../csharp/System/String/Format/Example1.cs | 40 ++-- .../csharp/System/String/Format/Example2.cs | 48 ++--- .../String/GetEnumerator/getenumerator.cs | 66 +++--- .../System/String/GetHashCode/gethashcode.cs | 36 ++-- .../System/String/GetHashCode/perdomain.cs | 74 +++---- .../csharp/System/String/GetTypeCode/gtc.cs | 9 +- .../csharp/System/String/IndexOf/Program.cs | 14 ++ .../System/String/IndexOf/Project.csproj | 8 + .../System/String/IndexOf/ignorable21.cs | 4 +- .../System/String/IndexOf/ignorable22.cs | 6 +- .../System/String/IndexOf/ignorable23.cs | 6 +- .../System/String/IndexOf/ignorable24.cs | 6 +- .../System/String/IndexOf/ignorable25.cs | 8 +- .../System/String/IndexOf/ignorable26.cs | 16 +- .../csharp/System/String/IndexOf/indexof_c.cs | 18 +- .../System/String/IndexOf/indexofcii.cs | 56 +++-- .../csharp/System/String/IndexOf/iocmp.cs | 123 ++++++----- .../csharp/System/String/IndexOf/ixof1.cs | 14 +- .../csharp/System/String/IndexOf/ixof8.cs | 16 +- .../csharp/System/String/IndexOf/simple1.cs | 11 +- .../System/String/IndexOf/stringindexof4.cs | 20 +- .../System/String/IndexOf/stringinsert.cs | 8 +- .../System/String/IndexOfAny/IndexOfAny1.cs | 26 +-- .../System/String/IndexOfAny/Program.cs | 10 +- .../csharp/System/String/Insert/Insert1.cs | 14 +- .../csharp/System/String/Intern/Intern1.cs | 20 +- .../System/String/Intern/string_intern.cs | 8 +- .../csharp/System/String/IsInterned/isin.cs | 12 +- .../System/String/IsInterned/isinternedex1.cs | 39 ++-- .../csharp/System/String/IsNormalized/norm.cs | 136 ++++++------ .../String/IsNullOrEmpty/NullString1.cs | 14 +- .../System/String/IsNullOrEmpty/inoe.cs | 38 ++-- .../String/IsNullOrWhiteSpace/Program.cs | 2 + .../String/IsNullOrWhiteSpace/Project.csproj | 8 + .../IsNullOrWhiteSpace/isnullorwhitespace.cs | 21 +- .../IsNullOrWhiteSpace/isnullorwhitespace1.cs | 20 +- snippets/csharp/System/String/Join/Program.cs | 7 + .../csharp/System/String/Join/Project.csproj | 8 + snippets/csharp/System/String/Join/join1.cs | 60 +++--- snippets/csharp/System/String/Join/join2.cs | 16 +- snippets/csharp/System/String/Join/join3.cs | 60 +++--- snippets/csharp/System/String/Join/join4.cs | 32 +-- snippets/csharp/System/String/Join/join5.cs | 47 ++-- snippets/csharp/System/String/Join/join6.cs | 60 +++--- .../csharp/System/String/Join/stringjoin.cs | 10 +- .../String/LastIndexOf/LastIndexOf_Example.cs | 84 ++++---- .../System/String/LastIndexOf/Program.cs | 13 ++ .../System/String/LastIndexOf/Project.csproj | 8 + .../String/LastIndexOf/lastindexof21.cs | 4 +- .../String/LastIndexOf/lastindexof22.cs | 4 +- .../String/LastIndexOf/lastindexof23.cs | 4 +- .../String/LastIndexOf/lastindexof24.cs | 4 +- .../String/LastIndexOf/lastindexof25.cs | 4 +- .../String/LastIndexOf/lastindexof26.cs | 4 +- .../LastIndexOf/lastindexof_example2.cs | 76 +++---- .../System/String/LastIndexOf/lastixof1.cs | 40 ++-- .../System/String/LastIndexOf/lastixof2.cs | 50 ++--- .../System/String/LastIndexOf/lastixof7.cs | 40 ++-- .../System/String/LastIndexOf/lastixof8.cs | 50 ++--- .../System/String/LastIndexOf/liocmp.cs | 121 ++++++----- .../System/String/LastIndexOfAny/Program.cs | 3 + .../String/LastIndexOfAny/Project.csproj | 8 + .../String/LastIndexOfAny/lastixany1.cs | 42 ++-- .../String/LastIndexOfAny/lastixany2.cs | 42 ++-- .../String/LastIndexOfAny/lastixany3.cs | 46 ++-- .../csharp/System/String/Length/length.cs | 6 +- .../String/Overview/System.String.Class.cs | 16 +- .../csharp/System/String/Overview/case1.cs | 84 ++++---- .../csharp/System/String/Overview/case2.cs | 47 ++-- .../System/String/Overview/compare11.cs | 12 +- .../csharp/System/String/Overview/compare2.cs | 79 ++++--- .../csharp/System/String/Overview/compare3.cs | 50 +++-- .../csharp/System/String/Overview/compare4.cs | 60 +++--- .../System/String/Overview/equality1.cs | 50 ++--- .../csharp/System/String/Overview/format1.cs | 21 +- .../System/String/Overview/grapheme1.cs | 41 ++-- .../System/String/Overview/immutable.cs | 31 +-- .../System/String/Overview/immutable1.cs | 29 +-- .../csharp/System/String/Overview/index11.cs | 36 ++-- .../csharp/System/String/Overview/index2.cs | 36 ++-- .../csharp/System/String/Overview/index3.cs | 140 ++++++------ .../System/String/Overview/normalize1.cs | 115 +++++----- .../System/String/Overview/nullorempty1.cs | 130 ++++++------ .../csharp/System/String/Overview/parse1.cs | 32 ++- .../csharp/System/String/Overview/program.cs | 200 +++++++++--------- .../csharp/System/String/Overview/search1.cs | 35 ++- .../csharp/System/String/Overview/sort1.cs | 62 +++--- .../System/String/Overview/surrogate1.cs | 27 ++- .../csharp/System/String/PadLeft/Program.cs | 2 + .../System/String/PadLeft/Project.csproj | 8 + .../csharp/System/String/PadLeft/source.cs | 14 +- .../csharp/System/String/PadLeft/source1.cs | 16 +- .../csharp/System/String/PadRight/Program.cs | 2 + .../System/String/PadRight/Project.csproj | 8 + .../csharp/System/String/PadRight/source.cs | 28 +-- .../csharp/System/String/PadRight/source1.cs | 20 +- snippets/csharp/System/String/Remove/r.cs | 6 +- .../System/String/Remove/stringremove.cs | 4 +- snippets/csharp/System/String/Split/basic.cs | 2 +- .../String/Split/compiler-resolution.cs | 2 +- snippets/csharp/System/String/Split/intro.cs | 8 +- snippets/csharp/System/String/Split/limit.cs | 2 +- .../csharp/System/String/Split/options.cs | 14 +- .../csharp/System/String/Split/program.cs | 10 +- .../System/String/StartsWith/Program.cs | 4 + .../System/String/StartsWith/Project.csproj | 8 + .../System/String/StartsWith/StartsWith2.cs | 26 +-- .../System/String/StartsWith/startswith1.cs | 43 ++-- .../String/StartsWith/stringstartswith.cs | 67 +++--- .../csharp/System/String/StartsWith/swci.cs | 104 ++++----- .../csharp/System/String/Substring/Program.cs | 6 + .../System/String/Substring/Project.csproj | 8 + .../System/String/Substring/Substring1.cs | 16 +- .../System/String/Substring/Substring10.cs | 16 +- .../System/String/Substring/Substring2.cs | 12 +- .../System/String/Substring/Substring3.cs | 14 +- .../System/String/Substring/Substring4.cs | 8 +- .../csharp/System/String/Substring/source.cs | 50 ++--- .../System/String/ToCharArray/ToCharArray1.cs | 22 +- .../System/String/ToCharArray/tocharry1.cs | 26 +-- .../System/String/ToLower/stringtolower.cs | 12 +- .../csharp/System/String/ToLower/tolower.cs | 68 +++--- .../ToLowerInvariant/tolowerinvariant.cs | 44 ++-- .../System/String/ToString/string.tostring.cs | 26 +-- .../csharp/System/String/ToUpper/Program.cs | 2 + .../System/String/ToUpper/Project.csproj | 8 + .../csharp/System/String/ToUpper/ToUpperEx.cs | 34 ++- .../csharp/System/String/ToUpper/toupper.cs | 35 ++- .../ToUpperInvariant/toupperinvariant.cs | 50 ++--- snippets/csharp/System/String/Trim/Program.cs | 2 + .../csharp/System/String/Trim/Project.csproj | 8 + snippets/csharp/System/String/Trim/Trim1.cs | 8 +- snippets/csharp/System/String/Trim/Trim2.cs | 19 +- .../csharp/System/String/TrimEnd/sample.cs | 8 +- .../csharp/System/String/TrimEnd/sample2.cs | 42 ++-- .../csharp/System/String/TrimStart/Program.cs | 2 + .../System/String/TrimStart/Project.csproj | 8 + .../csharp/System/String/TrimStart/sample.cs | 34 +-- .../System/String/op_Equality/equalityop.cs | 24 +-- .../String/op_Inequality/inequalityop.cs | 22 +- .../CurrentCulture/CompareObjects.cs | 54 ++--- .../System/StringComparer/Overview/omni.cs | 28 +-- 196 files changed, 2931 insertions(+), 2850 deletions(-) create mode 100644 snippets/csharp/System/String/CompareTo/Program.cs create mode 100644 snippets/csharp/System/String/CompareTo/Project.csproj create mode 100644 snippets/csharp/System/String/Concat/Program.cs create mode 100644 snippets/csharp/System/String/Concat/Project.csproj create mode 100644 snippets/csharp/System/String/EndsWith/Program.cs create mode 100644 snippets/csharp/System/String/EndsWith/Project.csproj create mode 100644 snippets/csharp/System/String/IndexOf/Program.cs create mode 100644 snippets/csharp/System/String/IndexOf/Project.csproj create mode 100644 snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs create mode 100644 snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj create mode 100644 snippets/csharp/System/String/Join/Program.cs create mode 100644 snippets/csharp/System/String/Join/Project.csproj create mode 100644 snippets/csharp/System/String/LastIndexOf/Program.cs create mode 100644 snippets/csharp/System/String/LastIndexOf/Project.csproj create mode 100644 snippets/csharp/System/String/LastIndexOfAny/Program.cs create mode 100644 snippets/csharp/System/String/LastIndexOfAny/Project.csproj create mode 100644 snippets/csharp/System/String/PadLeft/Program.cs create mode 100644 snippets/csharp/System/String/PadLeft/Project.csproj create mode 100644 snippets/csharp/System/String/PadRight/Program.cs create mode 100644 snippets/csharp/System/String/PadRight/Project.csproj create mode 100644 snippets/csharp/System/String/StartsWith/Program.cs create mode 100644 snippets/csharp/System/String/StartsWith/Project.csproj create mode 100644 snippets/csharp/System/String/Substring/Program.cs create mode 100644 snippets/csharp/System/String/Substring/Project.csproj create mode 100644 snippets/csharp/System/String/ToUpper/Program.cs create mode 100644 snippets/csharp/System/String/ToUpper/Project.csproj create mode 100644 snippets/csharp/System/String/Trim/Program.cs create mode 100644 snippets/csharp/System/String/Trim/Project.csproj create mode 100644 snippets/csharp/System/String/TrimStart/Program.cs create mode 100644 snippets/csharp/System/String/TrimStart/Project.csproj diff --git a/snippets/csharp/System/String/.ctor/char2_ctor.cs b/snippets/csharp/System/String/.ctor/char2_ctor.cs index ea152e7404d..15308e8a806 100644 --- a/snippets/csharp/System/String/.ctor/char2_ctor.cs +++ b/snippets/csharp/System/String/.ctor/char2_ctor.cs @@ -3,27 +3,28 @@ public class Example1 { - public static unsafe void Main() - { - char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', - 'w', 'o', 'r', 'l', 'd', '!', '\u0000' }; - String value; - - fixed (char* charPtr = characters) { - int length = 0; - Char* iterator = charPtr; - - while (*iterator != '\x0000') - { - if (*iterator == '!' || *iterator == '.') - break; - iterator++; - length++; - } - value = new String(charPtr, 0, length); - } - Console.WriteLine(value); - } + public static unsafe void Main() + { + char[] characters = [ 'H', 'e', 'l', 'l', 'o', ' ', + 'w', 'o', 'r', 'l', 'd', '!', '\u0000' ]; + string value; + + fixed (char* charPtr = characters) + { + int length = 0; + char* iterator = charPtr; + + while (*iterator != '\x0000') + { + if (*iterator == '!' || *iterator == '.') + break; + iterator++; + length++; + } + value = new(charPtr, 0, length); + } + Console.WriteLine(value); + } } // The example displays the following output: // Hello World diff --git a/snippets/csharp/System/String/.ctor/chptrctor_null.cs b/snippets/csharp/System/String/.ctor/chptrctor_null.cs index 41eb2e7fa08..1fe18ae543c 100644 --- a/snippets/csharp/System/String/.ctor/chptrctor_null.cs +++ b/snippets/csharp/System/String/.ctor/chptrctor_null.cs @@ -3,27 +3,29 @@ public class Example2 { - public unsafe static void Main() - { - char[] chars = { 'a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0' }; - string s = null; - - fixed(char* chPtr = chars) { - s = new string(chPtr, 0, chars.Length); - } + public unsafe static void Main() + { + char[] chars = ['a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0']; + string s = null; - foreach (var ch in s) - Console.Write($"{(ushort)ch:X4} "); - Console.WriteLine(); - - fixed(char* chPtr = chars) { - s = new string(chPtr); - } - - foreach (var ch in s) - Console.Write($"{(ushort)ch:X4} "); - Console.WriteLine(); - } + fixed (char* chPtr = chars) + { + s = new(chPtr, 0, chars.Length); + } + + foreach (char ch in s) + Console.Write($"{(ushort)ch:X4} "); + Console.WriteLine(); + + fixed (char* chPtr = chars) + { + s = new(chPtr); + } + + foreach (char ch in s) + Console.Write($"{(ushort)ch:X4} "); + Console.WriteLine(); + } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 diff --git a/snippets/csharp/System/String/.ctor/ctor1.cs b/snippets/csharp/System/String/.ctor/ctor1.cs index c3ff8a27bd1..c54fbceca92 100644 --- a/snippets/csharp/System/String/.ctor/ctor1.cs +++ b/snippets/csharp/System/String/.ctor/ctor1.cs @@ -3,13 +3,13 @@ public class Example3 { - public static void Main() - { - String value1 = "This is a string."; - String value2 = value1; - Console.WriteLine(value1); - Console.WriteLine(value2); - } + public static void Main() + { + string value1 = "This is a string."; + string value2 = value1; + Console.WriteLine(value1); + Console.WriteLine(value2); + } } // The example displays the following output: // This is a string. diff --git a/snippets/csharp/System/String/.ctor/ctor2.cs b/snippets/csharp/System/String/.ctor/ctor2.cs index b6e0d7f7885..51f35bd6b99 100644 --- a/snippets/csharp/System/String/.ctor/ctor2.cs +++ b/snippets/csharp/System/String/.ctor/ctor2.cs @@ -3,17 +3,18 @@ public class Example4 { - public static unsafe void Main() - { - char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', - 'w', 'o', 'r', 'l', 'd', '!', '\u0000' }; - string value; - - fixed (char* charPtr = characters) { - value = new String(charPtr); - } - Console.WriteLine(value); - } + public static unsafe void Main() + { + char[] characters = [ 'H', 'e', 'l', 'l', 'o', ' ', + 'w', 'o', 'r', 'l', 'd', '!', '\u0000' ]; + string value; + + fixed (char* charPtr = characters) + { + value = new(charPtr); + } + Console.WriteLine(value); + } } // The example displays the following output: // Hello world! diff --git a/snippets/csharp/System/String/.ctor/ptrctor_null.cs b/snippets/csharp/System/String/.ctor/ptrctor_null.cs index 7209113786f..a8bd9fbf4f8 100644 --- a/snippets/csharp/System/String/.ctor/ptrctor_null.cs +++ b/snippets/csharp/System/String/.ctor/ptrctor_null.cs @@ -3,28 +3,30 @@ public class Example5 { - public unsafe static void Main() - { - sbyte[] bytes = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42, 0x43, 0x44, 0x00 }; - - string s = null; - fixed (sbyte* bytePtr = bytes) { - s = new string(bytePtr, 0, bytes.Length); - } - - foreach (var ch in s) - Console.Write($"{(ushort)ch:X4} "); - - Console.WriteLine(); + public unsafe static void Main() + { + sbyte[] bytes = [0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42, 0x43, 0x44, 0x00]; - fixed(sbyte* bytePtr = bytes) { - s = new string(bytePtr); - } - - foreach (var ch in s) - Console.Write($"{(ushort)ch:X4} "); - Console.WriteLine(); - } + string s = null; + fixed (sbyte* bytePtr = bytes) + { + s = new(bytePtr, 0, bytes.Length); + } + + foreach (char ch in s) + Console.Write($"{(ushort)ch:X4} "); + + Console.WriteLine(); + + fixed (sbyte* bytePtr = bytes) + { + s = new(bytePtr); + } + + foreach (char ch in s) + Console.Write($"{(ushort)ch:X4} "); + Console.WriteLine(); + } } // The example displays the following output: // 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000 diff --git a/snippets/csharp/System/String/.ctor/source.cs b/snippets/csharp/System/String/.ctor/source.cs index 7eebd4e46d9..11c6449f472 100644 --- a/snippets/csharp/System/String/.ctor/source.cs +++ b/snippets/csharp/System/String/.ctor/source.cs @@ -8,56 +8,56 @@ class ConsoleApp [STAThread] static void Main(string[] args) { -// + // // Unicode Mathematical operators - char [] charArr1 = {'\u2200','\u2202','\u200F','\u2205'}; - String szMathSymbols = new String(charArr1); + char[] charArr1 = ['\u2200', '\u2202', '\u200F', '\u2205']; + string szMathSymbols = new(charArr1); // Unicode Letterlike Symbols - char [] charArr2 = {'\u2111','\u2118','\u2122','\u2126'}; - String szLetterLike = new String (charArr2); + char[] charArr2 = ['\u2111', '\u2118', '\u2122', '\u2126']; + string szLetterLike = new(charArr2); // Compare Strings - the result is false Console.WriteLine("The Strings are equal? " + - (String.Compare(szMathSymbols, szLetterLike)==0?"true":"false") ); -// -// + (string.Compare(szMathSymbols, szLetterLike) == 0 ? "true" : "false")); + // + // unsafe { // Null terminated ASCII characters in an sbyte array - String szAsciiUpper = null; - sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 }; + string szAsciiUpper = null; + sbyte[] sbArr1 = [0x41, 0x42, 0x43, 0x00]; // Instruct the Garbage Collector not to move the memory - fixed(sbyte* pAsciiUpper = sbArr1) + fixed (sbyte* pAsciiUpper = sbArr1) { - szAsciiUpper = new String(pAsciiUpper); + szAsciiUpper = new(pAsciiUpper); } - String szAsciiLower = null; - sbyte[] sbArr2 = { 0x61, 0x62, 0x63, 0x00 }; + string szAsciiLower = null; + sbyte[] sbArr2 = [0x61, 0x62, 0x63, 0x00]; // Instruct the Garbage Collector not to move the memory - fixed(sbyte* pAsciiLower = sbArr2) + fixed (sbyte* pAsciiLower = sbArr2) { - szAsciiLower = new String(pAsciiLower, 0, sbArr2.Length); + szAsciiLower = new(pAsciiLower, 0, sbArr2.Length); } // Prints "ABC abc" Console.WriteLine(szAsciiUpper + " " + szAsciiLower); // Compare Strings - the result is true Console.WriteLine("The Strings are equal when capitalized ? " + - (String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper())==0?"true":"false") ); + (string.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper()) == 0 ? "true" : "false")); // This is the effective equivalent of another Compare method, which ignores case Console.WriteLine("The Strings are equal when capitalized ? " + - (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") ); + (string.Compare(szAsciiUpper, szAsciiLower, true) == 0 ? "true" : "false")); } -// -// + // + // // Create a Unicode String with 5 Greek Alpha characters - String szGreekAlpha = new String('\u0391',5); + string szGreekAlpha = new('\u0391', 5); // Create a Unicode String with a Greek Omega character - String szGreekOmega = new String(new char [] {'\u03A9','\u03A9','\u03A9'},2,1); + string szGreekOmega = new(['\u03A9', '\u03A9', '\u03A9'], 2, 1); - String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone()); + string szGreekLetters = string.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone()); // Examine the result Console.WriteLine(szGreekLetters); @@ -69,23 +69,23 @@ static void Main(string[] args) Console.WriteLine("The Greek letter Alpha first appears at index " + ialpha + " and Omega last appears at index " + iomega + " in this String."); -// + // -// + // unsafe { - String utfeightstring = null; - sbyte [] asciiChars = new sbyte[] { 0x51,0x52,0x53,0x54,0x54,0x56 }; - UTF8Encoding encoding = new UTF8Encoding(true, true); + string utfeightstring = null; + sbyte[] asciiChars = [0x51, 0x52, 0x53, 0x54, 0x54, 0x56]; + UTF8Encoding encoding = new(true, true); // Instruct the Garbage Collector not to move the memory - fixed(sbyte* pAsciiChars = asciiChars) + fixed (sbyte* pAsciiChars = asciiChars) { - utfeightstring = new String(pAsciiChars,0,asciiChars.Length,encoding); + utfeightstring = new(pAsciiChars, 0, asciiChars.Length, encoding); } - Console.WriteLine("The UTF8 String is " + utfeightstring ); // prints "QRSTTV" + Console.WriteLine("The UTF8 String is " + utfeightstring); // prints "QRSTTV" } -// + // } } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/String/Chars/chars1.cs b/snippets/csharp/System/String/Chars/chars1.cs index 12081f2f6e9..65459d62154 100644 --- a/snippets/csharp/System/String/Chars/chars1.cs +++ b/snippets/csharp/System/String/Chars/chars1.cs @@ -2,14 +2,14 @@ public class Example { - public static void Main() - { - // - string str1 = "Test"; - for (int ctr = 0; ctr <= str1.Length - 1; ctr++ ) - Console.Write("{0} ", str1[ctr]); - // The example displays the following output: - // T e s t - // - } + public static void Main() + { + // + string str1 = "Test"; + for (int ctr = 0; ctr <= str1.Length - 1; ctr++) + Console.Write($"{str1[ctr]} "); + // The example displays the following output: + // T e s t + // + } } diff --git a/snippets/csharp/System/String/Chars/uri_ishexdigit.cs b/snippets/csharp/System/String/Chars/uri_ishexdigit.cs index 443ed53ec1b..2bc8b71c248 100644 --- a/snippets/csharp/System/String/Chars/uri_ishexdigit.cs +++ b/snippets/csharp/System/String/Chars/uri_ishexdigit.cs @@ -8,18 +8,18 @@ specified character is valid hexadecimal digit. using System; class MyIsHexDigitSample { - public static void Main() - { - try - { + public static void Main() + { + try + { // - Console.Write("Type a string : "); - string myString = Console.ReadLine(); - for (int i = 0; i < myString.Length; i ++) - if(Uri.IsHexDigit(myString[i])) - Console.WriteLine("{0} is a hexadecimal digit.", myString[i]); - else - Console.WriteLine("{0} is not a hexadecimal digit.", myString[i]); + Console.Write("Type a string : "); + string myString = Console.ReadLine(); + for (int i = 0; i < myString.Length; i++) + if (Uri.IsHexDigit(myString[i])) + Console.WriteLine($"{myString[i]} is a hexadecimal digit."); + else + Console.WriteLine($"{myString[i]} is not a hexadecimal digit."); // The example produces output like the following: // Type a string : 3f5EaZ // 3 is a hexadecimal digit. @@ -29,14 +29,14 @@ public static void Main() // a is a hexadecimal digit. // Z is not a hexadecimal digit. // - } - catch(Exception e) - { - Console.WriteLine(e.Message); - } - } + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } } // ***** Output ***** /* -*/ \ No newline at end of file +*/ diff --git a/snippets/csharp/System/String/Compare/ArrayListSample.cs b/snippets/csharp/System/String/Compare/ArrayListSample.cs index d85c1ff9a0d..acf6be7feda 100644 --- a/snippets/csharp/System/String/Compare/ArrayListSample.cs +++ b/snippets/csharp/System/String/Compare/ArrayListSample.cs @@ -1,7 +1,7 @@ // using System; -using System.Text; using System.Collections; +using System.Text; public class SamplesArrayList { @@ -10,20 +10,22 @@ public static void Main() { // // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("Eric"); - myAL.Add("Mark"); - myAL.Add("Lance"); - myAL.Add("Rob"); - myAL.Add("Kris"); - myAL.Add("Brad"); - myAL.Add("Kit"); - myAL.Add("Bradley"); - myAL.Add("Keith"); - myAL.Add("Susan"); + ArrayList myAL = new ArrayList() + { + "Eric", + "Mark", + "Lance", + "Rob", + "Kris", + "Brad", + "Kit", + "Bradley", + "Keith", + "Susan" + }; // Displays the properties and values of the ArrayList. - Console.WriteLine("Count: {0}", myAL.Count); + Console.WriteLine($"Count: {myAL.Count}"); // PrintValues("Unsorted", myAL); @@ -43,7 +45,7 @@ public static void Main() // public static void PrintValues(string title, IEnumerable myList) { - Console.Write("{0,10}: ", title); + Console.Write($"{title,10}: "); StringBuilder sb = new StringBuilder(); foreach (string s in myList) { @@ -62,7 +64,7 @@ public int Compare(object? x, object? y) string? s1 = x as string; string? s2 = y as string; //negate the return value to get the reverse order - return -String.Compare(s1, s2); + return -string.Compare(s1, s2); } } // diff --git a/snippets/csharp/System/String/Compare/Compare18.cs b/snippets/csharp/System/String/Compare/Compare18.cs index d570605d221..e10c4b7a483 100644 --- a/snippets/csharp/System/String/Compare/Compare18.cs +++ b/snippets/csharp/System/String/Compare/Compare18.cs @@ -5,19 +5,16 @@ public class Example18 public static void Main() { // - String s1, s2; + string s1, s2; s1 = "car"; s2 = "Car"; - Console.WriteLine("'{0}' and '{1}': {2}", s1, s2, - String.Compare(s1, s2)); - - s1 = "fork"; s2 = "forks"; - Console.WriteLine("'{0}' and '{1}': {2}", s1, s2, - String.Compare(s1, s2)); + Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}"); + + s1 = "fork"; s2 = "forks"; + Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}"); s1 = "mammal"; s2 = "fish"; - Console.WriteLine("'{0}' and '{1}': {2}", s1, s2, - String.Compare(s1, s2)); + Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}"); // The example displays the following output: // 'car' and 'Car': -1 diff --git a/snippets/csharp/System/String/Compare/Example.cs b/snippets/csharp/System/String/Compare/Example.cs index f2a50dead54..b80d4d96cfd 100644 --- a/snippets/csharp/System/String/Compare/Example.cs +++ b/snippets/csharp/System/String/Compare/Example.cs @@ -12,7 +12,7 @@ public static void Main() int result; // Cultural (linguistic) comparison. - result = String.Compare(string1, string2, new CultureInfo("en-US"), + result = string.Compare(string1, string2, new CultureInfo("en-US"), CompareOptions.None); if (result > 0) relation = "comes after"; @@ -21,11 +21,10 @@ public static void Main() else relation = "comes before"; - Console.WriteLine("'{0}' {1} '{2}'.", - string1, relation, string2); + Console.WriteLine($"'{string1}' {relation} '{string2}'."); // Cultural (linguistic) case-insensitive comparison. - result = String.Compare(string1, string2, new CultureInfo("en-US"), + result = string.Compare(string1, string2, new CultureInfo("en-US"), CompareOptions.IgnoreCase); if (result > 0) relation = "comes after"; @@ -34,11 +33,10 @@ public static void Main() else relation = "comes before"; - Console.WriteLine("'{0}' {1} '{2}'.", - string1, relation, string2); - + Console.WriteLine($"'{string1}' {relation} '{string2}'."); + // Culture-insensitive ordinal comparison. - result = String.CompareOrdinal(string1, string2); + result = string.CompareOrdinal(string1, string2); if (result > 0) relation = "comes after"; else if (result == 0) @@ -46,11 +44,10 @@ public static void Main() else relation = "comes before"; - Console.WriteLine("'{0}' {1} '{2}'.", - string1, relation, string2); + Console.WriteLine($"'{string1}' {relation} '{string2}'."); // The example produces the following output: - // 'brother' comes before 'Brother'. + // 'brother' comes before 'Brother'. // 'brother' is the same as 'Brother'. // 'brother' comes after 'Brother'. } diff --git a/snippets/csharp/System/String/Compare/Example1.cs b/snippets/csharp/System/String/Compare/Example1.cs index c70346e32dd..4208632f68c 100644 --- a/snippets/csharp/System/String/Compare/Example1.cs +++ b/snippets/csharp/System/String/Compare/Example1.cs @@ -19,11 +19,11 @@ public static void Main() int length = Math.Max(name1.Length, name2.Length); Console.WriteLine("Sorted alphabetically by last name:"); - if (String.Compare(name1, index1, name2, index2, length, + if (string.Compare(name1, index1, name2, index2, length, new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0) - Console.WriteLine("{0}\n{1}", name1, name2); + Console.WriteLine($"{name1}\n{name2}"); else - Console.WriteLine("{0}\n{1}", name2, name1); + Console.WriteLine($"{name2}\n{name1}"); // The example displays the following output: // Sorted alphabetically by last name: diff --git a/snippets/csharp/System/String/Compare/cmpcmp.cs b/snippets/csharp/System/String/Compare/cmpcmp.cs index e1326d072a9..a862ef2ff26 100644 --- a/snippets/csharp/System/String/Compare/cmpcmp.cs +++ b/snippets/csharp/System/String/Compare/cmpcmp.cs @@ -1,20 +1,20 @@ // -// This example demonstrates the +// This example demonstrates the // System.String.Compare(String, String, StringComparison) method. using System; using System.Threading; -class Sample +class Sample { - public static void Main() + public static void Main() { - string intro = "Compare three versions of the letter I using different " + + string intro = "Compare three versions of the letter I using different " + "values of StringComparison."; - // Define an array of strings where each element contains a version of the - // letter I. (An array of strings is used so you can easily modify this - // code example to test additional or different combinations of strings.) + // Define an array of strings where each element contains a version of the + // letter I. (An array of strings is used so you can easily modify this + // code example to test additional or different combinations of strings.) string[] threeIs = new string[3]; // LATIN SMALL LETTER I (U+0069) @@ -24,10 +24,10 @@ public static void Main() // LATIN CAPITAL LETTER I (U+0049) threeIs[2] = "\u0049"; - string[] unicodeNames = + string[] unicodeNames = { - "LATIN SMALL LETTER I (U+0069)", - "LATIN SMALL LETTER DOTLESS I (U+0131)", + "LATIN SMALL LETTER I (U+0069)", + "LATIN SMALL LETTER DOTLESS I (U+0131)", "LATIN CAPITAL LETTER I (U+0049)" }; @@ -46,13 +46,12 @@ public static void Main() // Display the current culture because the culture-specific comparisons // can produce different results with different cultures. - Console.WriteLine( - "The current culture is {0}.\n", Thread.CurrentThread.CurrentCulture.Name); + Console.WriteLine($"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n"); - // Determine the relative sort order of three versions of the letter I. + // Determine the relative sort order of three versions of the letter I. foreach (StringComparison sc in scValues) { - Console.WriteLine("StringComparison.{0}:", sc); + Console.WriteLine($"StringComparison.{sc}:"); // LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131) Test(0, 1, sc, threeIs, unicodeNames); @@ -74,7 +73,7 @@ protected static void Test( string result = "equal to"; int cmpValue = 0; - cmpValue = String.Compare(testI[x], testI[y], comparison); + cmpValue = string.Compare(testI[x], testI[y], comparison); if (cmpValue < 0) result = "less than"; else if (cmpValue > 0) diff --git a/snippets/csharp/System/String/Compare/comp3.cs b/snippets/csharp/System/String/Compare/comp3.cs index 89664c5dc38..7cef9a0f887 100644 --- a/snippets/csharp/System/String/Compare/comp3.cs +++ b/snippets/csharp/System/String/Compare/comp3.cs @@ -6,18 +6,18 @@ class Sample3 public static void Main() { // - String str1 = "machine"; - String str2 = "device"; - String str; + string str1 = "machine"; + string str2 = "device"; + string str; int result; Console.WriteLine(); - Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); - result = String.Compare(str1, 2, str2, 0, 2); + Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'"); + result = string.Compare(str1, 2, str2, 0, 2); str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1); - Console.Write("{0} ", str); - Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2); + Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"substring '{str2.Substring(0, 2)}' in '{str2}'."); /* This example produces the following results: diff --git a/snippets/csharp/System/String/Compare/comp4.cs b/snippets/csharp/System/String/Compare/comp4.cs index d803d385a27..29d2db41492 100644 --- a/snippets/csharp/System/String/Compare/comp4.cs +++ b/snippets/csharp/System/String/Compare/comp4.cs @@ -6,28 +6,28 @@ class Sample4 public static void Main() { // - String str1 = "MACHINE"; - String str2 = "machine"; - String str; + string str1 = "MACHINE"; + string str2 = "machine"; + string str; int result; Console.WriteLine(); - Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); + Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'"); Console.WriteLine("Ignore case:"); - result = String.Compare(str1, 2, str2, 2, 2, true); + result = string.Compare(str1, 2, str2, 2, 2, true); str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1); - Console.Write("{0} ", str); - Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2); + Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"substring '{str2.Substring(2, 2)}' in '{str2}'."); Console.WriteLine(); Console.WriteLine("Honor case:"); - result = String.Compare(str1, 2, str2, 2, 2, false); + result = string.Compare(str1, 2, str2, 2, 2, false); str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1); - Console.Write("{0} ", str); - Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2); + Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"substring '{str2.Substring(2, 2)}' in '{str2}'."); /* This example produces the following results: diff --git a/snippets/csharp/System/String/Compare/comp5.cs b/snippets/csharp/System/String/Compare/comp5.cs index dbfc689f393..7b63b5266dc 100644 --- a/snippets/csharp/System/String/Compare/comp5.cs +++ b/snippets/csharp/System/String/Compare/comp5.cs @@ -8,27 +8,27 @@ class Sample5 public static void Main() { // 0123456 - String str1 = "MACHINE"; - String str2 = "machine"; - String str; + string str1 = "MACHINE"; + string str2 = "machine"; + string str; int result; Console.WriteLine(); - Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); + Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'"); Console.WriteLine("Ignore case, Turkish culture:"); - result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR")); + result = string.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR")); str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1); - Console.Write("{0} ", str); - Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2); + Console.Write($"Substring '{str1.Substring(4, 2)}' in '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"substring '{str2.Substring(4, 2)}' in '{str2}'."); Console.WriteLine(); Console.WriteLine("Ignore case, invariant culture:"); - result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture); + result = string.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture); str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1); - Console.Write("{0} ", str); - Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2); + Console.Write($"Substring '{str1.Substring(4, 2)}' in '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"substring '{str2.Substring(4, 2)}' in '{str2}'."); } } /* diff --git a/snippets/csharp/System/String/Compare/compare02.cs b/snippets/csharp/System/String/Compare/compare02.cs index d9335e5a87d..4492e2bbbba 100644 --- a/snippets/csharp/System/String/Compare/compare02.cs +++ b/snippets/csharp/System/String/Compare/compare02.cs @@ -6,24 +6,19 @@ static void Main() { // // Create upper-case characters from their Unicode code units. - String stringUpper = "\x0041\x0042\x0043"; + string stringUpper = "\x0041\x0042\x0043"; // Create lower-case characters from their Unicode code units. - String stringLower = "\x0061\x0062\x0063"; + string stringLower = "\x0061\x0062\x0063"; // Display the strings. - Console.WriteLine("Comparing '{0}' and '{1}':", - stringUpper, stringLower); + Console.WriteLine($"Comparing '{stringUpper}' and '{stringLower}':"); // Compare the uppercased strings; the result is true. - Console.WriteLine("The Strings are equal when capitalized? {0}", - String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0 - ? "true" : "false"); + Console.WriteLine($"The Strings are equal when capitalized? {(string.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0 ? "true" : "false")}"); // The previous method call is equivalent to this Compare method, which ignores case. - Console.WriteLine("The Strings are equal when case is ignored? {0}", - String.Compare(stringUpper, stringLower, true) == 0 - ? "true" : "false" ); + Console.WriteLine($"The Strings are equal when case is ignored? {(string.Compare(stringUpper, stringLower, true) == 0 ? "true" : "false")}"); // The example displays the following output: // Comparing 'ABC' and 'abc': diff --git a/snippets/csharp/System/String/Compare/compare21.cs b/snippets/csharp/System/String/Compare/compare21.cs index d121700e920..d98cd894d54 100644 --- a/snippets/csharp/System/String/Compare/compare21.cs +++ b/snippets/csharp/System/String/Compare/compare21.cs @@ -8,8 +8,7 @@ public static void Main() string s1 = "ani\u00ADmal"; string s2 = "animal"; - Console.WriteLine("Comparison of '{0}' and '{1}': {2}", - s1, s2, String.Compare(s1, s2)); + Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2)}"); // The example displays the following output: // Comparison of 'ani-mal' and 'animal': 0 diff --git a/snippets/csharp/System/String/Compare/compare22.cs b/snippets/csharp/System/String/Compare/compare22.cs index f13a647852a..7151355a03e 100644 --- a/snippets/csharp/System/String/Compare/compare22.cs +++ b/snippets/csharp/System/String/Compare/compare22.cs @@ -8,8 +8,7 @@ public static void Main() string s1 = "Ani\u00ADmal"; string s2 = "animal"; - Console.WriteLine("Comparison of '{0}' and '{1}': {2}", - s1, s2, String.Compare(s1, s2, true)); + Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2, true)}"); // The example displays the following output: // Comparison of 'Ani-mal' and 'animal': 0 diff --git a/snippets/csharp/System/String/Compare/compare23.cs b/snippets/csharp/System/String/Compare/compare23.cs index 43f6d172e58..f110fe34f96 100644 --- a/snippets/csharp/System/String/Compare/compare23.cs +++ b/snippets/csharp/System/String/Compare/compare23.cs @@ -8,10 +8,8 @@ public static void Main() // string s1 = "Ani\u00ADmal"; string s2 = "animal"; - - Console.WriteLine("Comparison of '{0}' and '{1}': {2}", - s1, s2, String.Compare(s1, s2, true, - CultureInfo.InvariantCulture)); + + Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2, true, CultureInfo.InvariantCulture)}"); // The example displays the following output: // Comparison of 'Ani-mal' and 'animal': 0 diff --git a/snippets/csharp/System/String/Compare/remarks.cs b/snippets/csharp/System/String/Compare/remarks.cs index 54a9ce78435..4ecab74e919 100644 --- a/snippets/csharp/System/String/Compare/remarks.cs +++ b/snippets/csharp/System/String/Compare/remarks.cs @@ -1,22 +1,16 @@ using System; -using System.Globalization; + public class Remarks { - public static void Main() - { - Console.WriteLine("Hi!"); - } + public static void Main() => Console.WriteLine("Hi!"); } // System.String.Compare(System.String,System.Int32,System.String,System.Int32,System.Int32) public class CompareSample1_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -24,10 +18,7 @@ static bool IsFileURI(String path) public class CompareSample1_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -35,10 +26,7 @@ static bool IsFileURI(String path) public class CompareSample2_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -46,10 +34,7 @@ static bool IsFileURI(String path) public class CompareSample2_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -58,10 +43,7 @@ static bool IsFileURI(String path) public class CompareSample3_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -70,10 +52,7 @@ static bool IsFileURI(String path) public class CompareSample3_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -82,10 +61,7 @@ static bool IsFileURI(String path) public class CompareSample4_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -94,10 +70,7 @@ static bool IsFileURI(String path) public class CompareSample4_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -105,10 +78,7 @@ static bool IsFileURI(String path) public class CompareSample5_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -116,10 +86,7 @@ static bool IsFileURI(String path) public class CompareSample5_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -127,10 +94,7 @@ static bool IsFileURI(String path) public class CompareSample6_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -138,10 +102,7 @@ static bool IsFileURI(String path) public class CompareSample6_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -149,10 +110,7 @@ static bool IsFileURI(String path) public class CompareSample7_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -160,10 +118,7 @@ static bool IsFileURI(String path) public class CompareSample7_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } @@ -171,10 +126,7 @@ static bool IsFileURI(String path) public class CompareSample8_1 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, true) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0); // } @@ -182,9 +134,6 @@ static bool IsFileURI(String path) public class CompareSample8_2 { // - static bool IsFileURI(String path) - { - return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); - } + static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0); // } diff --git a/snippets/csharp/System/String/Compare/string.comp4.cs b/snippets/csharp/System/String/Compare/string.comp4.cs index 27c263c562f..1715fdc11a6 100644 --- a/snippets/csharp/System/String/Compare/string.comp4.cs +++ b/snippets/csharp/System/String/Compare/string.comp4.cs @@ -6,20 +6,20 @@ class Sample0 // public static void Main() { - String str1 = "change"; - String str2 = "dollar"; - String relation; + string str1 = "change"; + string str2 = "dollar"; + string relation; - relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US"))); - Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2); + relation = symbol(string.Compare(str1, str2, false, new CultureInfo("en-US"))); + Console.WriteLine($"For en-US: {str1} {relation} {str2}"); - relation = symbol(String.Compare(str1, str2, false, new CultureInfo("cs-CZ"))); - Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2); + relation = symbol(string.Compare(str1, str2, false, new CultureInfo("cs-CZ"))); + Console.WriteLine($"For cs-CZ: {str1} {relation} {str2}"); } - private static String symbol(int r) + private static string symbol(int r) { - String s = "="; + string s = "="; if (r < 0) s = "<"; else if (r > 0) s = ">"; return s; diff --git a/snippets/csharp/System/String/CompareOrdinal/comp0.cs b/snippets/csharp/System/String/CompareOrdinal/comp0.cs index b0aa972322a..e7355ed29c1 100644 --- a/snippets/csharp/System/String/CompareOrdinal/comp0.cs +++ b/snippets/csharp/System/String/CompareOrdinal/comp0.cs @@ -2,21 +2,23 @@ // Sample for String.CompareOrdinal(String, String) using System; -class Sample { - public static void Main() { - String str1 = "ABCD"; - String str2 = "abcd"; - String str; - int result; +class Sample +{ + public static void Main() + { + string str1 = "ABCD"; + string str2 = "abcd"; + string str; + int result; - Console.WriteLine(); - Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string."); - Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); - result = String.CompareOrdinal(str1, str2); - str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); - Console.Write("String '{0}' is ", str1); - Console.Write("{0} ", str); - Console.WriteLine("String '{0}'.", str2); + Console.WriteLine(); + Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string."); + Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'"); + result = string.CompareOrdinal(str1, str2); + str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to")); + Console.Write($"String '{str1}' is "); + Console.Write($"{str} "); + Console.WriteLine($"String '{str2}'."); } } /* @@ -26,4 +28,4 @@ Compare the numeric values of the corresponding Char objects in each string. str1 = 'ABCD', str2 = 'abcd' String 'ABCD' is less than String 'abcd'. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs b/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs index 4f7777b9761..beee0b53fc2 100644 --- a/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs +++ b/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs @@ -4,27 +4,27 @@ class Test { - public static void Main(String[] args) - { - String strLow = "abc"; - String strCap = "ABC"; - String result = "equal to "; - int x = 0; - int pos = 1; + public static void Main(string[] args) + { + string strLow = "abc"; + string strCap = "ABC"; + string result = "equal to "; + int x = 0; + int pos = 1; -// The Unicode codepoint for 'b' is greater than the codepoint for 'B'. - x = String.CompareOrdinal(strLow, pos, strCap, pos, 1); - if (x < 0) result = "less than"; - if (x > 0) result = "greater than"; - Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos); - Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]); + // The Unicode codepoint for 'b' is greater than the codepoint for 'B'. + x = string.CompareOrdinal(strLow, pos, strCap, pos, 1); + if (x < 0) result = "less than"; + if (x > 0) result = "greater than"; + Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos); + Console.WriteLine($" '{strLow[pos]}' is {result} '{strCap[pos]}'"); -// In U.S. English culture, 'b' is linguistically less than 'B'. - x = String.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US")); - if (x < 0) result = "less than"; - else if (x > 0) result = "greater than"; - Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos); - Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]); - } + // In U.S. English culture, 'b' is linguistically less than 'B'. + x = string.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US")); + if (x < 0) result = "less than"; + else if (x > 0) result = "greater than"; + Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos); + Console.WriteLine($" '{strLow[pos]}' is {result} '{strCap[pos]}'"); + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/CompareTo/Program.cs b/snippets/csharp/System/String/CompareTo/Program.cs new file mode 100644 index 00000000000..93f10cb2416 --- /dev/null +++ b/snippets/csharp/System/String/CompareTo/Program.cs @@ -0,0 +1,4 @@ +Example.Run(); +CompareToStringExample.Run(); +CompareToObjectExample.Run(); +CompareStringsExample.Run(); diff --git a/snippets/csharp/System/String/CompareTo/Project.csproj b/snippets/csharp/System/String/CompareTo/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/CompareTo/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/CompareTo/compareto1.cs b/snippets/csharp/System/String/CompareTo/compareto1.cs index 31bd2bce666..1100bd72a7c 100644 --- a/snippets/csharp/System/String/CompareTo/compareto1.cs +++ b/snippets/csharp/System/String/CompareTo/compareto1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - string s1 = "ani\u00ADmal"; - object o1 = "animal"; - - Console.WriteLine("Comparison of '{0}' and '{1}': {2}", - s1, o1, s1.CompareTo(o1)); - } + public static void Run() + { + string s1 = "ani\u00ADmal"; + object o1 = "animal"; + + Console.WriteLine($"Comparison of '{s1}' and '{o1}': {s1.CompareTo(o1)}"); + } } // The example displays the following output: // Comparison of 'ani-mal' and 'animal': 0 diff --git a/snippets/csharp/System/String/CompareTo/compareto2.cs b/snippets/csharp/System/String/CompareTo/compareto2.cs index e45f43f1359..85e8a397519 100644 --- a/snippets/csharp/System/String/CompareTo/compareto2.cs +++ b/snippets/csharp/System/String/CompareTo/compareto2.cs @@ -1,16 +1,15 @@ // using System; -public class Example +public class CompareToStringExample { - public static void Main() - { - string s1 = "ani\u00ADmal"; - string s2 = "animal"; - - Console.WriteLine("Comparison of '{0}' and '{1}': {2}", - s1, s2, s1.CompareTo(s2)); - } + public static void Run() + { + string s1 = "ani\u00ADmal"; + string s2 = "animal"; + + Console.WriteLine($"Comparison of '{s1}' and '{s2}': {s1.CompareTo(s2)}"); + } } // The example displays the following output: // Comparison of 'ani-mal' and 'animal': 0 diff --git a/snippets/csharp/System/String/CompareTo/extostring.cs b/snippets/csharp/System/String/CompareTo/extostring.cs index 625e49d9362..4fa5ee468fc 100644 --- a/snippets/csharp/System/String/CompareTo/extostring.cs +++ b/snippets/csharp/System/String/CompareTo/extostring.cs @@ -2,30 +2,30 @@ using System; public class TestClass -{} +{ } -public class Example +public class CompareToObjectExample { - public static void Main() - { - var test = new TestClass(); - Object[] objectsToCompare = { test, test.ToString(), 123, + public static void Run() + { + var test = new TestClass(); + object[] objectsToCompare = [ test, test.ToString(), 123, 123.ToString(), "some text", - "Some Text" }; - string s = "some text"; - foreach (var objectToCompare in objectsToCompare) { - try { - int i = s.CompareTo(objectToCompare); - Console.WriteLine("Comparing '{0}' with '{1}': {2}", - s, objectToCompare, i); - } - catch (ArgumentException) { - Console.WriteLine("Bad argument: {0} (type {1})", - objectToCompare, - objectToCompare.GetType().Name); - } - } - } + "Some Text" ]; + string s = "some text"; + foreach (object objectToCompare in objectsToCompare) + { + try + { + int i = s.CompareTo(objectToCompare); + Console.WriteLine($"Comparing '{s}' with '{objectToCompare}': {i}"); + } + catch (ArgumentException) + { + Console.WriteLine($"Bad argument: {objectToCompare} (type {objectToCompare.GetType().Name})"); + } + } + } } // The example displays the following output: // Bad argument: TestClass (type TestClass) @@ -34,4 +34,4 @@ public static void Main() // Comparing 'some text' with '123': 1 // Comparing 'some text' with 'some text': 0 // Comparing 'some text' with 'Some Text': -1 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/CompareTo/stringcompareto.cs b/snippets/csharp/System/String/CompareTo/stringcompareto.cs index 2bce361d198..a03dc7fb675 100644 --- a/snippets/csharp/System/String/CompareTo/stringcompareto.cs +++ b/snippets/csharp/System/String/CompareTo/stringcompareto.cs @@ -1,37 +1,37 @@ // using System; -public class Example +public class CompareStringsExample { - public static void Main() - { - string strFirst = "Goodbye"; - string strSecond = "Hello"; - string strThird = "a small string"; - string strFourth = "goodbye"; + public static void Run() + { + string strFirst = "Goodbye"; + string strSecond = "Hello"; + string strThird = "a small string"; + string strFourth = "goodbye"; - // Compare a string to itself. - Console.WriteLine(CompareStrings(strFirst, strFirst)); + // Compare a string to itself. + Console.WriteLine(CompareStrings(strFirst, strFirst)); - Console.WriteLine(CompareStrings(strFirst, strSecond)); - Console.WriteLine(CompareStrings(strFirst, strThird)); + Console.WriteLine(CompareStrings(strFirst, strSecond)); + Console.WriteLine(CompareStrings(strFirst, strThird)); - // Compare a string to another string that varies only by case. - Console.WriteLine(CompareStrings(strFirst, strFourth)); - Console.WriteLine(CompareStrings(strFourth, strFirst)); - } + // Compare a string to another string that varies only by case. + Console.WriteLine(CompareStrings(strFirst, strFourth)); + Console.WriteLine(CompareStrings(strFourth, strFirst)); + } - private static string CompareStrings( string str1, string str2 ) - { - // Compare the values, using the CompareTo method on the first string. - int cmpVal = str1.CompareTo(str2); + private static string CompareStrings(string str1, string str2) + { + // Compare the values, using the CompareTo method on the first string. + int cmpVal = str1.CompareTo(str2); - if (cmpVal == 0) // The strings are the same. - return "The strings occur in the same position in the sort order."; - else if (cmpVal < 0) - return "The first string precedes the second in the sort order."; - else - return "The first string follows the second in the sort order."; + if (cmpVal == 0) // The strings are the same. + return "The strings occur in the same position in the sort order."; + else if (cmpVal < 0) + return "The first string precedes the second in the sort order."; + else + return "The first string follows the second in the sort order."; } } // The example displays the following output: diff --git a/snippets/csharp/System/String/Concat/Concat6.cs b/snippets/csharp/System/String/Concat/Concat6.cs index b8a0afb05fb..921272ddc85 100644 --- a/snippets/csharp/System/String/Concat/Concat6.cs +++ b/snippets/csharp/System/String/Concat/Concat6.cs @@ -1,18 +1,18 @@ // using System; -public class Example +public class ConcatThreeStringsExample { - public static void Main() - { - String s1 = "We went to a bookstore, "; - String s2 = "a movie, "; - String s3 = "and a restaurant."; + public static void Run() + { + string s1 = "We went to a bookstore, "; + string s2 = "a movie, "; + string s3 = "and a restaurant."; - var s = String.Concat(s1, s2, s3); - Console.WriteLine(s); - } + string s = string.Concat(s1, s2, s3); + Console.WriteLine(s); + } } // The example displays the following output: -// We went to a bookstore, a movie, and a restaurant. +// We went to a bookstore, a movie, and a restaurant. // diff --git a/snippets/csharp/System/String/Concat/Program.cs b/snippets/csharp/System/String/Concat/Program.cs new file mode 100644 index 00000000000..fed8c0cab85 --- /dev/null +++ b/snippets/csharp/System/String/Concat/Program.cs @@ -0,0 +1,9 @@ +Example.Run(); +ConcatAlphabetExample.Run(); +ConcatAnimalsExample.Run(); +ConcatScrambleExample.Run(); +ConcatThreeStringsExample.Run(); +stringConcat5.Run(); +ConcatTest.Run(); +ConcatArrayExample.Run(); +ConcatNamesTest.Run(); diff --git a/snippets/csharp/System/String/Concat/Project.csproj b/snippets/csharp/System/String/Concat/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/Concat/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/Concat/concat1.cs b/snippets/csharp/System/String/Concat/concat1.cs index ef899ccee4f..930347b105b 100644 --- a/snippets/csharp/System/String/Concat/concat1.cs +++ b/snippets/csharp/System/String/Concat/concat1.cs @@ -4,35 +4,35 @@ public class Example { - public static void Main() - { - int maxPrime = 100; - IEnumerable primeList = GetPrimes(maxPrime); - Console.WriteLine("Primes less than {0}:", maxPrime); - Console.WriteLine(" {0}", String.Concat(primeList)); - } + public static void Run() + { + int maxPrime = 100; + IEnumerable primeList = GetPrimes(maxPrime); + Console.WriteLine($"Primes less than {maxPrime}:"); + Console.WriteLine($" {string.Concat(primeList)}"); + } - private static IEnumerable GetPrimes(int maxPrime) - { - Array values = Array.CreateInstance(typeof(int), - new int[] { maxPrime - 1}, new int[] { 2 }); - // Use Sieve of Erathsthenes to determine prime numbers. - for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) - { - - if ((int) values.GetValue(ctr) == 1) continue; - - for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) - if (ctr * multiplier <= maxPrime) - values.SetValue(1, ctr * multiplier); - } - - List primes = new List(); - for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) - if ((int) values.GetValue(ctr) == 0) - primes.Add(ctr.ToString() + " "); - return primes; - } + private static IEnumerable GetPrimes(int maxPrime) + { + Array values = Array.CreateInstance(typeof(int), + [maxPrime - 1], [2]); + // Use Sieve of Erathsthenes to determine prime numbers. + for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) + { + + if ((int)values.GetValue(ctr) == 1) continue; + + for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) + if (ctr * multiplier <= maxPrime) + values.SetValue(1, ctr * multiplier); + } + + List primes = new(); + for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) + if ((int)values.GetValue(ctr) == 0) + primes.Add($"{ctr} "); + return primes; + } } // The example displays the following output: // Primes less than 100: diff --git a/snippets/csharp/System/String/Concat/concat2.cs b/snippets/csharp/System/String/Concat/concat2.cs index 98be0070119..8cc4c92c82b 100644 --- a/snippets/csharp/System/String/Concat/concat2.cs +++ b/snippets/csharp/System/String/Concat/concat2.cs @@ -3,23 +3,23 @@ using System.Collections.Generic; using System.Linq; -public class Example +public class ConcatAlphabetExample { - public static void Main() - { - string output = String.Concat( GetAlphabet(true).Where( letter => - letter.CompareTo("M") >= 0)); - Console.WriteLine(output); - } + public static void Run() + { + string output = string.Concat(GetAlphabet(true).Where(letter => + letter.CompareTo("M") >= 0)); + Console.WriteLine(output); + } - private static List GetAlphabet(bool upper) - { - List alphabet = new List(); - int charValue = upper ? 65 : 97; - for (int ctr = 0; ctr <= 25; ctr++) - alphabet.Add(((char)(charValue + ctr)).ToString()); - return alphabet; - } + private static List GetAlphabet(bool upper) + { + List alphabet = new(); + int charValue = upper ? 65 : 97; + for (int ctr = 0; ctr <= 25; ctr++) + alphabet.Add(((char)(charValue + ctr)).ToString()); + return alphabet; + } } // The example displays the following output: // MNOPQRSTUVWXYZ diff --git a/snippets/csharp/System/String/Concat/concat3.cs b/snippets/csharp/System/String/Concat/concat3.cs index f190c57005c..f856ef97a5a 100644 --- a/snippets/csharp/System/String/Concat/concat3.cs +++ b/snippets/csharp/System/String/Concat/concat3.cs @@ -5,33 +5,32 @@ public class Animal { - public string Kind; - public string Order; - - public Animal(string kind, string order) - { - this.Kind = kind; - this.Order = order; - } - - public override string ToString() - { - return this.Kind; - } + public string Kind; + public string Order; + + public Animal(string kind, string order) + { + this.Kind = kind; + this.Order = order; + } + + public override string ToString() => this.Kind; } -public class Example +public class ConcatAnimalsExample { - public static void Main() - { - List animals = new List(); - animals.Add(new Animal("Squirrel", "Rodent")); - animals.Add(new Animal("Gray Wolf", "Carnivora")); - animals.Add(new Animal("Capybara", "Rodent")); - string output = String.Concat(animals.Where( animal => - (animal.Order == "Rodent"))); - Console.WriteLine(output); - } + public static void Run() + { + List animals = new() + { + new Animal("Squirrel", "Rodent"), + new Animal("Gray Wolf", "Carnivora"), + new Animal("Capybara", "Rodent") + }; + string output = string.Concat(animals.Where(animal => + (animal.Order == "Rodent"))); + Console.WriteLine(output); + } } // The example displays the following output: // SquirrelCapybara diff --git a/snippets/csharp/System/String/Concat/concat4.cs b/snippets/csharp/System/String/Concat/concat4.cs index c2ddee888f6..d5bdeca7159 100644 --- a/snippets/csharp/System/String/Concat/concat4.cs +++ b/snippets/csharp/System/String/Concat/concat4.cs @@ -2,42 +2,42 @@ using System; using System.Collections; -public class Example +public class ConcatScrambleExample { - public static void Main() - { - const int WORD_SIZE = 4; - - // Define some 4-letter words to be scrambled. - string[] words = { "home", "food", "game", "rest" }; - // Define two arrays equal to the number of letters in each word. - double[] keys = new double[WORD_SIZE]; - string[] letters = new string[WORD_SIZE]; - // Initialize the random number generator. - Random rnd = new Random(); - - // Scramble each word. - foreach (string word in words) - { - for (int ctr = 0; ctr < word.Length; ctr++) - { - // Populate the array of keys with random numbers. - keys[ctr] = rnd.NextDouble(); - // Assign a letter to the array of letters. - letters[ctr] = word[ctr].ToString(); - } - // Sort the array. - Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default); - // Display the scrambled word. - string scrambledWord = String.Concat(letters[0], letters[1], - letters[2], letters[3]); - Console.WriteLine("{0} --> {1}", word, scrambledWord); - } - } + public static void Run() + { + const int WORD_SIZE = 4; + + // Define some 4-letter words to be scrambled. + string[] words = ["home", "food", "game", "rest"]; + // Define two arrays equal to the number of letters in each word. + double[] keys = new double[WORD_SIZE]; + string[] letters = new string[WORD_SIZE]; + // Initialize the random number generator. + Random rnd = new(); + + // Scramble each word. + foreach (string word in words) + { + for (int ctr = 0; ctr < word.Length; ctr++) + { + // Populate the array of keys with random numbers. + keys[ctr] = rnd.NextDouble(); + // Assign a letter to the array of letters. + letters[ctr] = word[ctr].ToString(); + } + // Sort the array. + Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default); + // Display the scrambled word. + string scrambledWord = string.Concat(letters[0], letters[1], + letters[2], letters[3]); + Console.WriteLine($"{word} --> {scrambledWord}"); + } + } } // The example displays output like the following: // home --> mheo // food --> oodf // game --> aemg // rest --> trse -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Concat/string.concat5.cs b/snippets/csharp/System/String/Concat/string.concat5.cs index 7f2f7ac1123..ae056927f44 100644 --- a/snippets/csharp/System/String/Concat/string.concat5.cs +++ b/snippets/csharp/System/String/Concat/string.concat5.cs @@ -1,23 +1,25 @@ // using System; -class stringConcat5 { - public static void Main() { - int i = -123; - Object o = i; - Object[] objs = new Object[] {-123, -456, -789}; +class stringConcat5 +{ + public static void Run() + { + int i = -123; + object o = i; + object[] objs = [-123, -456, -789]; - Console.WriteLine("Concatenate 1, 2, and 3 objects:"); - Console.WriteLine("1) {0}", String.Concat(o)); - Console.WriteLine("2) {0}", String.Concat(o, o)); - Console.WriteLine("3) {0}", String.Concat(o, o, o)); + Console.WriteLine("Concatenate 1, 2, and 3 objects:"); + Console.WriteLine($"1) {string.Concat(o)}"); + Console.WriteLine($"2) {string.Concat(o, o)}"); + Console.WriteLine($"3) {string.Concat(o, o, o)}"); - Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:"); - Console.WriteLine("4) {0}", String.Concat(o, o, o, o)); - Console.WriteLine("5) {0}", String.Concat(o, o, o, o, o)); + Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:"); + Console.WriteLine($"4) {string.Concat(o, o, o, o)}"); + Console.WriteLine($"5) {string.Concat(o, o, o, o, o)}"); - Console.WriteLine("\nConcatenate a 3-element object array:"); - Console.WriteLine("6) {0}", String.Concat(objs)); + Console.WriteLine("\nConcatenate a 3-element object array:"); + Console.WriteLine($"6) {string.Concat(objs)}"); } } // The example displays the following output: @@ -32,4 +34,4 @@ public static void Main() { // // Concatenate a 3-element object array: // 6) -123-456-789 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Concat/stringconcat1.cs b/snippets/csharp/System/String/Concat/stringconcat1.cs index 3f9b60503d1..f7024531cc7 100644 --- a/snippets/csharp/System/String/Concat/stringconcat1.cs +++ b/snippets/csharp/System/String/Concat/stringconcat1.cs @@ -1,16 +1,18 @@ // using System; -public class ConcatTest { - public static void Main() { +public class ConcatTest +{ + public static void Run() + { // Create a group of objects. - Test1 t1 = new Test1(); - Test2 t2 = new Test2(); + Test1 t1 = new(); + Test2 t2 = new(); int i = 16; string s = "Demonstration"; // Place the objects in an array. - object [] o = { t1, i, t2, s }; + object[] o = [t1, i, t2, s]; // Concatenate the objects together as a string. To do this, // the ToString method of each of the objects is called. @@ -19,10 +21,12 @@ public static void Main() { } // Create two empty test classes. -class Test1 { +class Test1 +{ } -class Test2 { +class Test2 +{ } // The example displays the following output: // Test116Test2Demonstration diff --git a/snippets/csharp/System/String/Concat/stringconcat3.cs b/snippets/csharp/System/String/Concat/stringconcat3.cs index 1bde39eb10b..7ae186d130d 100644 --- a/snippets/csharp/System/String/Concat/stringconcat3.cs +++ b/snippets/csharp/System/String/Concat/stringconcat3.cs @@ -1,13 +1,13 @@ // using System; -public class Example +public class ConcatArrayExample { - public static void Main() + public static void Run() { // Make an array of strings. Note that we have included spaces. - string [] s = { "hello ", "and ", "welcome ", "to ", - "this ", "demo! " }; + string[] s = [ "hello ", "and ", "welcome ", "to ", + "this ", "demo! " ]; // Put all the strings together. Console.WriteLine(string.Concat(s)); diff --git a/snippets/csharp/System/String/Concat/stringconcat4.cs b/snippets/csharp/System/String/Concat/stringconcat4.cs index 3f740f83532..dc51856e25a 100644 --- a/snippets/csharp/System/String/Concat/stringconcat4.cs +++ b/snippets/csharp/System/String/Concat/stringconcat4.cs @@ -1,8 +1,10 @@ // using System; -public class ConcatTest { - public static void Main() { +public class ConcatNamesTest +{ + public static void Run() + { // we want to simply quickly add this person's name together string fName = "Simon"; @@ -16,9 +18,9 @@ public static void Main() { lName = " " + lName.Trim(); // this line simply concatenates the two strings - Console.WriteLine("Welcome to this page, '{0}'!", string.Concat( string.Concat(fName, mName), lName ) ); + Console.WriteLine($"Welcome to this page, '{string.Concat(string.Concat(fName, mName), lName)}'!"); } } // The example displays the following output: // Welcome to this page, 'Simon Jake Harrows'! -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Contains/ContainsExt1.cs b/snippets/csharp/System/String/Contains/ContainsExt1.cs index 7b68c95e12e..c9f4425d353 100644 --- a/snippets/csharp/System/String/Contains/ContainsExt1.cs +++ b/snippets/csharp/System/String/Contains/ContainsExt1.cs @@ -3,44 +3,44 @@ public static class StringExtensions { - public static bool Contains(this String str, String substring, - StringComparison comp) - { + public static bool Contains(this string str, string substring, + StringComparison comp) + { if (substring == null) - throw new ArgumentNullException("substring", + throw new ArgumentNullException("substring", "substring cannot be null."); else if (!Enum.IsDefined(typeof(StringComparison), comp)) throw new ArgumentException("comp is not a member of StringComparison", "comp"); - return str.IndexOf(substring, comp) >= 0; - } + return str.IndexOf(substring, comp) >= 0; + } } // namespace App { -using System; + using System; -public class Example -{ - public static void Main() + public class Example { - // - String s = "This is a string."; - String sub1 = "this"; - Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1); - StringComparison comp = StringComparison.Ordinal; - Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); + public static void Main() + { + // + string s = "This is a string."; + string sub1 = "this"; + Console.WriteLine($"Does '{s}' contain '{sub1}'?"); + StringComparison comp = StringComparison.Ordinal; + Console.WriteLine($" {comp:G}: {s.Contains(sub1, comp)}"); - comp = StringComparison.OrdinalIgnoreCase; - Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); + comp = StringComparison.OrdinalIgnoreCase; + Console.WriteLine($" {comp:G}: {s.Contains(sub1, comp)}"); - // The example displays the following output: - // Does 'This is a string.' contain 'this'? - // Ordinal: False - // OrdinalIgnoreCase: True - // + // The example displays the following output: + // Does 'This is a string.' contain 'this'? + // Ordinal: False + // OrdinalIgnoreCase: True + // + } } } -} diff --git a/snippets/csharp/System/String/Contains/cont.cs b/snippets/csharp/System/String/Contains/cont.cs index fa2396b7b2e..3b6b5cace3f 100644 --- a/snippets/csharp/System/String/Contains/cont.cs +++ b/snippets/csharp/System/String/Contains/cont.cs @@ -8,13 +8,12 @@ public static void Main() string s1 = "The quick brown fox jumps over the lazy dog"; string s2 = "fox"; bool b = s1.Contains(s2); - Console.WriteLine("'{0}' is in the string '{1}': {2}", - s2, s1, b); - if (b) { + Console.WriteLine($"'{s2}' is in the string '{s1}': {b}"); + if (b) + { int index = s1.IndexOf(s2); if (index >= 0) - Console.WriteLine("'{0} begins at character position {1}", - s2, index + 1); + Console.WriteLine($"'{s2} begins at character position {index + 1}"); } // This example displays the following output: // 'fox' is in the string 'The quick brown fox jumps over the lazy dog': True diff --git a/snippets/csharp/System/String/CopyTo/stringcopyto.cs b/snippets/csharp/System/String/CopyTo/stringcopyto.cs index ed39c240864..37b57ea6415 100644 --- a/snippets/csharp/System/String/CopyTo/stringcopyto.cs +++ b/snippets/csharp/System/String/CopyTo/stringcopyto.cs @@ -1,30 +1,32 @@ // using System; -public class CopyToTest { - public static void Main() { +public class CopyToTest +{ + public static void Main() + { // Embed an array of characters in a string string strSource = "changed"; - char [] destination = { 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ', - 'a', 'r', 'r', 'a', 'y' }; + char[] destination = [ 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ', + 'a', 'r', 'r', 'a', 'y' ]; // Print the char array - Console.WriteLine( destination ); + Console.WriteLine(destination); // Embed the source string in the destination string - strSource.CopyTo ( 0, destination, 4, strSource.Length ); + strSource.CopyTo(0, destination, 4, strSource.Length); // Print the resulting array - Console.WriteLine( destination ); + Console.WriteLine(destination); strSource = "A different string"; // Embed only a section of the source string in the destination - strSource.CopyTo ( 2, destination, 3, 9 ); + strSource.CopyTo(2, destination, 3, 9); // Print the resulting array - Console.WriteLine( destination ); + Console.WriteLine(destination); } } // The example displays the following output: diff --git a/snippets/csharp/System/String/EndsWith/EndsWith1.cs b/snippets/csharp/System/String/EndsWith/EndsWith1.cs index 5b188cc45d9..ad3510bb02f 100644 --- a/snippets/csharp/System/String/EndsWith/EndsWith1.cs +++ b/snippets/csharp/System/String/EndsWith/EndsWith1.cs @@ -3,16 +3,16 @@ public class Example { - public static void Main() - { - String[] strings = { "This is a string.", "Hello!", "Nothing.", - "Yes.", "randomize" }; - foreach (var value in strings) { - bool endsInPeriod = value.EndsWith("."); - Console.WriteLine("'{0}' ends in a period: {1}", - value, endsInPeriod); - } - } + public static void Run() + { + string[] strings = [ "This is a string.", "Hello!", "Nothing.", + "Yes.", "randomize" ]; + foreach (string value in strings) + { + bool endsInPeriod = value.EndsWith("."); + Console.WriteLine($"'{value}' ends in a period: {endsInPeriod}"); + } + } } // The example displays the following output: // 'This is a string.' ends in a period: True diff --git a/snippets/csharp/System/String/EndsWith/Program.cs b/snippets/csharp/System/String/EndsWith/Program.cs new file mode 100644 index 00000000000..5a20e5f7321 --- /dev/null +++ b/snippets/csharp/System/String/EndsWith/Program.cs @@ -0,0 +1,4 @@ +Example.Run(); +EndsWithCultureSample.Run(); +EndsWithComparisonSample.Run(); +EndsWithTest.Run(); diff --git a/snippets/csharp/System/String/EndsWith/Project.csproj b/snippets/csharp/System/String/EndsWith/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/EndsWith/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/EndsWith/ewci.cs b/snippets/csharp/System/String/EndsWith/ewci.cs index d6b248fc191..c0e192e0dc0 100644 --- a/snippets/csharp/System/String/EndsWith/ewci.cs +++ b/snippets/csharp/System/String/EndsWith/ewci.cs @@ -1,14 +1,14 @@ // -// This code example demonstrates the +// This code example demonstrates the // System.String.EndsWith(String, ..., CultureInfo) method. using System; -using System.Threading; + using System.Globalization; -class Sample +class EndsWithCultureSample { - public static void Main() + public static void Run() { string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n"; string msg2 = "Using the {0} - \"{1}\" culture:"; @@ -20,9 +20,9 @@ public static void Main() // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE string capitalARing = "\u00c5"; - // Define a string to search. - // The result of combining the characters LATIN SMALL LETTER A and COMBINING - // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character + // Define a string to search. + // The result of combining the characters LATIN SMALL LETTER A and COMBINING + // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). string xyzARing = "xyz" + "\u0061\u030a"; @@ -30,7 +30,7 @@ public static void Main() Console.WriteLine(msg1, capitalARing, xyzARing); // Search using English-United States culture. - ci = new CultureInfo("en-US"); + ci = new("en-US"); Console.WriteLine(msg2, ci.DisplayName, ci.Name); Console.WriteLine("Case sensitive:"); @@ -43,7 +43,7 @@ public static void Main() Console.WriteLine(); // Search using Swedish-Sweden culture. - ci = new CultureInfo("sv-SE"); + ci = new("sv-SE"); Console.WriteLine(msg2, ci.DisplayName, ci.Name); Console.WriteLine("Case sensitive:"); diff --git a/snippets/csharp/System/String/EndsWith/ewcmp.cs b/snippets/csharp/System/String/EndsWith/ewcmp.cs index f3e592bcd1d..56a1945198c 100644 --- a/snippets/csharp/System/String/EndsWith/ewcmp.cs +++ b/snippets/csharp/System/String/EndsWith/ewcmp.cs @@ -1,36 +1,35 @@ // -// This example demonstrates the +// This example demonstrates the // System.String.EndsWith(String, StringComparison) method. using System; using System.Threading; -class Sample +class EndsWithComparisonSample { - public static void Main() + public static void Run() { string intro = "Determine whether a string ends with another string, " + "using\n different values of StringComparison."; - StringComparison[] scValues = { + StringComparison[] scValues = [ StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, StringComparison.InvariantCulture, StringComparison.InvariantCultureIgnoreCase, StringComparison.Ordinal, - StringComparison.OrdinalIgnoreCase }; + StringComparison.OrdinalIgnoreCase ]; Console.WriteLine(intro); // Display the current culture because the culture-specific comparisons // can produce different results with different cultures. - Console.WriteLine("The current culture is {0}.\n", - Thread.CurrentThread.CurrentCulture.Name); - - // Determine whether three versions of the letter I are equal to each other. + Console.WriteLine($"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n"); + + // Determine whether three versions of the letter I are equal to each other. foreach (StringComparison sc in scValues) { - Console.WriteLine("StringComparison.{0}:", sc); + Console.WriteLine($"StringComparison.{sc}:"); Test("abcXYZ", "XYZ", sc); Test("abcXYZ", "xyz", sc); Console.WriteLine(); diff --git a/snippets/csharp/System/String/EndsWith/stringendswith.cs b/snippets/csharp/System/String/EndsWith/stringendswith.cs index 9fb10ebeefe..0649ce366c8 100644 --- a/snippets/csharp/System/String/EndsWith/stringendswith.cs +++ b/snippets/csharp/System/String/EndsWith/stringendswith.cs @@ -1,25 +1,27 @@ // using System; -public class EndsWithTest { - public static void Main() { +public class EndsWithTest +{ + public static void Run() + { // process an input file that contains html tags. // this sample checks for multiple tags at the end of the line, rather than simply // removing the last one. // note: HTML markup tags always end in a greater than symbol (>). - string [] strSource = { "This is bold text", "

This is large Text

", + string[] strSource = [ "This is bold text", "

This is large Text

", "This has multiple tags", "This has embedded tags.", - "This line simply ends with a greater than symbol, it should not be modified>" }; + "This line simply ends with a greater than symbol, it should not be modified>" ]; Console.WriteLine("The following lists the items before the ends have been stripped:"); Console.WriteLine("-----------------------------------------------------------------"); // print out the initial array of strings - foreach ( string s in strSource ) - Console.WriteLine( s ); + foreach (string s in strSource) + Console.WriteLine(s); Console.WriteLine(); @@ -27,29 +29,32 @@ public static void Main() { Console.WriteLine("----------------------------------------------------------------"); // print out the array of strings - foreach (var s in strSource) + foreach (string s in strSource) Console.WriteLine(StripEndTags(s)); } - private static string StripEndTags( string item ) { + private static string StripEndTags(string item) + { bool found = false; // try to find a tag at the end of the line using EndsWith - if (item.Trim().EndsWith(">")) { + if (item.Trim().EndsWith(">")) + { // now search for the opening tag... - int lastLocation = item.LastIndexOf( "= 0 ) { + if (lastLocation >= 0) + { found = true; - item = item.Substring( 0, lastLocation ); + item = item.Substring(0, lastLocation); } } if (found) - item = StripEndTags(item); + item = StripEndTags(item); return item; } @@ -70,4 +75,4 @@ private static string StripEndTags( string item ) { // This has multiple tags // This has embedded tags. // This line simply ends with a greater than symbol, it should not be modified> -//
\ No newline at end of file +//
diff --git a/snippets/csharp/System/String/Equals/eqcmp.cs b/snippets/csharp/System/String/Equals/eqcmp.cs index e17f0f0d072..c59ffb10497 100644 --- a/snippets/csharp/System/String/Equals/eqcmp.cs +++ b/snippets/csharp/System/String/Equals/eqcmp.cs @@ -1,79 +1,75 @@ // using System; -class Sample +class Sample { - public static void Main() - { - // Define a string array with the following three "I" characters: - // U+0069, U+0131, and U+0049. - string[] threeIs = { "i", "ı", "I" }; - // Define Type object representing StringComparison type. - Type scType = typeof(StringComparison); - - // Show the current culture (for culture-sensitive string comparisons). - Console.WriteLine("The current culture is {0}.\n", - System.Globalization.CultureInfo.CurrentCulture.Name); - - // Perform comparisons using each StringComparison member. - foreach (string scName in Enum.GetNames(scType)) - { - StringComparison sc = (StringComparison) Enum.Parse(scType, scName); - Console.WriteLine("Comparisons using {0}:", sc); - // Compare each character in character array. - for (int ctr = 0; ctr <= 1; ctr++) - { - string instanceChar = threeIs[ctr]; - for (int innerCtr = ctr + 1; innerCtr <= threeIs.GetUpperBound(0); innerCtr++) + public static void Main() + { + // Define a string array with the following three "I" characters: + // U+0069, U+0131, and U+0049. + string[] threeIs = ["i", "ı", "I"]; + // Define Type object representing StringComparison type. + Type scType = typeof(StringComparison); + + // Show the current culture (for culture-sensitive string comparisons). + Console.WriteLine($"The current culture is {System.Globalization.CultureInfo.CurrentCulture.Name}.\n"); + + // Perform comparisons using each StringComparison member. + foreach (string scName in Enum.GetNames(scType)) + { + StringComparison sc = (StringComparison)Enum.Parse(scType, scName); + Console.WriteLine($"Comparisons using {sc}:"); + // Compare each character in character array. + for (int ctr = 0; ctr <= 1; ctr++) { - string otherChar = threeIs[innerCtr]; - Console.WriteLine("{0} (U+{1}) = {2} (U+{3}): {4}", - instanceChar, Convert.ToInt16(Char.Parse(instanceChar)).ToString("X4"), - otherChar, Convert.ToInt16(Char.Parse(otherChar)).ToString("X4"), - instanceChar.Equals(otherChar, sc)); + string instanceChar = threeIs[ctr]; + for (int innerCtr = ctr + 1; innerCtr <= threeIs.GetUpperBound(0); innerCtr++) + { + string otherChar = threeIs[innerCtr]; + Console.WriteLine($"{instanceChar} (U+{Convert.ToInt16(char.Parse(instanceChar)):X4}) = {otherChar} (U+{Convert.ToInt16(char.Parse(otherChar)):X4}): {instanceChar.Equals(otherChar, sc)}"); + } + Console.WriteLine(); } - Console.WriteLine(); - } - } - } + } + } } // The example displays the following output: // The current culture is en-US. -// +// // Comparisons using CurrentCulture: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): False -// +// // ı (U+0131) = I (U+0049): False -// +// // Comparisons using CurrentCultureIgnoreCase: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): True -// +// // ı (U+0131) = I (U+0049): False -// +// // Comparisons using InvariantCulture: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): False -// +// // ı (U+0131) = I (U+0049): False -// +// // Comparisons using InvariantCultureIgnoreCase: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): True -// +// // ı (U+0131) = I (U+0049): False -// +// // Comparisons using Ordinal: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): False -// +// // ı (U+0131) = I (U+0049): False -// +// // Comparisons using OrdinalIgnoreCase: // i (U+0069) = ı (U+0131): False // i (U+0069) = I (U+0049): True -// +// // ı (U+0131) = I (U+0049): False // // 119 lines diff --git a/snippets/csharp/System/String/Equals/equals.cs b/snippets/csharp/System/String/Equals/equals.cs index b243c862fe2..bb63520f4ed 100644 --- a/snippets/csharp/System/String/Equals/equals.cs +++ b/snippets/csharp/System/String/Equals/equals.cs @@ -9,34 +9,34 @@ class Sample1 { public static void Main() { - StringBuilder sb = new StringBuilder("abcd"); - String str1 = "abcd"; - String str2 = null; - Object o2 = null; + StringBuilder sb = new("abcd"); + string str1 = "abcd"; + string str2 = null; + object o2 = null; Console.WriteLine(); - Console.WriteLine(" * The value of String str1 is '{0}'.", str1); - Console.WriteLine(" * The value of StringBuilder sb is '{0}'.", sb.ToString()); + Console.WriteLine($" * The value of String str1 is '{str1}'."); + Console.WriteLine($" * The value of StringBuilder sb is '{sb}'."); Console.WriteLine(); Console.WriteLine("1a) String.Equals(Object). Object is a StringBuilder, not a String."); - Console.WriteLine(" Is str1 equal to sb?: {0}", str1.Equals(sb)); + Console.WriteLine($" Is str1 equal to sb?: {str1.Equals(sb)}"); Console.WriteLine(); Console.WriteLine("1b) String.Equals(Object). Object is a String."); str2 = sb.ToString(); o2 = str2; - Console.WriteLine(" * The value of Object o2 is '{0}'.", o2); - Console.WriteLine(" Is str1 equal to o2?: {0}", str1.Equals(o2)); + Console.WriteLine($" * The value of Object o2 is '{o2}'."); + Console.WriteLine($" Is str1 equal to o2?: {str1.Equals(o2)}"); Console.WriteLine(); Console.WriteLine(" 2) String.Equals(String)"); - Console.WriteLine(" * The value of String str2 is '{0}'.", str2); - Console.WriteLine(" Is str1 equal to str2?: {0}", str1.Equals(str2)); + Console.WriteLine($" * The value of String str2 is '{str2}'."); + Console.WriteLine($" Is str1 equal to str2?: {str1.Equals(str2)}"); Console.WriteLine(); Console.WriteLine(" 3) String.Equals(String, String)"); - Console.WriteLine(" Is str1 equal to str2?: {0}", String.Equals(str1, str2)); + Console.WriteLine($" Is str1 equal to str2?: {string.Equals(str1, str2)}"); } } /* diff --git a/snippets/csharp/System/String/Equals/equals_ex3.cs b/snippets/csharp/System/String/Equals/equals_ex3.cs index a9ddb4936fa..8bbacdd1ad4 100644 --- a/snippets/csharp/System/String/Equals/equals_ex3.cs +++ b/snippets/csharp/System/String/Equals/equals_ex3.cs @@ -7,21 +7,19 @@ public class Example3 { public static void Main() { - String[] cultureNames = { "en-US", "th-TH", "tr-TR" }; - String[] strings1 = { "a", "i", "case", }; - String[] strings2 = { "a-", "\u0130", "Case" }; + string[] cultureNames = ["en-US", "th-TH", "tr-TR"]; + string[] strings1 = ["a", "i", "case",]; + string[] strings2 = ["a-", "\u0130", "Case"]; StringComparison[] comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison)); - foreach (var cultureName in cultureNames) + foreach (string cultureName in cultureNames) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName); - Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.Name); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); for (int ctr = 0; ctr <= strings1.GetUpperBound(0); ctr++) { foreach (var comparison in comparisons) - Console.WriteLine(" {0} = {1} ({2}): {3}", strings1[ctr], - strings2[ctr], comparison, - String.Equals(strings1[ctr], strings2[ctr], comparison)); + Console.WriteLine($" {strings1[ctr]} = {strings2[ctr]} ({comparison}): {string.Equals(strings1[ctr], strings2[ctr], comparison)}"); Console.WriteLine(); } diff --git a/snippets/csharp/System/String/Equals/equalsex1.cs b/snippets/csharp/System/String/Equals/equalsex1.cs index 32d31457361..4aa4470fa6d 100644 --- a/snippets/csharp/System/String/Equals/equalsex1.cs +++ b/snippets/csharp/System/String/Equals/equalsex1.cs @@ -7,13 +7,13 @@ public static void Main() { Console.OutputEncoding = System.Text.Encoding.UTF8; string word = "File"; - string[] others = { word.ToLower(), word, word.ToUpper(), "Fıle" }; + string[] others = [word.ToLower(), word, word.ToUpper(), "Fıle"]; foreach (string other in others) { if (word.Equals(other)) - Console.WriteLine("{0} = {1}", word, other); + Console.WriteLine($"{word} = {other}"); else - Console.WriteLine("{0} {1} {2}", word, '\u2260', other); + Console.WriteLine($"{word} {'\u2260'} {other}"); } } } diff --git a/snippets/csharp/System/String/Format/Example1.cs b/snippets/csharp/System/String/Format/Example1.cs index 1040735cbf8..3bc3b2a042f 100644 --- a/snippets/csharp/System/String/Format/Example1.cs +++ b/snippets/csharp/System/String/Format/Example1.cs @@ -2,24 +2,24 @@ public class Example1 { - public static void Main() - { - // - short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }; - Console.WriteLine("{0,10} {1,10}\n", "Decimal", "Hex"); - foreach (short value in values) - { - string formatString = String.Format("{0,10:G}: {0,10:X}", value); - Console.WriteLine(formatString); - } - // The example displays the following output: - // Decimal Hex - // - // -32768: 8000 - // -27: FFE5 - // 0: 0 - // 1042: 412 - // 32767: 7FFF - // - } + public static void Main() + { + // + short[] values = [short.MinValue, -27, 0, 1042, short.MaxValue]; + Console.WriteLine($"{"Decimal",10} {"Hex",10}\n"); + foreach (short value in values) + { + string formatString = string.Format("{0,10:G}: {0,10:X}", value); + Console.WriteLine(formatString); + } + // The example displays the following output: + // Decimal Hex + // + // -32768: 8000 + // -27: FFE5 + // 0: 0 + // 1042: 412 + // 32767: 7FFF + // + } } diff --git a/snippets/csharp/System/String/Format/Example2.cs b/snippets/csharp/System/String/Format/Example2.cs index b33a5f30d9e..1f6eccf8ff3 100644 --- a/snippets/csharp/System/String/Format/Example2.cs +++ b/snippets/csharp/System/String/Format/Example2.cs @@ -1,31 +1,31 @@ using System; -using System.Globalization; + public class Example2 { - public static void Main() - { - // - string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" }; + public static void Main() + { + // + string[] cultureNames = ["en-US", "fr-FR", "de-DE", "es-ES"]; - DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0); - double value = 9164.32; + DateTime dateToDisplay = new(2009, 9, 1, 18, 32, 0); + double value = 9164.32; - Console.WriteLine("Culture Date Value\n"); - foreach (string cultureName in cultureNames) - { - System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName); - string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", - culture.Name, dateToDisplay, value); - Console.WriteLine(output); - } - // The example displays the following output: - // Culture Date Value - // - // en-US Tuesday, September 01, 2009 9,164.32 - // fr-FR mardi 1 septembre 2009 9 164,32 - // de-DE Dienstag, 1. September 2009 9.164,32 - // es-ES martes, 01 de septiembre de 2009 9.164,32 - // - } + Console.WriteLine("Culture Date Value\n"); + foreach (string cultureName in cultureNames) + { + System.Globalization.CultureInfo culture = new(cultureName); + string output = string.Format(culture, "{0,-11} {1,-35:D} {2:N}", + culture.Name, dateToDisplay, value); + Console.WriteLine(output); + } + // The example displays the following output: + // Culture Date Value + // + // en-US Tuesday, September 01, 2009 9,164.32 + // fr-FR mardi 1 septembre 2009 9 164,32 + // de-DE Dienstag, 1. September 2009 9.164,32 + // es-ES martes, 01 de septiembre de 2009 9.164,32 + // + } } diff --git a/snippets/csharp/System/String/GetEnumerator/getenumerator.cs b/snippets/csharp/System/String/GetEnumerator/getenumerator.cs index 8c75ca9dd1b..384fdeee234 100644 --- a/snippets/csharp/System/String/GetEnumerator/getenumerator.cs +++ b/snippets/csharp/System/String/GetEnumerator/getenumerator.cs @@ -3,41 +3,41 @@ class Example { - public static void Main() - { - EnumerateAndDisplay("Test Case"); - EnumerateAndDisplay("This is a sentence."); - EnumerateAndDisplay("Has\ttwo\ttabs" ); - EnumerateAndDisplay("Two\nnew\nlines"); - } + public static void Main() + { + EnumerateAndDisplay("Test Case"); + EnumerateAndDisplay("This is a sentence."); + EnumerateAndDisplay("Has\ttwo\ttabs"); + EnumerateAndDisplay("Two\nnew\nlines"); + } - static void EnumerateAndDisplay(String phrase) - { - Console.WriteLine("The characters in the string \"{0}\" are:", - phrase); + static void EnumerateAndDisplay(string phrase) + { + Console.WriteLine($"The characters in the string \"{phrase}\" are:"); - int CharCount = 0; - int controlChars = 0; - int alphanumeric = 0; - int punctuation = 0; + int CharCount = 0; + int controlChars = 0; + int alphanumeric = 0; + int punctuation = 0; - foreach (var ch in phrase) { - Console.Write(Char.IsControl(ch) ? $"{ch}" : $"0x{(ushort)ch:X4}"); + foreach (char ch in phrase) + { + Console.Write(char.IsControl(ch) ? $"{ch}" : $"0x{(ushort)ch:X4}"); - if (Char.IsLetterOrDigit(ch)) - alphanumeric++; - else if (Char.IsControl(ch)) - controlChars++; - else if (Char.IsPunctuation(ch)) - punctuation++; - CharCount++; - } + if (char.IsLetterOrDigit(ch)) + alphanumeric++; + else if (char.IsControl(ch)) + controlChars++; + else if (char.IsPunctuation(ch)) + punctuation++; + CharCount++; + } - Console.WriteLine("\n Total characters: {0,3}", CharCount); - Console.WriteLine(" Alphanumeric characters: {0,3}", alphanumeric); - Console.WriteLine(" Punctuation characters: {0,3}", punctuation); - Console.WriteLine(" Control Characters: {0,3}\n", controlChars); - } + Console.WriteLine($"\n Total characters: {CharCount,3}"); + Console.WriteLine($" Alphanumeric characters: {alphanumeric,3}"); + Console.WriteLine($" Punctuation characters: {punctuation,3}"); + Console.WriteLine($" Control Characters: {controlChars,3}\n"); + } } // The example displays the following output: // The characters in the string "Test Case" are: @@ -46,21 +46,21 @@ static void EnumerateAndDisplay(String phrase) // Alphanumeric characters: 8 // Punctuation characters: 0 // Control Characters: 0 -// +// // The characters in the string "This is a sentence." are: // 'T' 'h' 'i' 's' ' ' 'i' 's' ' ' 'a' ' ' 's' 'e' 'n' 't' 'e' 'n' 'c' 'e' '.' // Total characters: 19 // Alphanumeric characters: 15 // Punctuation characters: 1 // Control Characters: 0 -// +// // The characters in the string "Has two tabs" are: // 'H' 'a' 's' '0x0009' 't' 'w' 'o' '0x0009' 't' 'a' 'b' 's' // Total characters: 12 // Alphanumeric characters: 10 // Punctuation characters: 0 // Control Characters: 2 -// +// // The characters in the string "Two // new // lines" are: diff --git a/snippets/csharp/System/String/GetHashCode/gethashcode.cs b/snippets/csharp/System/String/GetHashCode/gethashcode.cs index be0146f6d53..d63cdb3fe0b 100644 --- a/snippets/csharp/System/String/GetHashCode/gethashcode.cs +++ b/snippets/csharp/System/String/GetHashCode/gethashcode.cs @@ -1,30 +1,30 @@ // using System; -class GetHashCode +class GetHashCode { - public static void Main() + public static void Main() { - DisplayHashCode( "" ); - DisplayHashCode( "a" ); - DisplayHashCode( "ab" ); - DisplayHashCode( "abc" ); - DisplayHashCode( "abd" ); - DisplayHashCode( "abe" ); - DisplayHashCode( "abcdef" ); - DisplayHashCode( "abcdeg" ); - DisplayHashCode( "abcdeh" ); - DisplayHashCode( "abcdei" ); - DisplayHashCode( "Abcdeg" ); - DisplayHashCode( "Abcdeh" ); - DisplayHashCode( "Abcdei" ); + DisplayHashCode(""); + DisplayHashCode("a"); + DisplayHashCode("ab"); + DisplayHashCode("abc"); + DisplayHashCode("abd"); + DisplayHashCode("abe"); + DisplayHashCode("abcdef"); + DisplayHashCode("abcdeg"); + DisplayHashCode("abcdeh"); + DisplayHashCode("abcdei"); + DisplayHashCode("Abcdeg"); + DisplayHashCode("Abcdeh"); + DisplayHashCode("Abcdei"); } - static void DisplayHashCode( String Operand ) + static void DisplayHashCode(string Operand) { - int HashCode = Operand.GetHashCode( ); + int HashCode = Operand.GetHashCode(); Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}", - Operand, HashCode ); + Operand, HashCode); } } /* diff --git a/snippets/csharp/System/String/GetHashCode/perdomain.cs b/snippets/csharp/System/String/GetHashCode/perdomain.cs index ab65986cc17..cdf6cd6fef7 100644 --- a/snippets/csharp/System/String/GetHashCode/perdomain.cs +++ b/snippets/csharp/System/String/GetHashCode/perdomain.cs @@ -3,53 +3,39 @@ public class Example { - public static void Main() - { - // Show hash code in current domain. - DisplayString display = new DisplayString(); - display.ShowStringHashCode(); - - // Create a new app domain and show string hash code. - AppDomain domain = AppDomain.CreateDomain("NewDomain"); - var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, - "DisplayString"); - display2.ShowStringHashCode(); - } + public static void Main() + { + // Show hash code in current domain. + DisplayString display = new(); + display.ShowStringHashCode(); + + // Create a new app domain and show string hash code. + AppDomain domain = AppDomain.CreateDomain("NewDomain"); + var display2 = (DisplayString)domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, + "DisplayString"); + display2.ShowStringHashCode(); + } } public class DisplayString : MarshalByRefObject { - private String s = "This is a string."; - - public override bool Equals(Object obj) - { - String s2 = obj as String; - if (s2 == null) - return false; - else - return s == s2; - } - - public bool Equals(String str) - { - return s == str; - } - - public override int GetHashCode() - { - return s.GetHashCode(); - } - - public override String ToString() - { - return s; - } - - public void ShowStringHashCode() - { - Console.WriteLine("String '{0}' in domain '{1}': {2:X8}", - s, AppDomain.CurrentDomain.FriendlyName, - s.GetHashCode()); - } + private string s = "This is a string."; + + public override bool Equals(object obj) + { + string s2 = obj as string; + if (s2 == null) + return false; + else + return s == s2; + } + + public bool Equals(string str) => s == str; + + public override int GetHashCode() => s.GetHashCode(); + + public override string ToString() => s; + + public void ShowStringHashCode() => Console.WriteLine($"String '{s}' in domain '{AppDomain.CurrentDomain.FriendlyName}': {s.GetHashCode():X8}"); } //
diff --git a/snippets/csharp/System/String/GetTypeCode/gtc.cs b/snippets/csharp/System/String/GetTypeCode/gtc.cs index c5356ddf9a5..2d70716b99e 100644 --- a/snippets/csharp/System/String/GetTypeCode/gtc.cs +++ b/snippets/csharp/System/String/GetTypeCode/gtc.cs @@ -6,14 +6,13 @@ class Sample { public static void Main() { - String str = "abc"; - TypeCode tc = str.GetTypeCode(); - Console.WriteLine("The type code for '{0}' is {1}, which represents {2}.", - str, tc.ToString("D"), tc.ToString("F")); + string str = "abc"; + TypeCode tc = str.GetTypeCode(); + Console.WriteLine($"The type code for '{str}' is {tc:D}, which represents {tc:F}."); } } /* This example produces the following results: The type code for 'abc' is 18, which represents String. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/IndexOf/Program.cs b/snippets/csharp/System/String/IndexOf/Program.cs new file mode 100644 index 00000000000..b505b064718 --- /dev/null +++ b/snippets/csharp/System/String/IndexOf/Program.cs @@ -0,0 +1,14 @@ +IndexOfIgnorable21Example.Run(); +IndexOfIgnorable22Example.Run(); +IndexOfIgnorable23Example.Run(); +IndexOfIgnorable24Example.Run(); +IndexOfIgnorable25Example.Run(); +IndexOfIgnorable26Example.Run(); +IndexOfCharExample.Run(); +IndexOfCII.Run(); +IndexOfComparisonSample.Run(); +IndexOfCharStartSample.Run(); +IndexOfStringRangeSample.Run(); +IndexOfSimpleExample.Run(); +IndexOfTest.Run(); +IndexOfInsertExample.Run(); diff --git a/snippets/csharp/System/String/IndexOf/Project.csproj b/snippets/csharp/System/String/IndexOf/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/IndexOf/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/IndexOf/ignorable21.cs b/snippets/csharp/System/String/IndexOf/ignorable21.cs index 29b182f331b..b0d6f02fb2d 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable21.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable21.cs @@ -1,9 +1,9 @@ // using System; -public class Example +public class IndexOfIgnorable21Example { - public static void Main() + public static void Run() { string s1 = "ani\u00ADmal"; string s2 = "animal"; diff --git a/snippets/csharp/System/String/IndexOf/ignorable22.cs b/snippets/csharp/System/String/IndexOf/ignorable22.cs index e1180339da9..309de8e989d 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable22.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable22.cs @@ -1,12 +1,12 @@ // using System; -public class Example +public class IndexOfIgnorable22Example { - public static void Main() + public static void Run() { string searchString = "\u00ADm"; - string s1 = "ani\u00ADmal" ; + string s1 = "ani\u00ADmal"; string s2 = "animal"; Console.WriteLine(s1.IndexOf(searchString, 2)); diff --git a/snippets/csharp/System/String/IndexOf/ignorable23.cs b/snippets/csharp/System/String/IndexOf/ignorable23.cs index be4b57bf6f2..ab2ad572ff7 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable23.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable23.cs @@ -1,12 +1,12 @@ // using System; -public class Example +public class IndexOfIgnorable23Example { - public static void Main() + public static void Run() { string searchString = "\u00ADm"; - string s1 = "ani\u00ADmal" ; + string s1 = "ani\u00ADmal"; string s2 = "animal"; Console.WriteLine(s1.IndexOf(searchString, 2, 4)); diff --git a/snippets/csharp/System/String/IndexOf/ignorable24.cs b/snippets/csharp/System/String/IndexOf/ignorable24.cs index c63cb7df854..b3ccc5efb99 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable24.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable24.cs @@ -1,13 +1,13 @@ // using System; -public class Example +public class IndexOfIgnorable24Example { - public static void Main() + public static void Run() { string searchString = "\u00ADm"; - string s1 = "ani\u00ADmal" ; + string s1 = "ani\u00ADmal"; string s2 = "animal"; Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture)); diff --git a/snippets/csharp/System/String/IndexOf/ignorable25.cs b/snippets/csharp/System/String/IndexOf/ignorable25.cs index b5d9fafe11a..4113d5dec59 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable25.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable25.cs @@ -1,13 +1,13 @@ // using System; -public class Example +public class IndexOfIgnorable25Example { - public static void Main() + public static void Run() { - + string searchString = "\u00ADm"; - string s1 = "ani\u00ADmal" ; + string s1 = "ani\u00ADmal"; string s2 = "animal"; Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.CurrentCulture)); diff --git a/snippets/csharp/System/String/IndexOf/ignorable26.cs b/snippets/csharp/System/String/IndexOf/ignorable26.cs index 61944637145..5c39f7f5943 100644 --- a/snippets/csharp/System/String/IndexOf/ignorable26.cs +++ b/snippets/csharp/System/String/IndexOf/ignorable26.cs @@ -1,35 +1,35 @@ // using System; -public class Example +public class IndexOfIgnorable26Example { - public static void Main() + public static void Run() { string s1 = "ani\u00ADmal"; string s2 = "animal"; - + Console.WriteLine("Culture-sensitive comparison:"); // Use culture-sensitive comparison to find the soft hyphen. Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.CurrentCulture)); Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.CurrentCulture)); - + // Use culture-sensitive comparison to find the soft hyphen followed by "n". Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.CurrentCulture)); Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.CurrentCulture)); - + // Use culture-sensitive comparison to find the soft hyphen followed by "m". Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.CurrentCulture)); Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.CurrentCulture)); - + Console.WriteLine("Ordinal comparison:"); // Use ordinal comparison to find the soft hyphen. Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.Ordinal)); Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.Ordinal)); - + // Use ordinal comparison to find the soft hyphen followed by "n". Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.Ordinal)); Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.Ordinal)); - + // Use ordinal comparison to find the soft hyphen followed by "m". Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.Ordinal)); Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.Ordinal)); diff --git a/snippets/csharp/System/String/IndexOf/indexof_c.cs b/snippets/csharp/System/String/IndexOf/indexof_c.cs index 2b7c273d005..9151244d7a7 100644 --- a/snippets/csharp/System/String/IndexOf/indexof_c.cs +++ b/snippets/csharp/System/String/IndexOf/indexof_c.cs @@ -1,31 +1,29 @@ using System; -class Example +class IndexOfCharExample { - static void Main() + public static void Run() { // // Create a Unicode string with 5 Greek Alpha characters. - String szGreekAlpha = new String('\u0391',5); + string szGreekAlpha = new('\u0391', 5); // Create a Unicode string with 3 Greek Omega characters. - String szGreekOmega = "\u03A9\u03A9\u03A9"; + string szGreekOmega = "\u03A9\u03A9\u03A9"; - String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, + string szGreekLetters = string.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone()); // Display the entire string. - Console.WriteLine("The string: {0}", szGreekLetters); + Console.WriteLine($"The string: {szGreekLetters}"); // The first index of Alpha. int ialpha = szGreekLetters.IndexOf('\u0391'); // The first index of Omega. int iomega = szGreekLetters.IndexOf('\u03A9'); - Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", - ialpha); - Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", - iomega); + Console.WriteLine($"First occurrence of the Greek letter Alpha: Index {ialpha}"); + Console.WriteLine($"First occurrence of the Greek letter Omega: Index {iomega}"); // The example displays the following output: // The string: ΩΩΩΑΑΑΑΑΩΩΩ diff --git a/snippets/csharp/System/String/IndexOf/indexofcii.cs b/snippets/csharp/System/String/IndexOf/indexofcii.cs index ae361791095..3d254bb5853 100644 --- a/snippets/csharp/System/String/IndexOf/indexofcii.cs +++ b/snippets/csharp/System/String/IndexOf/indexofcii.cs @@ -2,60 +2,58 @@ // Example for the String.IndexOf( char, int, int ) method. using System; -class IndexOfCII +class IndexOfCII { - public static void Main() + public static void Run() { - string br1 = + string br1 = "0----+----1----+----2----+----3----+----" + "4----+----5----+----6----+----7"; - string br2 = + string br2 = "0123456789012345678901234567890123456789" + "0123456789012345678901234567890"; - string str = + string str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " + "ABCDEFGHI abcdefghi ABCDEFGHI"; - Console.WriteLine( + Console.WriteLine( "This example of String.IndexOf( char, int, int )\n" + - "generates the following output." ); - Console.WriteLine( - "{0}{1}{0}{2}{0}{3}{0}", - Environment.NewLine, br1, br2, str ); + "generates the following output."); + Console.WriteLine( + "{0}{1}{0}{2}{0}{3}{0}", + Environment.NewLine, br1, br2, str); - FindAllChar( 'A', str ); - FindAllChar( 'a', str ); - FindAllChar( 'I', str ); - FindAllChar( 'i', str ); - FindAllChar( '@', str ); - FindAllChar( ' ', str ); + FindAllChar('A', str); + FindAllChar('a', str); + FindAllChar('I', str); + FindAllChar('i', str); + FindAllChar('@', str); + FindAllChar(' ', str); } - static void FindAllChar( Char target, String searched ) + static void FindAllChar(char target, string searched) { - Console.Write( - "The character '{0}' occurs at position(s): ", - target ); + Console.Write($"The character '{target}' occurs at position(s): "); - int startIndex = -1; - int hitCount = 0; + int startIndex = -1; + int hitCount = 0; // Search for all occurrences of the target. - while( true ) + while (true) { - startIndex = searched.IndexOf( - target, startIndex + 1, - searched.Length - startIndex - 1 ); + startIndex = searched.IndexOf( + target, startIndex + 1, + searched.Length - startIndex - 1); // Exit the loop if the target is not found. - if( startIndex < 0 ) + if (startIndex < 0) break; - Console.Write( "{0}, ", startIndex ); + Console.Write($"{startIndex}, "); hitCount++; } - Console.WriteLine( "occurrences: {0}", hitCount ); + Console.WriteLine($"occurrences: {hitCount}"); } } diff --git a/snippets/csharp/System/String/IndexOf/iocmp.cs b/snippets/csharp/System/String/IndexOf/iocmp.cs index 27b599505ff..cd332b3dcb0 100644 --- a/snippets/csharp/System/String/IndexOf/iocmp.cs +++ b/snippets/csharp/System/String/IndexOf/iocmp.cs @@ -1,90 +1,87 @@ // -// This code example demonstrates the +// This code example demonstrates the // System.String.IndexOf(String, ..., StringComparison) methods. using System; using System.Threading; -using System.Globalization; -class Sample + +class IndexOfComparisonSample { - public static void Main() + public static void Run() { - string intro = "Find the first occurrence of a character using different " + - "values of StringComparison."; - string resultFmt = "Comparison: {0,-28} Location: {1,3}"; - -// Define a string to search for. -// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE - string CapitalAWithRing = "\u00c5"; - -// Define a string to search. -// The result of combining the characters LATIN SMALL LETTER A and COMBINING -// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character -// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). - string cat = "A Cheshire c" + "\u0061\u030a" + "t"; - - int loc = 0; - StringComparison[] scValues = { + string intro = "Find the first occurrence of a character using different " + + "values of StringComparison."; + string resultFmt = "Comparison: {0,-28} Location: {1,3}"; + + // Define a string to search for. + // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE + string CapitalAWithRing = "\u00c5"; + + // Define a string to search. + // The result of combining the characters LATIN SMALL LETTER A and COMBINING + // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character + // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). + string cat = "A Cheshire c" + "\u0061\u030a" + "t"; + + int loc = 0; + StringComparison[] scValues = [ StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, StringComparison.InvariantCulture, StringComparison.InvariantCultureIgnoreCase, StringComparison.Ordinal, - StringComparison.OrdinalIgnoreCase }; - -// Clear the screen and display an introduction. - Console.Clear(); - Console.WriteLine(intro); - -// Display the current culture because culture affects the result. For example, -// try this code example with the "sv-SE" (Swedish-Sweden) culture. - - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - Console.WriteLine("The current culture is \"{0}\" - {1}.", - Thread.CurrentThread.CurrentCulture.Name, - Thread.CurrentThread.CurrentCulture.DisplayName); - -// Display the string to search for and the string to search. - Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", - CapitalAWithRing, cat); - Console.WriteLine(); - -// Note that in each of the following searches, we look for -// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains -// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates -// the string was not found. -// Search using different values of StringComparison. Specify the start -// index and count. - - Console.WriteLine("Part 1: Start index and count are specified."); - foreach (StringComparison sc in scValues) + StringComparison.OrdinalIgnoreCase ]; + + // Clear the screen and display an introduction. + Console.Clear(); + Console.WriteLine(intro); + + // Display the current culture because culture affects the result. For example, + // try this code example with the "sv-SE" (Swedish-Sweden) culture. + + Thread.CurrentThread.CurrentCulture = new("en-US"); + Console.WriteLine($"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."); + + // Display the string to search for and the string to search. + Console.WriteLine($"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\""); + Console.WriteLine(); + + // Note that in each of the following searches, we look for + // LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains + // LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates + // the string was not found. + // Search using different values of StringComparison. Specify the start + // index and count. + + Console.WriteLine("Part 1: Start index and count are specified."); + foreach (StringComparison sc in scValues) { - loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc); + Console.WriteLine(resultFmt, sc, loc); } -// Search using different values of StringComparison. Specify the -// start index. - Console.WriteLine("\nPart 2: Start index is specified."); - foreach (StringComparison sc in scValues) + // Search using different values of StringComparison. Specify the + // start index. + Console.WriteLine("\nPart 2: Start index is specified."); + foreach (StringComparison sc in scValues) { - loc = cat.IndexOf(CapitalAWithRing, 0, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.IndexOf(CapitalAWithRing, 0, sc); + Console.WriteLine(resultFmt, sc, loc); } -// Search using different values of StringComparison. - Console.WriteLine("\nPart 3: Neither start index nor count is specified."); - foreach (StringComparison sc in scValues) + // Search using different values of StringComparison. + Console.WriteLine("\nPart 3: Neither start index nor count is specified."); + foreach (StringComparison sc in scValues) { - loc = cat.IndexOf(CapitalAWithRing, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.IndexOf(CapitalAWithRing, sc); + Console.WriteLine(resultFmt, sc, loc); } } } /* -Note: This code example was executed on a console whose user interface +Note: This code example was executed on a console whose user interface culture is "en-US" (English-United States). This code example produces the following results: @@ -118,4 +115,4 @@ public static void Main() Comparison: OrdinalIgnoreCase Location: -1 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/IndexOf/ixof1.cs b/snippets/csharp/System/String/IndexOf/ixof1.cs index 9433fe653c9..5a2a7decd3e 100644 --- a/snippets/csharp/System/String/IndexOf/ixof1.cs +++ b/snippets/csharp/System/String/IndexOf/ixof1.cs @@ -1,9 +1,9 @@ -// Sample for String.IndexOf(Char, Int32) +// Sample for String.IndexOf(Char, Int32) using System; -class Sample +class IndexOfCharStartSample { - public static void Main() + public static void Run() { // string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---"; @@ -13,18 +13,18 @@ public static void Main() int at; Console.WriteLine(); - Console.WriteLine("All occurrences of 't' from position 0 to {0}.", str.Length-1); + Console.WriteLine($"All occurrences of 't' from position 0 to {str.Length - 1}."); Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); Console.Write("The letter 't' occurs at position(s): "); at = 0; start = 0; - while((start < str.Length) && (at > -1)) + while ((start < str.Length) && (at > -1)) { at = str.IndexOf('t', start); if (at == -1) break; - Console.Write("{0} ", at); - start = at+1; + Console.Write($"{at} "); + start = at + 1; } Console.WriteLine(); diff --git a/snippets/csharp/System/String/IndexOf/ixof8.cs b/snippets/csharp/System/String/IndexOf/ixof8.cs index cbc10380838..b8ac12b99b8 100644 --- a/snippets/csharp/System/String/IndexOf/ixof8.cs +++ b/snippets/csharp/System/String/IndexOf/ixof8.cs @@ -1,9 +1,9 @@ -// Sample for String.IndexOf(String, Int32, Int32) +// Sample for String.IndexOf(String, Int32, Int32) using System; -class Sample +class IndexOfStringRangeSample { - public static void Main() + public static void Run() { // string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---"; @@ -15,22 +15,22 @@ public static void Main() int count; end = str.Length; - start = end/2; + start = end / 2; Console.WriteLine(); - Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end-1); + Console.WriteLine($"All occurrences of 'he' from position {start} to {end - 1}."); Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); Console.Write("The string 'he' occurs at position(s): "); count = 0; at = 0; - while((start <= end) && (at > -1)) + while ((start <= end) && (at > -1)) { // start+count must be a position within -str-. count = end - start; at = str.IndexOf("he", start, count); if (at == -1) break; - Console.Write("{0} ", at); - start = at+1; + Console.Write($"{at} "); + start = at + 1; } Console.WriteLine(); diff --git a/snippets/csharp/System/String/IndexOf/simple1.cs b/snippets/csharp/System/String/IndexOf/simple1.cs index f95f43a3db8..e6b7f7695b6 100644 --- a/snippets/csharp/System/String/IndexOf/simple1.cs +++ b/snippets/csharp/System/String/IndexOf/simple1.cs @@ -1,15 +1,14 @@ using System; -public class Example +public class IndexOfSimpleExample { - public static void Main() + public static void Run() { // - String str = "animal"; - String toFind = "n"; + string str = "animal"; + string toFind = "n"; int index = str.IndexOf("n"); - Console.WriteLine("Found '{0}' in '{1}' at position {2}", - toFind, str, index); + Console.WriteLine($"Found '{toFind}' in '{str}' at position {index}"); // The example displays the following output: // Found 'n' in 'animal' at position 1 diff --git a/snippets/csharp/System/String/IndexOf/stringindexof4.cs b/snippets/csharp/System/String/IndexOf/stringindexof4.cs index 041de8858d8..8bac7e8766f 100644 --- a/snippets/csharp/System/String/IndexOf/stringindexof4.cs +++ b/snippets/csharp/System/String/IndexOf/stringindexof4.cs @@ -1,8 +1,10 @@ // using System; -public class IndexOfTest { - public static void Main() { +public class IndexOfTest +{ + public static void Run() + { string strSource = "This is the string which we will perform the search on"; @@ -12,18 +14,22 @@ public static void Main() { int found = 0; int totFinds = 0; - do { + do + { Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> "); strTarget = Console.ReadLine(); - if (strTarget != "") { + if (strTarget != "") + { - for (int i = 0; i < strSource.Length; i++) { + for (int i = 0; i < strSource.Length; i++) + { found = strSource.IndexOf(strTarget, i); - if (found >= 0) { + if (found >= 0) + { totFinds++; i = found; } @@ -42,7 +48,7 @@ public static void Main() { Environment.NewLine, strTarget, totFinds); totFinds = 0; - } while ( true ); + } while (true); } } // diff --git a/snippets/csharp/System/String/IndexOf/stringinsert.cs b/snippets/csharp/System/String/IndexOf/stringinsert.cs index 9fb39e92607..1b99e5b4c99 100644 --- a/snippets/csharp/System/String/IndexOf/stringinsert.cs +++ b/snippets/csharp/System/String/IndexOf/stringinsert.cs @@ -1,14 +1,14 @@ // using System; -public class Example { - public static void Main() +public class IndexOfInsertExample +{ + public static void Run() { string animal1 = "fox"; string animal2 = "dog"; - string strTarget = String.Format("The {0} jumps over the {1}.", - animal1, animal2); + string strTarget = $"The {animal1} jumps over the {animal2}."; Console.WriteLine("The original string is:{0}{1}{0}", Environment.NewLine, strTarget); diff --git a/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs b/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs index 7e46888284c..1c167ef5e5c 100644 --- a/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs +++ b/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs @@ -2,22 +2,22 @@ public class Example1 { - public static void Run() - { - // - char[] chars = { 'a', 'e', 'i', 'o', 'u', 'y', - 'A', 'E', 'I', 'O', 'U', 'Y' }; - String s = "The long and winding road..."; - Console.WriteLine($""" + public static void Run() + { + // + char[] chars = [ 'a', 'e', 'i', 'o', 'u', 'y', + 'A', 'E', 'I', 'O', 'U', 'Y' ]; + string s = "The long and winding road..."; + Console.WriteLine($""" The first vowel in '{s}' is found at index {s.IndexOfAny(chars)} """); - // The example displays the following output: - // The first vowel in - // 'The long and winding road...' - // is found at index 2 - // - } + // The example displays the following output: + // The first vowel in + // 'The long and winding road...' + // is found at index 2 + // + } } diff --git a/snippets/csharp/System/String/IndexOfAny/Program.cs b/snippets/csharp/System/String/IndexOfAny/Program.cs index 510edb4cb58..c84db44d8fb 100644 --- a/snippets/csharp/System/String/IndexOfAny/Program.cs +++ b/snippets/csharp/System/String/IndexOfAny/Program.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + + + + + namespace Project { diff --git a/snippets/csharp/System/String/Insert/Insert1.cs b/snippets/csharp/System/String/Insert/Insert1.cs index 033b12127ad..d888d8bca49 100644 --- a/snippets/csharp/System/String/Insert/Insert1.cs +++ b/snippets/csharp/System/String/Insert/Insert1.cs @@ -3,13 +3,13 @@ public class Example { - public static void Main() - { - String original = "aaabbb"; - Console.WriteLine("The original string: '{0}'", original); - String modified = original.Insert(3, " "); - Console.WriteLine("The modified string: '{0}'", modified); - } + public static void Main() + { + string original = "aaabbb"; + Console.WriteLine($"The original string: '{original}'"); + string modified = original.Insert(3, " "); + Console.WriteLine($"The modified string: '{modified}'"); + } } // The example displays the following output: // The original string: 'aaabbb' diff --git a/snippets/csharp/System/String/Intern/Intern1.cs b/snippets/csharp/System/String/Intern/Intern1.cs index fa3a57ae33a..685a2fa10e9 100644 --- a/snippets/csharp/System/String/Intern/Intern1.cs +++ b/snippets/csharp/System/String/Intern/Intern1.cs @@ -4,14 +4,14 @@ [assembly: CLSCompliant(true)] public class Class1 { - public static void Main() - { - // - string s1 = "MyTest"; - string s2 = new StringBuilder().Append("My").Append("Test").ToString(); - string s3 = String.Intern(s2); - Console.WriteLine((Object)s2==(Object)s1); // Different references. - Console.WriteLine((Object)s3==(Object)s1); // The same reference. - // - } + public static void Main() + { + // + string s1 = "MyTest"; + string s2 = new StringBuilder().Append("My").Append("Test").ToString(); + string s3 = string.Intern(s2); + Console.WriteLine((object)s2 == (object)s1); // Different references. + Console.WriteLine((object)s3 == (object)s1); // The same reference. + // + } } diff --git a/snippets/csharp/System/String/Intern/string_intern.cs b/snippets/csharp/System/String/Intern/string_intern.cs index 8f14ccb26f7..d177d745c93 100644 --- a/snippets/csharp/System/String/Intern/string_intern.cs +++ b/snippets/csharp/System/String/Intern/string_intern.cs @@ -12,13 +12,13 @@ public static void Main() Console.WriteLine($"s1 == {s1}"); Console.WriteLine($"s2 == {s2}"); Console.WriteLine($"Are s1 and s2 equal in value? {s1 == s2}"); - Console.WriteLine($"Are s1 and s2 the same reference? {Object.ReferenceEquals(s1, s2)}"); + Console.WriteLine($"Are s1 and s2 the same reference? {object.ReferenceEquals(s1, s2)}"); - string i1 = String.Intern(s1); - string i2 = String.Intern(s2); + string i1 = string.Intern(s1); + string i2 = string.Intern(s2); Console.WriteLine($"After interning:"); Console.WriteLine($" Are i1 and i2 equal in value? {i1 == i2}"); - Console.WriteLine($" Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}"); + Console.WriteLine($" Are i1 and i2 the same reference? {object.ReferenceEquals(i1, i2)}"); } } /* diff --git a/snippets/csharp/System/String/IsInterned/isin.cs b/snippets/csharp/System/String/IsInterned/isin.cs index e7dc8a16d93..7077f417841 100644 --- a/snippets/csharp/System/String/IsInterned/isin.cs +++ b/snippets/csharp/System/String/IsInterned/isin.cs @@ -12,17 +12,17 @@ public static void Main() string s2 = new StringBuilder().Append("My").Append("Test").ToString(); // Neither string is in the intern pool yet. - Console.WriteLine($"Is s1 interned? {String.IsInterned(s1) != null}"); - Console.WriteLine($"Is s2 interned? {String.IsInterned(s2) != null}"); + Console.WriteLine($"Is s1 interned? {string.IsInterned(s1) != null}"); + Console.WriteLine($"Is s2 interned? {string.IsInterned(s2) != null}"); // Intern s1 explicitly. - string i1 = String.Intern(s1); + string i1 = string.Intern(s1); // Now s2 can be found in the intern pool. - string i2 = String.IsInterned(s2); + string i2 = string.IsInterned(s2); Console.WriteLine($"Is s2 interned after interning s1? {i2 != null}"); - Console.WriteLine($"Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}"); + Console.WriteLine($"Are i1 and i2 the same reference? {object.ReferenceEquals(i1, i2)}"); } } @@ -33,4 +33,4 @@ public static void Main() // Is s2 interned after interning s1? True // Are i1 and i2 the same reference? True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/IsInterned/isinternedex1.cs b/snippets/csharp/System/String/IsInterned/isinternedex1.cs index 71b73869dde..fcc54c72ac7 100644 --- a/snippets/csharp/System/String/IsInterned/isinternedex1.cs +++ b/snippets/csharp/System/String/IsInterned/isinternedex1.cs @@ -3,29 +3,28 @@ public class Example { - public static void Main() - { - string str1 = "a"; - string str2 = str1 + "b"; - string str3 = str2 + "c"; - string[] strings = { "value", "part1" + "_" + "part2", str3, - String.Empty, null }; - foreach (var value in strings) { - if (value == null) continue; - - bool interned = String.IsInterned(value) != null; - if (interned) - Console.WriteLine("'{0}' is in the string intern pool.", - value); - else - Console.WriteLine("'{0}' is not in the string intern pool.", - value); - } - } + public static void Main() + { + string str1 = "a"; + string str2 = str1 + "b"; + string str3 = str2 + "c"; + string[] strings = [ "value", "part1" + "_" + "part2", str3, + string.Empty, null ]; + foreach (string value in strings) + { + if (value == null) continue; + + bool interned = string.IsInterned(value) != null; + if (interned) + Console.WriteLine($"'{value}' is in the string intern pool."); + else + Console.WriteLine($"'{value}' is not in the string intern pool."); + } + } } // The example displays the following output: // 'value' is in the string intern pool. // 'part1_part2' is in the string intern pool. // 'abc' is not in the string intern pool. // '' is in the string intern pool. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/IsNormalized/norm.cs b/snippets/csharp/System/String/IsNormalized/norm.cs index a675445da1b..b8a80b7e51b 100644 --- a/snippets/csharp/System/String/IsNormalized/norm.cs +++ b/snippets/csharp/System/String/IsNormalized/norm.cs @@ -6,79 +6,75 @@ class Example { public static void Main() { - // Character c; combining characters acute and cedilla; character 3/4 - string s1 = new String( new char[] {'\u0063', '\u0301', '\u0327', '\u00BE'}); - string s2 = null; - string divider = new String('-', 80); - divider = String.Concat(Environment.NewLine, divider, Environment.NewLine); - - Show("s1", s1); - Console.WriteLine(); - Console.WriteLine("U+0063 = LATIN SMALL LETTER C"); - Console.WriteLine("U+0301 = COMBINING ACUTE ACCENT"); - Console.WriteLine("U+0327 = COMBINING CEDILLA"); - Console.WriteLine("U+00BE = VULGAR FRACTION THREE QUARTERS"); - Console.WriteLine(divider); - - Console.WriteLine("A1) Is s1 normalized to the default form (Form C)?: {0}", - s1.IsNormalized()); - Console.WriteLine("A2) Is s1 normalized to Form C?: {0}", - s1.IsNormalized(NormalizationForm.FormC)); - Console.WriteLine("A3) Is s1 normalized to Form D?: {0}", - s1.IsNormalized(NormalizationForm.FormD)); - Console.WriteLine("A4) Is s1 normalized to Form KC?: {0}", - s1.IsNormalized(NormalizationForm.FormKC)); - Console.WriteLine("A5) Is s1 normalized to Form KD?: {0}", - s1.IsNormalized(NormalizationForm.FormKD)); - - Console.WriteLine(divider); - - Console.WriteLine("Set string s2 to each normalized form of string s1."); - Console.WriteLine(); - Console.WriteLine("U+1E09 = LATIN SMALL LETTER C WITH CEDILLA AND ACUTE"); - Console.WriteLine("U+0033 = DIGIT THREE"); - Console.WriteLine("U+2044 = FRACTION SLASH"); - Console.WriteLine("U+0034 = DIGIT FOUR"); - Console.WriteLine(divider); - - s2 = s1.Normalize(); - Console.Write("B1) Is s2 normalized to the default form (Form C)?: "); - Console.WriteLine(s2.IsNormalized()); - Show("s2", s2); - Console.WriteLine(); - - s2 = s1.Normalize(NormalizationForm.FormC); - Console.Write("B2) Is s2 normalized to Form C?: "); - Console.WriteLine(s2.IsNormalized(NormalizationForm.FormC)); - Show("s2", s2); - Console.WriteLine(); - - s2 = s1.Normalize(NormalizationForm.FormD); - Console.Write("B3) Is s2 normalized to Form D?: "); - Console.WriteLine(s2.IsNormalized(NormalizationForm.FormD)); - Show("s2", s2); - Console.WriteLine(); - - s2 = s1.Normalize(NormalizationForm.FormKC); - Console.Write("B4) Is s2 normalized to Form KC?: "); - Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKC)); - Show("s2", s2); - Console.WriteLine(); - - s2 = s1.Normalize(NormalizationForm.FormKD); - Console.Write("B5) Is s2 normalized to Form KD?: "); - Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKD)); - Show("s2", s2); - Console.WriteLine(); + // Character c; combining characters acute and cedilla; character 3/4 + string s1 = new(['\u0063', '\u0301', '\u0327', '\u00BE']); + string s2 = null; + string divider = new('-', 80); + divider = string.Concat(Environment.NewLine, divider, Environment.NewLine); + + Show("s1", s1); + Console.WriteLine(); + Console.WriteLine("U+0063 = LATIN SMALL LETTER C"); + Console.WriteLine("U+0301 = COMBINING ACUTE ACCENT"); + Console.WriteLine("U+0327 = COMBINING CEDILLA"); + Console.WriteLine("U+00BE = VULGAR FRACTION THREE QUARTERS"); + Console.WriteLine(divider); + + Console.WriteLine($"A1) Is s1 normalized to the default form (Form C)?: {s1.IsNormalized()}"); + Console.WriteLine($"A2) Is s1 normalized to Form C?: {s1.IsNormalized(NormalizationForm.FormC)}"); + Console.WriteLine($"A3) Is s1 normalized to Form D?: {s1.IsNormalized(NormalizationForm.FormD)}"); + Console.WriteLine($"A4) Is s1 normalized to Form KC?: {s1.IsNormalized(NormalizationForm.FormKC)}"); + Console.WriteLine($"A5) Is s1 normalized to Form KD?: {s1.IsNormalized(NormalizationForm.FormKD)}"); + + Console.WriteLine(divider); + + Console.WriteLine("Set string s2 to each normalized form of string s1."); + Console.WriteLine(); + Console.WriteLine("U+1E09 = LATIN SMALL LETTER C WITH CEDILLA AND ACUTE"); + Console.WriteLine("U+0033 = DIGIT THREE"); + Console.WriteLine("U+2044 = FRACTION SLASH"); + Console.WriteLine("U+0034 = DIGIT FOUR"); + Console.WriteLine(divider); + + s2 = s1.Normalize(); + Console.Write("B1) Is s2 normalized to the default form (Form C)?: "); + Console.WriteLine(s2.IsNormalized()); + Show("s2", s2); + Console.WriteLine(); + + s2 = s1.Normalize(NormalizationForm.FormC); + Console.Write("B2) Is s2 normalized to Form C?: "); + Console.WriteLine(s2.IsNormalized(NormalizationForm.FormC)); + Show("s2", s2); + Console.WriteLine(); + + s2 = s1.Normalize(NormalizationForm.FormD); + Console.Write("B3) Is s2 normalized to Form D?: "); + Console.WriteLine(s2.IsNormalized(NormalizationForm.FormD)); + Show("s2", s2); + Console.WriteLine(); + + s2 = s1.Normalize(NormalizationForm.FormKC); + Console.Write("B4) Is s2 normalized to Form KC?: "); + Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKC)); + Show("s2", s2); + Console.WriteLine(); + + s2 = s1.Normalize(NormalizationForm.FormKD); + Console.Write("B5) Is s2 normalized to Form KD?: "); + Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKD)); + Show("s2", s2); + Console.WriteLine(); } private static void Show(string title, string s) { - Console.Write("Characters in string {0} = ", title); - foreach(short x in s) { - Console.Write("{0:X4} ", x); - } - Console.WriteLine(); + Console.Write($"Characters in string {title} = "); + foreach (short x in s) + { + Console.Write($"{x:X4} "); + } + Console.WriteLine(); } } /* @@ -126,4 +122,4 @@ Set string s2 to each normalized form of string s1. Characters in string s2 = 0063 0327 0301 0033 2044 0034 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs b/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs index c9da93895ba..76c0dafd51d 100644 --- a/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs +++ b/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs @@ -1,19 +1,19 @@ -using System; +using System; public class Example { public static void Main() { // - String s = null; - + string s = null; + Console.WriteLine($"The value of the string is '{s}'"); - try + try { Console.WriteLine($"String length is {s.Length}"); } - catch (NullReferenceException e) + catch (NullReferenceException e) { Console.WriteLine(e.Message); } @@ -30,11 +30,11 @@ public class Empty public void Test() { // - String s = ""; + string s = ""; Console.WriteLine($"The length of '{s}' is {s.Length}."); // The example displays the following output: - // The length of '' is 0. + // The length of '' is 0. // } } diff --git a/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs b/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs index 004791df431..68c224af75a 100644 --- a/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs +++ b/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs @@ -4,27 +4,27 @@ class Sample { public static void Main() { - // - string s1 = "abcd"; - string s2 = ""; - string s3 = null; + // + string s1 = "abcd"; + string s2 = ""; + string s3 = null; - Console.WriteLine("String s1 {0}.", Test(s1)); - Console.WriteLine("String s2 {0}.", Test(s2)); - Console.WriteLine("String s3 {0}.", Test(s3)); + Console.WriteLine($"String s1 {Test(s1)}."); + Console.WriteLine($"String s2 {Test(s2)}."); + Console.WriteLine($"String s3 {Test(s3)}."); - String Test(string s) - { - if (String.IsNullOrEmpty(s)) - return "is null or empty"; - else - return String.Format("(\"{0}\") is neither null nor empty", s); - } + string Test(string s) + { + if (string.IsNullOrEmpty(s)) + return "is null or empty"; + else + return $"(\"{s}\") is neither null nor empty"; + } - // The example displays the following output: - // String s1 ("abcd") is neither null nor empty. - // String s2 is null or empty. - // String s3 is null or empty. - // + // The example displays the following output: + // String s1 ("abcd") is neither null nor empty. + // String s2 is null or empty. + // String s3 is null or empty. + // } } diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs new file mode 100644 index 00000000000..a6cb7b07baa --- /dev/null +++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs @@ -0,0 +1,2 @@ +IsNullOrWhiteSpaceEquivalentExample.Run(); +IsNullOrWhiteSpaceExample.Run(); diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj b/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs index 0cd03284113..80a4ace4701 100644 --- a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs +++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs @@ -1,17 +1,14 @@ using System; -public class Example +public class IsNullOrWhiteSpaceEquivalentExample { - public static void Main() - { - Console.WriteLine(ShowCode()); - } + public static void Run() => Console.WriteLine(ShowCode()); - private static bool ShowCode() - { - string value = null; - // - return String.IsNullOrEmpty(value) || value.Trim().Length == 0; - // - } + private static bool ShowCode() + { + string value = null; + // + return string.IsNullOrEmpty(value) || value.Trim().Length == 0; + // + } } diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs index 48a2dde44c3..7763fdcb924 100644 --- a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs +++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs @@ -1,16 +1,16 @@ // using System; -public class Example +public class IsNullOrWhiteSpaceExample { - public static void Main() - { - string[] values = { null, String.Empty, "ABCDE", - new String(' ', 20), " \t ", - new String('\u2000', 10) }; - foreach (string value in values) - Console.WriteLine(String.IsNullOrWhiteSpace(value)); - } + public static void Run() + { + string[] values = [ null, string.Empty, "ABCDE", + new string(' ', 20), " \t ", + new string('\u2000', 10) ]; + foreach (string value in values) + Console.WriteLine(string.IsNullOrWhiteSpace(value)); + } } // The example displays the following output: // True @@ -19,4 +19,4 @@ public static void Main() // True // True // True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Join/Program.cs b/snippets/csharp/System/String/Join/Program.cs new file mode 100644 index 00000000000..44d79eafae7 --- /dev/null +++ b/snippets/csharp/System/String/Join/Program.cs @@ -0,0 +1,7 @@ +JoinArrayExample.Run(); +Sample.Run(); +JoinListExample.Run(); +JoinAlphabetExample.Run(); +JoinAnimalsExample.Run(); +JoinEnumerableExample.Run(); +JoinTest.Run(); diff --git a/snippets/csharp/System/String/Join/Project.csproj b/snippets/csharp/System/String/Join/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/Join/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/Join/join1.cs b/snippets/csharp/System/String/Join/join1.cs index 618d055e2bb..12549ff897e 100644 --- a/snippets/csharp/System/String/Join/join1.cs +++ b/snippets/csharp/System/String/Join/join1.cs @@ -2,39 +2,39 @@ using System; using System.Collections.Generic; -public class Example +public class JoinArrayExample { - public static void Main() - { - int maxPrime = 100; - int[] primes = GetPrimes(maxPrime); - Console.WriteLine("Primes less than {0}:", maxPrime); - Console.WriteLine(" {0}", String.Join(" ", primes)); - } + public static void Run() + { + int maxPrime = 100; + int[] primes = GetPrimes(maxPrime); + Console.WriteLine($"Primes less than {maxPrime}:"); + Console.WriteLine($" {string.Join(" ", primes)}"); + } - private static int[] GetPrimes(int maxPrime) - { - Array values = Array.CreateInstance(typeof(int), - new int[] { maxPrime - 1}, new int[] { 2 }); - // Use Sieve of Eratosthenes to determine prime numbers. - for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) - { - - if ((int) values.GetValue(ctr) == 1) continue; - - for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) - if (ctr * multiplier <= maxPrime) - values.SetValue(1, ctr * multiplier); - } - - List primes = new List(); - for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) - if ((int) values.GetValue(ctr) == 0) - primes.Add(ctr); - return primes.ToArray(); - } + private static int[] GetPrimes(int maxPrime) + { + Array values = Array.CreateInstance(typeof(int), + [maxPrime - 1], [2]); + // Use Sieve of Eratosthenes to determine prime numbers. + for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) + { + + if ((int)values.GetValue(ctr) == 1) continue; + + for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) + if (ctr * multiplier <= maxPrime) + values.SetValue(1, ctr * multiplier); + } + + List primes = new(); + for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) + if ((int)values.GetValue(ctr) == 0) + primes.Add(ctr); + return [.. primes]; + } } // The example displays the following output: // Primes less than 100: // 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Join/join2.cs b/snippets/csharp/System/String/Join/join2.cs index 5b2912b9190..92dd8ce00a4 100644 --- a/snippets/csharp/System/String/Join/join2.cs +++ b/snippets/csharp/System/String/Join/join2.cs @@ -3,17 +3,17 @@ class Sample { - public static void Main() + public static void Run() { // - String[] val = {"apple", "orange", "grape", "pear"}; - String sep = ", "; - String result; + string[] val = ["apple", "orange", "grape", "pear"]; + string sep = ", "; + string result; - Console.WriteLine("sep = '{0}'", sep); - Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]); - result = String.Join(sep, val, 1, 2); - Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result); + Console.WriteLine($"sep = '{sep}'"); + Console.WriteLine($"val[] = {{'{val[0]}' '{val[1]}' '{val[2]}' '{val[3]}'}}"); + result = string.Join(sep, val, 1, 2); + Console.WriteLine($"String.Join(sep, val, 1, 2) = '{result}'"); // This example produces the following results: // sep = ', ' diff --git a/snippets/csharp/System/String/Join/join3.cs b/snippets/csharp/System/String/Join/join3.cs index b9fee22660b..5e9a2146b9f 100644 --- a/snippets/csharp/System/String/Join/join3.cs +++ b/snippets/csharp/System/String/Join/join3.cs @@ -2,39 +2,39 @@ using System; using System.Collections.Generic; -public class Example +public class JoinListExample { - public static void Main() - { - int maxPrime = 100; - List primes = GetPrimes(maxPrime); - Console.WriteLine("Primes less than {0}:", maxPrime); - Console.WriteLine(" {0}", String.Join(" ", primes)); - } + public static void Run() + { + int maxPrime = 100; + List primes = GetPrimes(maxPrime); + Console.WriteLine($"Primes less than {maxPrime}:"); + Console.WriteLine($" {string.Join(" ", primes)}"); + } - private static List GetPrimes(int maxPrime) - { - Array values = Array.CreateInstance(typeof(int), - new int[] { maxPrime - 1}, new int[] { 2 }); - // Use Sieve of Eratosthenes to determine prime numbers. - for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) - { - - if ((int) values.GetValue(ctr) == 1) continue; - - for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) - if (ctr * multiplier <= maxPrime) - values.SetValue(1, ctr * multiplier); - } - - List primes = new List(); - for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) - if ((int) values.GetValue(ctr) == 0) - primes.Add(ctr); - return primes; - } + private static List GetPrimes(int maxPrime) + { + Array values = Array.CreateInstance(typeof(int), + [maxPrime - 1], [2]); + // Use Sieve of Eratosthenes to determine prime numbers. + for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) + { + + if ((int)values.GetValue(ctr) == 1) continue; + + for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) + if (ctr * multiplier <= maxPrime) + values.SetValue(1, ctr * multiplier); + } + + List primes = new(); + for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) + if ((int)values.GetValue(ctr) == 0) + primes.Add(ctr); + return primes; + } } // The example displays the following output: // Primes less than 100: // 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Join/join4.cs b/snippets/csharp/System/String/Join/join4.cs index 1eaea09860d..2e9b986dd1b 100644 --- a/snippets/csharp/System/String/Join/join4.cs +++ b/snippets/csharp/System/String/Join/join4.cs @@ -3,24 +3,24 @@ using System.Collections.Generic; using System.Linq; -public class Example +public class JoinAlphabetExample { - public static void Main() - { - string output = String.Join(" ", GetAlphabet(true).Where( letter => - letter.CompareTo("M") >= 0)); - Console.WriteLine(output); - } + public static void Run() + { + string output = string.Join(" ", GetAlphabet(true).Where(letter => + letter.CompareTo("M") >= 0)); + Console.WriteLine(output); + } - private static List GetAlphabet(bool upper) - { - List alphabet = new List(); - int charValue = upper ? 65 : 97; - for (int ctr = 0; ctr <= 25; ctr++) - alphabet.Add(((char)(charValue + ctr)).ToString()); - return alphabet; - } + private static List GetAlphabet(bool upper) + { + List alphabet = new(); + int charValue = upper ? 65 : 97; + for (int ctr = 0; ctr <= 25; ctr++) + alphabet.Add(((char)(charValue + ctr)).ToString()); + return alphabet; + } } // The example displays the following output: // M N O P Q R S T U V W X Y Z -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Join/join5.cs b/snippets/csharp/System/String/Join/join5.cs index 240ee2c40f9..1b4995aca74 100644 --- a/snippets/csharp/System/String/Join/join5.cs +++ b/snippets/csharp/System/String/Join/join5.cs @@ -5,33 +5,32 @@ public class Animal { - public string Kind; - public string Order; - - public Animal(string kind, string order) - { - this.Kind = kind; - this.Order = order; - } - - public override string ToString() - { - return this.Kind; - } + public string Kind; + public string Order; + + public Animal(string kind, string order) + { + this.Kind = kind; + this.Order = order; + } + + public override string ToString() => this.Kind; } -public class Example +public class JoinAnimalsExample { - public static void Main() - { - List animals = new List(); - animals.Add(new Animal("Squirrel", "Rodent")); - animals.Add(new Animal("Gray Wolf", "Carnivora")); - animals.Add(new Animal("Capybara", "Rodent")); - string output = String.Join(" ", animals.Where( animal => - (animal.Order == "Rodent"))); - Console.WriteLine(output); - } + public static void Run() + { + List animals = new() + { + new Animal("Squirrel", "Rodent"), + new Animal("Gray Wolf", "Carnivora"), + new Animal("Capybara", "Rodent") + }; + string output = string.Join(" ", animals.Where(animal => + (animal.Order == "Rodent"))); + Console.WriteLine(output); + } } // The example displays the following output: // Squirrel Capybara diff --git a/snippets/csharp/System/String/Join/join6.cs b/snippets/csharp/System/String/Join/join6.cs index 1e98285e8ba..6f8e34a338a 100644 --- a/snippets/csharp/System/String/Join/join6.cs +++ b/snippets/csharp/System/String/Join/join6.cs @@ -2,39 +2,39 @@ using System; using System.Collections.Generic; -public class Example +public class JoinEnumerableExample { - public static void Main() - { - int maxPrime = 100; - List primes = GetPrimes(maxPrime); - Console.WriteLine("Primes less than {0}:", maxPrime); - Console.WriteLine(" {0}", String.Join(" ", primes)); - } + public static void Run() + { + int maxPrime = 100; + List primes = GetPrimes(maxPrime); + Console.WriteLine($"Primes less than {maxPrime}:"); + Console.WriteLine($" {string.Join(" ", primes)}"); + } - private static List GetPrimes(int maxPrime) - { - Array values = Array.CreateInstance(typeof(int), - new int[] { maxPrime - 1}, new int[] { 2 }); - // Use Sieve of Eratosthenes to determine prime numbers. - for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) - { - - if ((int) values.GetValue(ctr) == 1) continue; - - for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) - if (ctr * multiplier <= maxPrime) - values.SetValue(1, ctr * multiplier); - } - - List primes = new List(); - for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) - if ((int) values.GetValue(ctr) == 0) - primes.Add(ctr); - return primes; - } + private static List GetPrimes(int maxPrime) + { + Array values = Array.CreateInstance(typeof(int), + [maxPrime - 1], [2]); + // Use Sieve of Eratosthenes to determine prime numbers. + for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++) + { + + if ((int)values.GetValue(ctr) == 1) continue; + + for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++) + if (ctr * multiplier <= maxPrime) + values.SetValue(1, ctr * multiplier); + } + + List primes = new(); + for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) + if ((int)values.GetValue(ctr) == 0) + primes.Add(ctr); + return primes; + } } // The example displays the following output: // Primes less than 100: // 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 -// \ No newline at end of file +//
diff --git a/snippets/csharp/System/String/Join/stringjoin.cs b/snippets/csharp/System/String/Join/stringjoin.cs index 1de6bfd4ba8..fc6dfb23fec 100644 --- a/snippets/csharp/System/String/Join/stringjoin.cs +++ b/snippets/csharp/System/String/Join/stringjoin.cs @@ -3,7 +3,7 @@ public class JoinTest { - public static void Main() + public static void Run() { Console.WriteLine(MakeLine(0, 5, ", ")); Console.WriteLine(MakeLine(1, 6, " ")); @@ -13,12 +13,12 @@ public static void Main() private static string MakeLine(int initVal, int multVal, string sep) { - string [] sArr = new string [10]; + string[] sArr = new string[10]; for (int i = initVal; i < initVal + 10; i++) - sArr[i - initVal] = String.Format("{0,-3}", i * multVal); + sArr[i - initVal] = $"{i * multVal,-3}"; - return String.Join(sep, sArr); + return string.Join(sep, sArr); } } // The example displays the following output: @@ -26,4 +26,4 @@ private static string MakeLine(int initVal, int multVal, string sep) // 6 12 18 24 30 36 42 48 54 60 // 81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162 // 28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs b/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs index 99fb57f04c5..b4838a6ecb2 100644 --- a/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs +++ b/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs @@ -4,49 +4,49 @@ public class TestLastIndexOf { - public static void Main() - { - string filename; - - filename = ExtractFilename(@"C:\temp\"); - Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename); - - filename = ExtractFilename(@"C:\temp\delegate.txt"); - Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename); + public static void Run() + { + string filename; - filename = ExtractFilename("delegate.txt"); - Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename); - - filename = ExtractFilename(@"C:\temp\notafile.txt"); - Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename); - } + filename = ExtractFilename(@"C:\temp\"); + Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}"); - public static string ExtractFilename(string filepath) - { - // If path ends with a "\", it's a path only so return String.Empty. - if (filepath.Trim().EndsWith(@"\")) - return String.Empty; - - // Determine where last backslash is. - int position = filepath.LastIndexOf('\\'); - // If there is no backslash, assume that this is a filename. - if (position == -1) - { - // Determine whether file exists in the current directory. - if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath)) - return filepath; - else - return String.Empty; - } - else - { - // Determine whether file exists using filepath. - if (File.Exists(filepath)) - // Return filename without file path. - return filepath.Substring(position + 1); - else - return String.Empty; - } - } + filename = ExtractFilename(@"C:\temp\delegate.txt"); + Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}"); + + filename = ExtractFilename("delegate.txt"); + Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}"); + + filename = ExtractFilename(@"C:\temp\notafile.txt"); + Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}"); + } + + public static string ExtractFilename(string filepath) + { + // If path ends with a "\", it's a path only so return String.Empty. + if (filepath.Trim().EndsWith(@"\")) + return string.Empty; + + // Determine where last backslash is. + int position = filepath.LastIndexOf('\\'); + // If there is no backslash, assume that this is a filename. + if (position == -1) + { + // Determine whether file exists in the current directory. + if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath)) + return filepath; + else + return string.Empty; + } + else + { + // Determine whether file exists using filepath. + if (File.Exists(filepath)) + // Return filename without file path. + return filepath.Substring(position + 1); + else + return string.Empty; + } + } } // diff --git a/snippets/csharp/System/String/LastIndexOf/Program.cs b/snippets/csharp/System/String/LastIndexOf/Program.cs new file mode 100644 index 00000000000..4834bb32f7e --- /dev/null +++ b/snippets/csharp/System/String/LastIndexOf/Program.cs @@ -0,0 +1,13 @@ +TestLastIndexOf.Run(); +LastIndexOfTagsExample.Run(); +LastIndexOfIgnorable21Example.Run(); +LastIndexOfIgnorable22Example.Run(); +LastIndexOfIgnorable23Example.Run(); +LastIndexOfIgnorable24Example.Run(); +LastIndexOfIgnorable25Example.Run(); +LastIndexOfIgnorable26Example.Run(); +LastIndexOfCharSample.Run(); +LastIndexOfCharRangeSample.Run(); +LastIndexOfStringSample.Run(); +LastIndexOfStringRangeSample.Run(); +LastIndexOfComparisonSample.Run(); diff --git a/snippets/csharp/System/String/LastIndexOf/Project.csproj b/snippets/csharp/System/String/LastIndexOf/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/LastIndexOf/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs index 5414e083ae4..0961a734067 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable21Example { - public static void Main() + public static void Run() { // string s1 = "ani\u00ADmal"; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs index 702370a2c0c..8a3ea8868b0 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable22Example { - public static void Main() + public static void Run() { // int position = 0; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs index 2a8c70c7bf5..b9b084d12fd 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable23Example { - public static void Main() + public static void Run() { // int position = 0; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs index c16a2a6a53a..189cb7aa75e 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable24Example { - public static void Main() + public static void Run() { // string searchString = "\u00ADm"; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs index 5d5af49ef14..cb81ae29475 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable25Example { - public static void Main() + public static void Run() { // string searchString = "\u00ADm"; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs index a78ec97f8e7..b2d68f94004 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs @@ -1,8 +1,8 @@ using System; -public class Example +public class LastIndexOfIgnorable26Example { - public static void Main() + public static void Run() { // string s1 = "ani\u00ADmal"; diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs index 4a52a79b1dc..61f4299bc15 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs @@ -1,58 +1,58 @@ // using System; -public class Example +public class LastIndexOfTagsExample { - public static void Main() - { - string[] strSource = { "This is bold text", "

This is large Text

", + public static void Run() + { + string[] strSource = [ "This is bold text", "

This is large Text

", "This has multiple tags", "This has embedded tags.", - "This line ends with a greater than symbol and should not be modified>" }; + "This line ends with a greater than symbol and should not be modified>" ]; - // Strip HTML start and end tags from each string if they are present. - foreach (string s in strSource) - { - Console.WriteLine("Before: " + s); - string item = s; - // Use EndsWith to find a tag at the end of the line. - if (item.Trim().EndsWith(">")) - { - // Locate the opening tag. - int endTagStartPosition = item.LastIndexOf("= 0 ) - item = item.Substring(0, endTagStartPosition); - - // Use StartsWith to find the opening tag. - if (item.Trim().StartsWith("<")) + // Strip HTML start and end tags from each string if they are present. + foreach (string s in strSource) + { + Console.WriteLine("Before: " + s); + string item = s; + // Use EndsWith to find a tag at the end of the line. + if (item.Trim().EndsWith(">")) { - // Locate the end of opening tab. - int openTagEndPosition = item.IndexOf(">"); - // Remove the identified section, if it is valid. - if (openTagEndPosition >= 0) - item = item.Substring(openTagEndPosition + 1); - } - } - // Display the trimmed string. - Console.WriteLine("After: " + item); - Console.WriteLine(); - } - } + // Locate the opening tag. + int endTagStartPosition = item.LastIndexOf("= 0) + item = item.Substring(0, endTagStartPosition); + + // Use StartsWith to find the opening tag. + if (item.Trim().StartsWith("<")) + { + // Locate the end of opening tab. + int openTagEndPosition = item.IndexOf(">"); + // Remove the identified section, if it is valid. + if (openTagEndPosition >= 0) + item = item.Substring(openTagEndPosition + 1); + } + } + // Display the trimmed string. + Console.WriteLine("After: " + item); + Console.WriteLine(); + } + } } // The example displays the following output: // Before: This is bold text // After: This is bold text -// +// // Before:

This is large Text

// After: This is large Text -// +// // Before: This has multiple tags // After: This has multiple tags -// +// // Before: This has embedded tags. // After: This has embedded tags. -// +// // Before: This line ends with a greater than symbol and should not be modified> // After: This line ends with a greater than symbol and should not be modified> -//
\ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof1.cs b/snippets/csharp/System/String/LastIndexOf/lastixof1.cs index fc60630d9c4..5e3e7d2ef0a 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastixof1.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastixof1.cs @@ -2,31 +2,33 @@ // Sample for String.LastIndexOf(Char, Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfCharSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; - start = str.Length-1; - Console.WriteLine("All occurrences of 't' from position {0} to 0.", start); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("The letter 't' occurs at position(s): "); + start = str.Length - 1; + Console.WriteLine($"All occurrences of 't' from position {start} to 0."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write("The letter 't' occurs at position(s): "); - at = 0; - while((start > -1) && (at > -1)) + at = 0; + while ((start > -1) && (at > -1)) { - at = str.LastIndexOf('t', start); - if (at > -1) + at = str.LastIndexOf('t', start); + if (at > -1) { - Console.Write("{0} ", at); - start = at - 1; + Console.Write($"{at} "); + start = at - 1; } } - Console.Write("{0}{0}{0}", Environment.NewLine); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -38,4 +40,4 @@ All occurrences of 't' from position 66 to 0. The letter 't' occurs at position(s): 64 55 44 41 33 11 7 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof2.cs b/snippets/csharp/System/String/LastIndexOf/lastixof2.cs index 09a23421cc9..4a92d56d2df 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastixof2.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastixof2.cs @@ -2,36 +2,38 @@ // Sample for String.LastIndexOf(Char, Int32, Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfCharRangeSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; - int count; - int end; + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; + int count; + int end; - start = str.Length-1; - end = start/2 - 1; - Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("The letter 't' occurs at position(s): "); + start = str.Length - 1; + end = start / 2 - 1; + Console.WriteLine($"All occurrences of 't' from position {start} to {end}."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write("The letter 't' occurs at position(s): "); - count = 0; - at = 0; - while((start > -1) && (at > -1)) + count = 0; + at = 0; + while ((start > -1) && (at > -1)) { - count = start - end; //Count must be within the substring. - at = str.LastIndexOf('t', start, count); - if (at > -1) + count = start - end; //Count must be within the substring. + at = str.LastIndexOf('t', start, count); + if (at > -1) { - Console.Write("{0} ", at); - start = at - 1; + Console.Write($"{at} "); + start = at - 1; } } - Console.Write("{0}{0}{0}", Environment.NewLine); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -45,4 +47,4 @@ All occurrences of 't' from position 66 to 32. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof7.cs b/snippets/csharp/System/String/LastIndexOf/lastixof7.cs index 8f6333c2009..024ec87be7e 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastixof7.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastixof7.cs @@ -2,31 +2,33 @@ // Sample for String.LastIndexOf(String, Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfStringSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; - start = str.Length-1; - Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("The string 'he' occurs at position(s): "); + start = str.Length - 1; + Console.WriteLine($"All occurrences of 'he' from position {start} to 0."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write("The string 'he' occurs at position(s): "); - at = 0; - while((start > -1) && (at > -1)) + at = 0; + while ((start > -1) && (at > -1)) { - at = str.LastIndexOf("he", start); - if (at > -1) + at = str.LastIndexOf("he", start); + if (at > -1) { - Console.Write("{0} ", at); - start = at - 1; + Console.Write($"{at} "); + start = at - 1; } } - Console.Write("{0}{0}{0}", Environment.NewLine); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -40,4 +42,4 @@ All occurrences of 'he' from position 66 to 0. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof8.cs b/snippets/csharp/System/String/LastIndexOf/lastixof8.cs index 5870a79733d..f5740de3531 100644 --- a/snippets/csharp/System/String/LastIndexOf/lastixof8.cs +++ b/snippets/csharp/System/String/LastIndexOf/lastixof8.cs @@ -2,36 +2,38 @@ // Sample for String.LastIndexOf(String, Int32, Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfStringRangeSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; - int count; - int end; + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; + int count; + int end; - start = str.Length-1; - end = start/2 - 1; - Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("The string 'he' occurs at position(s): "); + start = str.Length - 1; + end = start / 2 - 1; + Console.WriteLine($"All occurrences of 'he' from position {start} to {end}."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write("The string 'he' occurs at position(s): "); - count = 0; - at = 0; - while((start > -1) && (at > -1)) + count = 0; + at = 0; + while ((start > -1) && (at > -1)) { - count = start - end; //Count must be within the substring. - at = str.LastIndexOf("he", start, count); - if (at > -1) + count = start - end; //Count must be within the substring. + at = str.LastIndexOf("he", start, count); + if (at > -1) { - Console.Write("{0} ", at); - start = at - 1; + Console.Write($"{at} "); + start = at - 1; } } - Console.Write("{0}{0}{0}", Environment.NewLine); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -43,4 +45,4 @@ All occurrences of 'he' from position 66 to 32. The string 'he' occurs at position(s): 56 45 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOf/liocmp.cs b/snippets/csharp/System/String/LastIndexOf/liocmp.cs index 39a9cc84947..8228ecdb874 100644 --- a/snippets/csharp/System/String/LastIndexOf/liocmp.cs +++ b/snippets/csharp/System/String/LastIndexOf/liocmp.cs @@ -1,89 +1,86 @@ // -// This code example demonstrates the +// This code example demonstrates the // System.String.LastIndexOf(String, ..., StringComparison) methods. using System; using System.Threading; -using System.Globalization; -class Sample + +class LastIndexOfComparisonSample { - public static void Main() + public static void Run() { - string intro = "Find the last occurrence of a character using different " + - "values of StringComparison."; - string resultFmt = "Comparison: {0,-28} Location: {1,3}"; - -// Define a string to search for. -// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE - string CapitalAWithRing = "\u00c5"; - -// Define a string to search. -// The result of combining the characters LATIN SMALL LETTER A and COMBINING -// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character -// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). - string cat = "A Cheshire c" + "\u0061\u030a" + "t"; - int loc = 0; - StringComparison[] scValues = { + string intro = "Find the last occurrence of a character using different " + + "values of StringComparison."; + string resultFmt = "Comparison: {0,-28} Location: {1,3}"; + + // Define a string to search for. + // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE + string CapitalAWithRing = "\u00c5"; + + // Define a string to search. + // The result of combining the characters LATIN SMALL LETTER A and COMBINING + // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character + // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). + string cat = "A Cheshire c" + "\u0061\u030a" + "t"; + int loc = 0; + StringComparison[] scValues = [ StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, StringComparison.InvariantCulture, StringComparison.InvariantCultureIgnoreCase, StringComparison.Ordinal, - StringComparison.OrdinalIgnoreCase }; - -// Clear the screen and display an introduction. - Console.Clear(); - Console.WriteLine(intro); - -// Display the current culture because culture affects the result. For example, -// try this code example with the "sv-SE" (Swedish-Sweden) culture. - - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - Console.WriteLine("The current culture is \"{0}\" - {1}.", - Thread.CurrentThread.CurrentCulture.Name, - Thread.CurrentThread.CurrentCulture.DisplayName); - -// Display the string to search for and the string to search. - Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", - CapitalAWithRing, cat); - Console.WriteLine(); - -// Note that in each of the following searches, we look for -// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains -// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates -// the string was not found. -// Search using different values of StringComparsion. Specify the start -// index and count. - - Console.WriteLine("Part 1: Start index and count are specified."); - foreach (StringComparison sc in scValues) + StringComparison.OrdinalIgnoreCase ]; + + // Clear the screen and display an introduction. + Console.Clear(); + Console.WriteLine(intro); + + // Display the current culture because culture affects the result. For example, + // try this code example with the "sv-SE" (Swedish-Sweden) culture. + + Thread.CurrentThread.CurrentCulture = new("en-US"); + Console.WriteLine($"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."); + + // Display the string to search for and the string to search. + Console.WriteLine($"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\""); + Console.WriteLine(); + + // Note that in each of the following searches, we look for + // LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains + // LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates + // the string was not found. + // Search using different values of StringComparsion. Specify the start + // index and count. + + Console.WriteLine("Part 1: Start index and count are specified."); + foreach (StringComparison sc in scValues) { - loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc); + Console.WriteLine(resultFmt, sc, loc); } -// Search using different values of StringComparsion. Specify the -// start index. - Console.WriteLine("\nPart 2: Start index is specified."); - foreach (StringComparison sc in scValues) + // Search using different values of StringComparsion. Specify the + // start index. + Console.WriteLine("\nPart 2: Start index is specified."); + foreach (StringComparison sc in scValues) { - loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc); + Console.WriteLine(resultFmt, sc, loc); } -// Search using different values of StringComparsion. - Console.WriteLine("\nPart 3: Neither start index nor count is specified."); - foreach (StringComparison sc in scValues) + // Search using different values of StringComparsion. + Console.WriteLine("\nPart 3: Neither start index nor count is specified."); + foreach (StringComparison sc in scValues) { - loc = cat.LastIndexOf(CapitalAWithRing, sc); - Console.WriteLine(resultFmt, sc, loc); + loc = cat.LastIndexOf(CapitalAWithRing, sc); + Console.WriteLine(resultFmt, sc, loc); } } } /* -Note: This code example was executed on a console whose user interface +Note: This code example was executed on a console whose user interface culture is "en-US" (English-United States). This code example produces the following results: @@ -117,4 +114,4 @@ public static void Main() Comparison: OrdinalIgnoreCase Location: -1 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOfAny/Program.cs b/snippets/csharp/System/String/LastIndexOfAny/Program.cs new file mode 100644 index 00000000000..0ed1a250cee --- /dev/null +++ b/snippets/csharp/System/String/LastIndexOfAny/Program.cs @@ -0,0 +1,3 @@ +LastIndexOfAnySample.Run(); +LastIndexOfAnyStartSample.Run(); +LastIndexOfAnyRangeSample.Run(); diff --git a/snippets/csharp/System/String/LastIndexOfAny/Project.csproj b/snippets/csharp/System/String/LastIndexOfAny/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/LastIndexOfAny/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs index 2a7cf5a248c..837d91f059f 100644 --- a/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs +++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs @@ -2,28 +2,30 @@ // Sample for String.LastIndexOfAny(Char[]) using System; -class Sample { - public static void Main() { +class LastIndexOfAnySample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; - string target = "is"; - char[] anyOf = target.ToCharArray(); + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; + string target = "is"; + char[] anyOf = target.ToCharArray(); - start = str.Length-1; - Console.WriteLine("The last character occurrence from position {0} to 0.", start); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("A character in '{0}' occurs at position: ", target); + start = str.Length - 1; + Console.WriteLine($"The last character occurrence from position {start} to 0."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write($"A character in '{target}' occurs at position: "); - at = str.LastIndexOfAny(anyOf); - if (at > -1) - Console.Write(at); - else - Console.Write("(not found)"); - Console.Write("{0}{0}{0}", Environment.NewLine); + at = str.LastIndexOfAny(anyOf); + if (at > -1) + Console.Write(at); + else + Console.Write("(not found)"); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -37,4 +39,4 @@ The last character occurrence from position 66 to 0. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs index 9dc667f3f92..d3365e029ab 100644 --- a/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs +++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs @@ -2,28 +2,30 @@ // Sample for String.LastIndexOfAny(Char[], Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfAnyStartSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; - string target = "is"; - char[] anyOf = target.ToCharArray(); + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; + string target = "is"; + char[] anyOf = target.ToCharArray(); - start = (str.Length-1)/2; - Console.WriteLine("The last character occurrence from position {0} to 0.", start); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("A character in '{0}' occurs at position: ", target); + start = (str.Length - 1) / 2; + Console.WriteLine($"The last character occurrence from position {start} to 0."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write($"A character in '{target}' occurs at position: "); - at = str.LastIndexOfAny(anyOf, start); - if (at > -1) - Console.Write(at); - else - Console.Write("(not found)"); - Console.Write("{0}{0}{0}", Environment.NewLine); + at = str.LastIndexOfAny(anyOf, start); + if (at > -1) + Console.Write(at); + else + Console.Write("(not found)"); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -37,4 +39,4 @@ The last character occurrence from position 33 to 0. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs index 6d469b914b0..693f05ef2d4 100644 --- a/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs +++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs @@ -2,30 +2,32 @@ // Sample for String.LastIndexOfAny(Char[], Int32, Int32) using System; -class Sample { - public static void Main() { +class LastIndexOfAnyRangeSample +{ + public static void Run() + { - string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; - string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; - string str = "Now is the time for all good men to come to the aid of their party."; - int start; - int at; - int count; - string target = "aid"; - char[] anyOf = target.ToCharArray(); + string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"; + string br2 = "0123456789012345678901234567890123456789012345678901234567890123456"; + string str = "Now is the time for all good men to come to the aid of their party."; + int start; + int at; + int count; + string target = "aid"; + char[] anyOf = target.ToCharArray(); - start = ((str.Length-1)*2)/3; - count = (str.Length-1)/3; - Console.WriteLine("The last character occurrence from position {0} for {1} characters.", start, count); - Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); - Console.Write("A character in '{0}' occurs at position: ", target); + start = ((str.Length - 1) * 2) / 3; + count = (str.Length - 1) / 3; + Console.WriteLine($"The last character occurrence from position {start} for {count} characters."); + Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str); + Console.Write($"A character in '{target}' occurs at position: "); - at = str.LastIndexOfAny(anyOf, start, count); - if (at > -1) - Console.Write(at); - else - Console.Write("(not found)"); - Console.Write("{0}{0}{0}", Environment.NewLine); + at = str.LastIndexOfAny(anyOf, start, count); + if (at > -1) + Console.Write(at); + else + Console.Write("(not found)"); + Console.Write("{0}{0}{0}", Environment.NewLine); } } /* @@ -37,4 +39,4 @@ public static void Main() { A character in 'aid' occurs at position: 27 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Length/length.cs b/snippets/csharp/System/String/Length/length.cs index 943ec2dc761..f5b68edd556 100644 --- a/snippets/csharp/System/String/Length/length.cs +++ b/snippets/csharp/System/String/Length/length.cs @@ -6,11 +6,11 @@ public static void Main() { // string str = "abcdefg"; - Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length); - Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length); + Console.WriteLine($"1) The length of '{str}' is {str.Length}"); + Console.WriteLine($"2) The length of '{"xyz"}' is {"xyz".Length}"); int length = str.Length; - Console.WriteLine("3) The length of '{0}' is {1}", str, length); + Console.WriteLine($"3) The length of '{str}' is {length}"); // This example displays the following output: // 1) The length of 'abcdefg' is 7 diff --git a/snippets/csharp/System/String/Overview/System.String.Class.cs b/snippets/csharp/System/String/Overview/System.String.Class.cs index d45e146c43a..6b311953a7d 100644 --- a/snippets/csharp/System/String/Overview/System.String.Class.cs +++ b/snippets/csharp/System/String/Overview/System.String.Class.cs @@ -1,13 +1,13 @@ using System; -using System.Text; + public class StringClassTest { - public static void Main() - { - // - string characters = "abc\u0000def"; - Console.WriteLine(characters.Length); // Displays 7 - // - } + public static void Main() + { + // + string characters = "abc\u0000def"; + Console.WriteLine(characters.Length); // Displays 7 + // + } } diff --git a/snippets/csharp/System/String/Overview/case1.cs b/snippets/csharp/System/String/Overview/case1.cs index 7bf03f61dbf..2e4209c1a86 100644 --- a/snippets/csharp/System/String/Overview/case1.cs +++ b/snippets/csharp/System/String/Overview/case1.cs @@ -5,51 +5,53 @@ public class Example { - public static void Main() - { - StreamWriter sw = new StreamWriter(@".\case.txt"); - string[] words = { "file", "sıfır", "Dženana" }; - CultureInfo[] cultures = { CultureInfo.InvariantCulture, - new CultureInfo("en-US"), - new CultureInfo("tr-TR") }; + public static void Main() + { + StreamWriter sw = new(@".\case.txt"); + string[] words = ["file", "sıfır", "Dženana"]; + CultureInfo[] cultures = [CultureInfo.InvariantCulture, + new CultureInfo("en-US"), + new CultureInfo("tr-TR")]; - foreach (var word in words) { - sw.WriteLine("{0}:", word); - foreach (var culture in cultures) { - string name = String.IsNullOrEmpty(culture.Name) ? - "Invariant" : culture.Name; - string upperWord = word.ToUpper(culture); - sw.WriteLine(" {0,10}: {1,7} {2, 38}", name, - upperWord, ShowHexValue(upperWord)); - } - sw.WriteLine(); - } - sw.Close(); - } + foreach (string word in words) + { + sw.WriteLine($"{word}:"); + foreach (var culture in cultures) + { + string name = string.IsNullOrEmpty(culture.Name) ? + "Invariant" : culture.Name; + string upperWord = word.ToUpper(culture); + sw.WriteLine($" {name,10}: {upperWord,7} {ShowHexValue(upperWord),38}"); + } + sw.WriteLine(); + } + sw.Close(); + } - private static string ShowHexValue(string s) - { - string retval = null; - foreach (var ch in s) { - byte[] bytes = BitConverter.GetBytes(ch); - retval += String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0]); - } - return retval; - } + private static string ShowHexValue(string s) + { + string retval = null; + foreach (char ch in s) + { + byte[] bytes = BitConverter.GetBytes(ch); + retval += $"{bytes[1]:X2} {bytes[0]:X2} "; + } + return retval; + } } // The example displays the following output: // file: -// Invariant: FILE 00 46 00 49 00 4C 00 45 -// en-US: FILE 00 46 00 49 00 4C 00 45 -// tr-TR: FİLE 00 46 01 30 00 4C 00 45 -// +// Invariant: FILE 00 46 00 49 00 4C 00 45 +// en-US: FILE 00 46 00 49 00 4C 00 45 +// tr-TR: FİLE 00 46 01 30 00 4C 00 45 +// // sıfır: -// Invariant: SıFıR 00 53 01 31 00 46 01 31 00 52 -// en-US: SIFIR 00 53 00 49 00 46 00 49 00 52 -// tr-TR: SIFIR 00 53 00 49 00 46 00 49 00 52 -// +// Invariant: SıFıR 00 53 01 31 00 46 01 31 00 52 +// en-US: SIFIR 00 53 00 49 00 46 00 49 00 52 +// tr-TR: SIFIR 00 53 00 49 00 46 00 49 00 52 +// // Dženana: -// Invariant: DžENANA 01 C5 00 45 00 4E 00 41 00 4E 00 41 -// en-US: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41 -// tr-TR: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41 -//
+// Invariant: DžENANA 01 C5 00 45 00 4E 00 41 00 4E 00 41 +// en-US: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41 +// tr-TR: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41 +// diff --git a/snippets/csharp/System/String/Overview/case2.cs b/snippets/csharp/System/String/Overview/case2.cs index 5e76ba4ba2a..a49b104aec7 100644 --- a/snippets/csharp/System/String/Overview/case2.cs +++ b/snippets/csharp/System/String/Overview/case2.cs @@ -5,38 +5,35 @@ public class Example { - const string disallowed = "file"; - - public static void Main() - { - IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt"); - } + const string disallowed = "file"; - private static void IsAccessAllowed(String resource) - { - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("tr-TR") }; - String scheme = null; - int index = resource.IndexOfAny( new Char[] { '\\', '/' } ); - if (index > 0) - scheme = resource.Substring(0, index - 1); + public static void Main() => IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt"); - // Change the current culture and perform the comparison. - foreach (var culture in cultures) { - Thread.CurrentThread.CurrentCulture = culture; - Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName); - Console.WriteLine(resource); - Console.WriteLine("Access allowed: {0}", - ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase)); - Console.WriteLine(); - } - } + private static void IsAccessAllowed(string resource) + { + CultureInfo[] cultures = [CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("tr-TR")]; + string scheme = null; + int index = resource.IndexOfAny(['\\', '/']); + if (index > 0) + scheme = resource.Substring(0, index - 1); + + // Change the current culture and perform the comparison. + foreach (var culture in cultures) + { + Thread.CurrentThread.CurrentCulture = culture; + Console.WriteLine($"Culture: {CultureInfo.CurrentCulture.DisplayName}"); + Console.WriteLine(resource); + Console.WriteLine($"Access allowed: {!string.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase)}"); + Console.WriteLine(); + } + } } // The example displays the following output: // Culture: English (United States) // FILE:\\\c:\users\user001\documents\FinancialInfo.txt // Access allowed: False -// +// // Culture: Turkish (Turkey) // FILE:\\\c:\users\user001\documents\FinancialInfo.txt // Access allowed: True diff --git a/snippets/csharp/System/String/Overview/compare11.cs b/snippets/csharp/System/String/Overview/compare11.cs index 6ad8377992b..6408bca1b84 100644 --- a/snippets/csharp/System/String/Overview/compare11.cs +++ b/snippets/csharp/System/String/Overview/compare11.cs @@ -5,12 +5,12 @@ public class Example { - public static void Main() - { - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture)); - Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal)); - } + public static void Main() + { + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); + Console.WriteLine(string.Compare("A", "a", StringComparison.CurrentCulture)); + Console.WriteLine(string.Compare("A", "a", StringComparison.Ordinal)); + } } // The example displays the following output: // 1 diff --git a/snippets/csharp/System/String/Overview/compare2.cs b/snippets/csharp/System/String/Overview/compare2.cs index 6a622fd7cf3..f224ef9fc8d 100644 --- a/snippets/csharp/System/String/Overview/compare2.cs +++ b/snippets/csharp/System/String/Overview/compare2.cs @@ -1,62 +1,55 @@ // using System; -using System.Collections; + using System.Collections.Generic; using System.Globalization; - + public class Example { - public static void Main() - { - string[] strings = { "coop", "co-op", "cooperative", - "co\u00ADoperative", "cœur", "coeur" }; - - // Perform a word sort using the current (en-US) culture. - string[] current = new string[strings.Length]; - strings.CopyTo(current, 0); - Array.Sort(current, StringComparer.CurrentCulture); - - // Perform a word sort using the invariant culture. - string[] invariant = new string[strings.Length]; - strings.CopyTo(invariant, 0); - Array.Sort(invariant, StringComparer.InvariantCulture); - - // Perform an ordinal sort. - string[] ordinal = new string[strings.Length]; - strings.CopyTo(ordinal, 0); - Array.Sort(ordinal, StringComparer.Ordinal); - - // Perform a string sort using the current culture. - string[] stringSort = new string[strings.Length]; - strings.CopyTo(stringSort, 0); - Array.Sort(stringSort, new SCompare()); - - // Display array values - Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n", - "Original", "Word Sort", "Invariant Word", - "Ordinal Sort", "String Sort"); - for (int ctr = 0; ctr < strings.Length; ctr++) - Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", - strings[ctr], current[ctr], invariant[ctr], - ordinal[ctr], stringSort[ctr] ); - } + public static void Main() + { + string[] strings = ["coop", "co-op", "cooperative", + "co\u00ADoperative", "cœur", "coeur"]; + + // Perform a word sort using the current (en-US) culture. + string[] current = new string[strings.Length]; + strings.CopyTo(current, 0); + Array.Sort(current, StringComparer.CurrentCulture); + + // Perform a word sort using the invariant culture. + string[] invariant = new string[strings.Length]; + strings.CopyTo(invariant, 0); + Array.Sort(invariant, StringComparer.InvariantCulture); + + // Perform an ordinal sort. + string[] ordinal = new string[strings.Length]; + strings.CopyTo(ordinal, 0); + Array.Sort(ordinal, StringComparer.Ordinal); + + // Perform a string sort using the current culture. + string[] stringSort = new string[strings.Length]; + strings.CopyTo(stringSort, 0); + Array.Sort(stringSort, new SCompare()); + + // Display array values + Console.WriteLine($"{"Original",13} {"Word Sort",13} {"Invariant Word",15} {"Ordinal Sort",13} {"String Sort",13}\n"); + for (int ctr = 0; ctr < strings.Length; ctr++) + Console.WriteLine($"{strings[ctr],13} {current[ctr],13} {invariant[ctr],15} {ordinal[ctr],13} {stringSort[ctr],13}"); + } } // IComparer implementation to perform string sort. -internal class SCompare : IComparer +internal class SCompare : IComparer { - public int Compare(string x, string y) - { - return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort); - } + public int Compare(string x, string y) => CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort); } // The example displays the following output: // Original Word Sort Invariant Word Ordinal Sort String Sort -// +// // coop cœur cœur co-op co-op // co-op coeur coeur coeur cœur // cooperative coop coop coop coeur // co­operative co-op co-op cooperative coop // cœur cooperative cooperative co­operative cooperative // coeur co­operative co­operative cœur co­operative -// +// diff --git a/snippets/csharp/System/String/Overview/compare3.cs b/snippets/csharp/System/String/Overview/compare3.cs index f09b00e6399..e8e916ed258 100644 --- a/snippets/csharp/System/String/Overview/compare3.cs +++ b/snippets/csharp/System/String/Overview/compare3.cs @@ -3,39 +3,37 @@ public class Example { - public static void Main() - { - // Search for "oe" and "œu" in "œufs" and "oeufs". - string s1 = "œufs"; - string s2 = "oeufs"; - FindInString(s1, "oe", StringComparison.CurrentCulture); - FindInString(s1, "oe", StringComparison.Ordinal); - FindInString(s2, "œu", StringComparison.CurrentCulture); - FindInString(s2, "œu", StringComparison.Ordinal); - Console.WriteLine(); - - string s3 = "co\u00ADoperative"; - FindInString(s3, "\u00AD", StringComparison.CurrentCulture); - FindInString(s3, "\u00AD", StringComparison.Ordinal); - } + public static void Main() + { + // Search for "oe" and "œu" in "œufs" and "oeufs". + string s1 = "œufs"; + string s2 = "oeufs"; + FindInString(s1, "oe", StringComparison.CurrentCulture); + FindInString(s1, "oe", StringComparison.Ordinal); + FindInString(s2, "œu", StringComparison.CurrentCulture); + FindInString(s2, "œu", StringComparison.Ordinal); + Console.WriteLine(); - private static void FindInString(string s, string substring, StringComparison options) - { - int result = s.IndexOf(substring, options); - if (result != -1) - Console.WriteLine("'{0}' found in {1} at position {2}", - substring, s, result); - else - Console.WriteLine("'{0}' not found in {1}", - substring, s); - } + string s3 = "co\u00ADoperative"; + FindInString(s3, "\u00AD", StringComparison.CurrentCulture); + FindInString(s3, "\u00AD", StringComparison.Ordinal); + } + + private static void FindInString(string s, string substring, StringComparison options) + { + int result = s.IndexOf(substring, options); + if (result != -1) + Console.WriteLine($"'{substring}' found in {s} at position {result}"); + else + Console.WriteLine($"'{substring}' not found in {s}"); + } } // The example displays the following output: // 'oe' found in œufs at position 0 // 'oe' not found in œufs // 'œu' found in oeufs at position 0 // 'œu' not found in oeufs -// +// // '­' found in co­operative at position 0 // '­' found in co­operative at position 2 // diff --git a/snippets/csharp/System/String/Overview/compare4.cs b/snippets/csharp/System/String/Overview/compare4.cs index eb56bef05bc..56fa038fe9c 100644 --- a/snippets/csharp/System/String/Overview/compare4.cs +++ b/snippets/csharp/System/String/Overview/compare4.cs @@ -5,49 +5,39 @@ public class CompareStringSample { - public static void Main() - { - string str1 = "Apple"; - string str2 = "Æble"; - string str3 = "AEble"; - - // Set the current culture to Danish in Denmark. - Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK"); - Console.WriteLine("Current culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, String.Compare(str1, str2)); - Console.WriteLine("Comparison of {0} with {1}: {2}\n", - str2, str3, String.Compare(str2, str3)); - - // Set the current culture to English in the U.S. - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - Console.WriteLine("Current culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, String.Compare(str1, str2)); - Console.WriteLine("Comparison of {0} with {1}: {2}\n", - str2, str3, String.Compare(str2, str3)); - - // Perform an ordinal comparison. - Console.WriteLine("Ordinal comparison"); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, - String.Compare(str1, str2, StringComparison.Ordinal)); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str2, str3, - String.Compare(str2, str3, StringComparison.Ordinal)); - } + public static void Main() + { + string str1 = "Apple"; + string str2 = "Æble"; + string str3 = "AEble"; + + // Set the current culture to Danish in Denmark. + Thread.CurrentThread.CurrentCulture = new("da-DK"); + Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3)}\n"); + + // Set the current culture to English in the U.S. + Thread.CurrentThread.CurrentCulture = new("en-US"); + Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3)}\n"); + + // Perform an ordinal comparison. + Console.WriteLine("Ordinal comparison"); + Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2, StringComparison.Ordinal)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3, StringComparison.Ordinal)}"); + } } // The example displays the following output: // Current culture: da-DK // Comparison of Apple with Æble: -1 // Comparison of Æble with AEble: 1 -// +// // Current culture: en-US // Comparison of Apple with Æble: 1 // Comparison of Æble with AEble: 0 -// +// // Ordinal comparison // Comparison of Apple with Æble: -133 // Comparison of Æble with AEble: 133 diff --git a/snippets/csharp/System/String/Overview/equality1.cs b/snippets/csharp/System/String/Overview/equality1.cs index 7f8cf23fca1..aaa04d4b042 100644 --- a/snippets/csharp/System/String/Overview/equality1.cs +++ b/snippets/csharp/System/String/Overview/equality1.cs @@ -5,38 +5,38 @@ public class Example { - public static void Main() - { - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR"); + public static void Main() + { + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR"); - string filePath = "file://c:/notes.txt"; - - Console.WriteLine("Culture-sensitive test for equality:"); - if (!TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase)) - Console.WriteLine("Access to {0} is allowed.", filePath); - else - Console.WriteLine("Access to {0} is not allowed.", filePath); - - Console.WriteLine("\nOrdinal test for equality:"); - if (!TestForEquality(filePath, StringComparison.OrdinalIgnoreCase)) - Console.WriteLine("Access to {0} is allowed.", filePath); - else - Console.WriteLine("Access to {0} is not allowed.", filePath); - } + string filePath = "file://c:/notes.txt"; - private static bool TestForEquality(string str, StringComparison cmp) - { - int position = str.IndexOf("://"); - if (position < 0) return false; + Console.WriteLine("Culture-sensitive test for equality:"); + if (!TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase)) + Console.WriteLine($"Access to {filePath} is allowed."); + else + Console.WriteLine($"Access to {filePath} is not allowed."); - string substring = str.Substring(0, position); - return substring.Equals("FILE", cmp); - } + Console.WriteLine("\nOrdinal test for equality:"); + if (!TestForEquality(filePath, StringComparison.OrdinalIgnoreCase)) + Console.WriteLine($"Access to {filePath} is allowed."); + else + Console.WriteLine($"Access to {filePath} is not allowed."); + } + + private static bool TestForEquality(string str, StringComparison cmp) + { + int position = str.IndexOf("://"); + if (position < 0) return false; + + string substring = str.Substring(0, position); + return substring.Equals("FILE", cmp); + } } // The example displays the following output: // Culture-sensitive test for equality: // Access to file://c:/notes.txt is allowed. -// +// // Ordinal test for equality: // Access to file://c:/notes.txt is not allowed. // diff --git a/snippets/csharp/System/String/Overview/format1.cs b/snippets/csharp/System/String/Overview/format1.cs index ad80b2938da..4c83842befc 100644 --- a/snippets/csharp/System/String/Overview/format1.cs +++ b/snippets/csharp/System/String/Overview/format1.cs @@ -4,18 +4,17 @@ public class Example { - public static void Main() - { - DateTime date = new DateTime(2011, 3, 1); - CultureInfo[] cultures = { CultureInfo.InvariantCulture, - new CultureInfo("en-US"), - new CultureInfo("fr-FR") }; + public static void Main() + { + DateTime date = new(2011, 3, 1); + CultureInfo[] cultures = [CultureInfo.InvariantCulture, + new CultureInfo("en-US"), + new CultureInfo("fr-FR")]; - foreach (var culture in cultures) - Console.WriteLine("{0,-12} {1}", String.IsNullOrEmpty(culture.Name) ? - "Invariant" : culture.Name, - date.ToString("d", culture)); - } + foreach (var culture in cultures) + Console.WriteLine($"{(string.IsNullOrEmpty(culture.Name) ? + "Invariant" : culture.Name),-12} {date.ToString("d", culture)}"); + } } // The example displays the following output: // Invariant 03/01/2011 diff --git a/snippets/csharp/System/String/Overview/grapheme1.cs b/snippets/csharp/System/String/Overview/grapheme1.cs index a4e04a0b855..75b13221c72 100644 --- a/snippets/csharp/System/String/Overview/grapheme1.cs +++ b/snippets/csharp/System/String/Overview/grapheme1.cs @@ -1,31 +1,28 @@ // using System; -using System.Globalization; + using System.IO; public class Example { - public static void Main() - { - StreamWriter sw = new StreamWriter(@".\graphemes.txt"); - string grapheme = "\u0061\u0308"; - sw.WriteLine(grapheme); - - string singleChar = "\u00e4"; - sw.WriteLine(singleChar); - - sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, - String.Equals(grapheme, singleChar, - StringComparison.CurrentCulture)); - sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, - String.Equals(grapheme, singleChar, - StringComparison.Ordinal)); - sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, - String.Equals(grapheme.Normalize(), - singleChar.Normalize(), - StringComparison.Ordinal)); - sw.Close(); - } + public static void Main() + { + StreamWriter sw = new(@".\graphemes.txt"); + string grapheme = "\u0061\u0308"; + sw.WriteLine(grapheme); + + string singleChar = "\u00e4"; + sw.WriteLine(singleChar); + + sw.WriteLine($"{grapheme} = {singleChar} (Culture-sensitive): {string.Equals(grapheme, singleChar, + StringComparison.CurrentCulture)}"); + sw.WriteLine($"{grapheme} = {singleChar} (Ordinal): {string.Equals(grapheme, singleChar, + StringComparison.Ordinal)}"); + sw.WriteLine($"{grapheme} = {singleChar} (Normalized Ordinal): {string.Equals(grapheme.Normalize(), + singleChar.Normalize(), + StringComparison.Ordinal)}"); + sw.Close(); + } } // The example produces the following output: // ä diff --git a/snippets/csharp/System/String/Overview/immutable.cs b/snippets/csharp/System/String/Overview/immutable.cs index 571d9fd093d..9f99dd02d10 100644 --- a/snippets/csharp/System/String/Overview/immutable.cs +++ b/snippets/csharp/System/String/Overview/immutable.cs @@ -5,21 +5,22 @@ public class Example { - public static void Main() - { - Random rnd = new Random(); - - string str = String.Empty; - StreamWriter sw = new StreamWriter(@".\StringFile.txt", - false, Encoding.Unicode); + public static void Main() + { + Random rnd = new(); - for (int ctr = 0; ctr <= 1000; ctr++) { - str += (char)rnd.Next(1, 0x0530); - if (str.Length % 60 == 0) - str += Environment.NewLine; - } - sw.Write(str); - sw.Close(); - } + string str = string.Empty; + StreamWriter sw = new(@".\StringFile.txt", + false, Encoding.Unicode); + + for (int ctr = 0; ctr <= 1000; ctr++) + { + str += (char)rnd.Next(1, 0x0530); + if (str.Length % 60 == 0) + str += Environment.NewLine; + } + sw.Write(str); + sw.Close(); + } } // diff --git a/snippets/csharp/System/String/Overview/immutable1.cs b/snippets/csharp/System/String/Overview/immutable1.cs index 7acce8bd779..707334e238e 100644 --- a/snippets/csharp/System/String/Overview/immutable1.cs +++ b/snippets/csharp/System/String/Overview/immutable1.cs @@ -5,20 +5,21 @@ public class Example { - public static void Main() - { - Random rnd = new Random(); - StringBuilder sb = new StringBuilder(); - StreamWriter sw = new StreamWriter(@".\StringFile.txt", - false, Encoding.Unicode); + public static void Main() + { + Random rnd = new(); + StringBuilder sb = new(); + StreamWriter sw = new(@".\StringFile.txt", + false, Encoding.Unicode); - for (int ctr = 0; ctr <= 1000; ctr++) { - sb.Append((char)rnd.Next(1, 0x0530)); - if (sb.Length % 60 == 0) - sb.AppendLine(); - } - sw.Write(sb.ToString()); - sw.Close(); - } + for (int ctr = 0; ctr <= 1000; ctr++) + { + sb.Append((char)rnd.Next(1, 0x0530)); + if (sb.Length % 60 == 0) + sb.AppendLine(); + } + sw.Write(sb); + sw.Close(); + } } // diff --git a/snippets/csharp/System/String/Overview/index11.cs b/snippets/csharp/System/String/Overview/index11.cs index ef64e09c306..21a336bf445 100644 --- a/snippets/csharp/System/String/Overview/index11.cs +++ b/snippets/csharp/System/String/Overview/index11.cs @@ -2,23 +2,23 @@ public class Example { - public static void Main() - { - // - string s1 = "This string consists of a single short sentence."; - int nWords = 0; + public static void Main() + { + // + string s1 = "This string consists of a single short sentence."; + int nWords = 0; - s1 = s1.Trim(); - for (int ctr = 0; ctr < s1.Length; ctr++) { - if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr])) - nWords++; - } - Console.WriteLine("The sentence\n {0}\nhas {1} words.", - s1, nWords); - // The example displays the following output: - // The sentence - // This string consists of a single short sentence. - // has 8 words. - // - } + s1 = s1.Trim(); + for (int ctr = 0; ctr < s1.Length; ctr++) + { + if (char.IsPunctuation(s1[ctr]) || char.IsWhiteSpace(s1[ctr])) + nWords++; + } + Console.WriteLine($"The sentence\n {s1}\nhas {nWords} words."); + // The example displays the following output: + // The sentence + // This string consists of a single short sentence. + // has 8 words. + // + } } diff --git a/snippets/csharp/System/String/Overview/index2.cs b/snippets/csharp/System/String/Overview/index2.cs index a34063b02e4..1e5633c01a7 100644 --- a/snippets/csharp/System/String/Overview/index2.cs +++ b/snippets/csharp/System/String/Overview/index2.cs @@ -2,23 +2,23 @@ public class Example { - public static void Main() - { - // - string s1 = "This string consists of a single short sentence."; - int nWords = 0; + public static void Main() + { + // + string s1 = "This string consists of a single short sentence."; + int nWords = 0; - s1 = s1.Trim(); - foreach (var ch in s1) { - if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch)) - nWords++; - } - Console.WriteLine("The sentence\n {0}\nhas {1} words.", - s1, nWords); - // The example displays the following output: - // The sentence - // This string consists of a single short sentence. - // has 8 words. - // - } + s1 = s1.Trim(); + foreach (char ch in s1) + { + if (char.IsPunctuation(ch) || char.IsWhiteSpace(ch)) + nWords++; + } + Console.WriteLine($"The sentence\n {s1}\nhas {nWords} words."); + // The example displays the following output: + // The sentence + // This string consists of a single short sentence. + // has 8 words. + // + } } diff --git a/snippets/csharp/System/String/Overview/index3.cs b/snippets/csharp/System/String/Overview/index3.cs index e19fee09d03..dffa7527192 100644 --- a/snippets/csharp/System/String/Overview/index3.cs +++ b/snippets/csharp/System/String/Overview/index3.cs @@ -3,74 +3,78 @@ public class Example { - public static void Main() - { - // - // First sentence of The Mystery of the Yellow Room, by Leroux. - string opening = "Ce n'est pas sans une certaine émotion que "+ - "je commence à raconter ici les aventures " + - "extraordinaires de Joseph Rouletabille."; - // Character counters. - int nChars = 0; - // Objects to store word count. - List chars = new List(); - List elements = new List(); - - foreach (var ch in opening) { - // Skip the ' character. - if (ch == '\u0027') continue; - - if (Char.IsWhiteSpace(ch) | (Char.IsPunctuation(ch))) { - chars.Add(nChars); - nChars = 0; - } - else { - nChars++; - } - } + public static void Main() + { + // + // First sentence of The Mystery of the Yellow Room, by Leroux. + string opening = "Ce n'est pas sans une certaine émotion que " + + "je commence à raconter ici les aventures " + + "extraordinaires de Joseph Rouletabille."; + // Character counters. + int nChars = 0; + // Objects to store word count. + List chars = new(); + List elements = new(); - System.Globalization.TextElementEnumerator te = - System.Globalization.StringInfo.GetTextElementEnumerator(opening); - while (te.MoveNext()) { - string s = te.GetTextElement(); - // Skip the ' character. - if (s == "\u0027") continue; - if ( String.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && Char.IsPunctuation(Convert.ToChar(s)))) { - elements.Add(nChars); - nChars = 0; - } - else { - nChars++; - } - } + foreach (char ch in opening) + { + // Skip the ' character. + if (ch == '\u0027') continue; - // Display character counts. - Console.WriteLine("{0,6} {1,20} {2,20}", - "Word #", "Char Objects", "Characters"); - for (int ctr = 0; ctr < chars.Count; ctr++) - Console.WriteLine("{0,6} {1,20} {2,20}", - ctr, chars[ctr], elements[ctr]); - // The example displays the following output: - // Word # Char Objects Characters - // 0 2 2 - // 1 4 4 - // 2 3 3 - // 3 4 4 - // 4 3 3 - // 5 8 8 - // 6 8 7 - // 7 3 3 - // 8 2 2 - // 9 8 8 - // 10 2 1 - // 11 8 8 - // 12 3 3 - // 13 3 3 - // 14 9 9 - // 15 15 15 - // 16 2 2 - // 17 6 6 - // 18 12 12 - // - } + if (char.IsWhiteSpace(ch) | (char.IsPunctuation(ch))) + { + chars.Add(nChars); + nChars = 0; + } + else + { + nChars++; + } + } + + System.Globalization.TextElementEnumerator te = + System.Globalization.StringInfo.GetTextElementEnumerator(opening); + while (te.MoveNext()) + { + string s = te.GetTextElement(); + // Skip the ' character. + if (s == "\u0027") continue; + if (string.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && char.IsPunctuation(Convert.ToChar(s)))) + { + elements.Add(nChars); + nChars = 0; + } + else + { + nChars++; + } + } + + // Display character counts. + Console.WriteLine($"{"Word #",6} {"Char Objects",20} {"Characters",20}"); + for (int ctr = 0; ctr < chars.Count; ctr++) + Console.WriteLine($"{ctr,6} {chars[ctr],20} {elements[ctr],20}"); + // The example displays the following output: + // Word # Char Objects Characters + // 0 2 2 + // 1 4 4 + // 2 3 3 + // 3 4 4 + // 4 3 3 + // 5 8 8 + // 6 8 7 + // 7 3 3 + // 8 2 2 + // 9 8 8 + // 10 2 1 + // 11 8 8 + // 12 3 3 + // 13 3 3 + // 14 9 9 + // 15 15 15 + // 16 2 2 + // 17 6 6 + // 18 12 12 + // + } } diff --git a/snippets/csharp/System/String/Overview/normalize1.cs b/snippets/csharp/System/String/Overview/normalize1.cs index 6c17b6d3930..92746c3223f 100644 --- a/snippets/csharp/System/String/Overview/normalize1.cs +++ b/snippets/csharp/System/String/Overview/normalize1.cs @@ -1,92 +1,89 @@ // using System; -using System.Globalization; + using System.IO; using System.Text; public class Example { - private static StreamWriter sw; - - public static void Main() - { - sw = new StreamWriter(@".\TestNorm1.txt"); + private static StreamWriter sw; + + public static void Main() + { + sw = new(@".\TestNorm1.txt"); + + // Define three versions of the same word. + string s1 = "sống"; // create word with U+1ED1 + string s2 = "s\u00F4\u0301ng"; + string s3 = "so\u0302\u0301ng"; + + TestForEquality(s1, s2, s3); + sw.WriteLine(); - // Define three versions of the same word. - string s1 = "sống"; // create word with U+1ED1 - string s2 = "s\u00F4\u0301ng"; - string s3 = "so\u0302\u0301ng"; + // Normalize and compare strings using each normalization form. + foreach (string formName in Enum.GetNames(typeof(NormalizationForm))) + { + sw.WriteLine($"Normalization {formName}:\n"); + NormalizationForm nf = (NormalizationForm)Enum.Parse(typeof(NormalizationForm), formName); + string[] sn = NormalizeStrings(nf, s1, s2, s3); + TestForEquality(sn); + sw.WriteLine("\n"); + } - TestForEquality(s1, s2, s3); - sw.WriteLine(); + sw.Close(); + } - // Normalize and compare strings using each normalization form. - foreach (string formName in Enum.GetNames(typeof(NormalizationForm))) - { - sw.WriteLine("Normalization {0}:\n", formName); - NormalizationForm nf = (NormalizationForm) Enum.Parse(typeof(NormalizationForm), formName); - string[] sn = NormalizeStrings(nf, s1, s2, s3); - TestForEquality(sn); - sw.WriteLine("\n"); - } - - sw.Close(); - } + private static void TestForEquality(params string[] words) + { + for (int ctr = 0; ctr <= words.Length - 2; ctr++) + for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++) + sw.WriteLine($"{words[ctr]} ({ShowBytes(words[ctr])}) = {words[ctr2]} ({ShowBytes(words[ctr2])}): {words[ctr].Equals(words[ctr2], StringComparison.Ordinal)}"); + } - private static void TestForEquality(params string[] words) - { - for (int ctr = 0; ctr <= words.Length - 2; ctr++) - for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++) - sw.WriteLine("{0} ({1}) = {2} ({3}): {4}", - words[ctr], ShowBytes(words[ctr]), - words[ctr2], ShowBytes(words[ctr2]), - words[ctr].Equals(words[ctr2], StringComparison.Ordinal)); - } + private static string ShowBytes(string str) + { + string result = null; + foreach (char ch in str) + result += $"{(ushort)ch:X4} "; + return result.Trim(); + } - private static string ShowBytes(string str) - { - string result = null; - foreach (var ch in str) - result += $"{(ushort)ch:X4} "; - return result.Trim(); - } - - private static string[] NormalizeStrings(NormalizationForm nf, params string[] words) - { - for (int ctr = 0; ctr < words.Length; ctr++) - if (!words[ctr].IsNormalized(nf)) - words[ctr] = words[ctr].Normalize(nf); - return words; - } + private static string[] NormalizeStrings(NormalizationForm nf, params string[] words) + { + for (int ctr = 0; ctr < words.Length; ctr++) + if (!words[ctr].IsNormalized(nf)) + words[ctr] = words[ctr].Normalize(nf); + return words; + } } // The example displays the following output: // sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False // sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False // sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False -// +// // Normalization FormC: -// +// // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True -// -// +// +// // Normalization FormD: -// +// // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True -// -// +// +// // Normalization FormKC: -// +// // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True // sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True -// -// +// +// // Normalization FormKD: -// +// // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True // sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True diff --git a/snippets/csharp/System/String/Overview/nullorempty1.cs b/snippets/csharp/System/String/Overview/nullorempty1.cs index 51921237593..d4d5b07dcfb 100644 --- a/snippets/csharp/System/String/Overview/nullorempty1.cs +++ b/snippets/csharp/System/String/Overview/nullorempty1.cs @@ -3,78 +3,68 @@ public class Example { - public static void Main() - { - TestForIsNullOrEmpty(); - Console.WriteLine("-----"); - TestForIsNullOrEmptyOrWhitespaceOnly(); - } + public static void Main() + { + TestForIsNullOrEmpty(); + Console.WriteLine("-----"); + TestForIsNullOrEmptyOrWhitespaceOnly(); + } - private static void TestForIsNullOrEmpty() - { - string str = ""; - // - if (str == null || str.Equals(String.Empty)) - // - Console.WriteLine("Bad string!"); - else - Console.WriteLine("Good string!"); - } + private static void TestForIsNullOrEmpty() + { + string str = ""; + // + if (str == null || str.Equals(string.Empty)) + // + Console.WriteLine("Bad string!"); + else + Console.WriteLine("Good string!"); + } - private static void TestForIsNullOrEmptyOrWhitespaceOnly() - { - string str = null; - // - if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty)) - // - Console.WriteLine("Bad string!"); - else - Console.WriteLine("Good string!"); - } + private static void TestForIsNullOrEmptyOrWhitespaceOnly() + { + string str = null; + // + if (str == null || str.Equals(string.Empty) || str.Trim().Equals(string.Empty)) + // + Console.WriteLine("Bad string!"); + else + Console.WriteLine("Good string!"); + } } -public class Temperature : IFormattable +public class Temperature : IFormattable { - double temp; - - public Temperature(double temp) - { - this.temp = temp; - } - - public override string ToString() - { - return this.ToString("G", CultureInfo.CurrentCulture); - } - - public string ToString(string format) - { - return this.ToString(format, CultureInfo.CurrentCulture); - } - - // - public string ToString(string format, IFormatProvider provider) - { - if (String.IsNullOrEmpty(format)) format = "G"; - if (provider == null) provider = CultureInfo.CurrentCulture; - - switch (format.ToUpperInvariant()) - { - // Return degrees in Celsius. - case "G": - case "C": - return temp.ToString("F2", provider) + "°C"; - // Return degrees in Fahrenheit. - case "F": - return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F"; - // Return degrees in Kelvin. - case "K": - return (temp + 273.15).ToString(); - default: - throw new FormatException( - String.Format("The {0} format string is not supported.", - format)); - } - } - // -} \ No newline at end of file + double temp; + + public Temperature(double temp) => this.temp = temp; + + public override string ToString() => this.ToString("G", CultureInfo.CurrentCulture); + + public string ToString(string format) => this.ToString(format, CultureInfo.CurrentCulture); + + // + public string ToString(string format, IFormatProvider provider) + { + if (string.IsNullOrEmpty(format)) format = "G"; + if (provider == null) provider = CultureInfo.CurrentCulture; + + switch (format.ToUpperInvariant()) + { + // Return degrees in Celsius. + case "G": + case "C": + return temp.ToString("F2", provider) + "°C"; + // Return degrees in Fahrenheit. + case "F": + return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F"; + // Return degrees in Kelvin. + case "K": + return (temp + 273.15).ToString(); + default: + throw new FormatException( + $"The {format} format string is not supported."); + } + } + // +} diff --git a/snippets/csharp/System/String/Overview/parse1.cs b/snippets/csharp/System/String/Overview/parse1.cs index 064e1283cf7..d82cc4e413d 100644 --- a/snippets/csharp/System/String/Overview/parse1.cs +++ b/snippets/csharp/System/String/Overview/parse1.cs @@ -4,26 +4,24 @@ public class Example { - public static void Main() - { - string dateString = "07/10/2011"; - CultureInfo[] cultures = { CultureInfo.InvariantCulture, - CultureInfo.CreateSpecificCulture("en-GB"), - CultureInfo.CreateSpecificCulture("en-US") }; - Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture", - "Month", "Day"); - foreach (var culture in cultures) { - DateTime date = DateTime.Parse(dateString, culture); - Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, - String.IsNullOrEmpty(culture.Name) ? - "Invariant" : culture.Name, - date.Month, date.Day); - } - } + public static void Main() + { + string dateString = "07/10/2011"; + CultureInfo[] cultures = [CultureInfo.InvariantCulture, + CultureInfo.CreateSpecificCulture("en-GB"), + CultureInfo.CreateSpecificCulture("en-US")]; + Console.WriteLine($"{"Date String",-12} {"Culture",10} {"Month",8} {"Day",8}\n"); + foreach (var culture in cultures) + { + DateTime date = DateTime.Parse(dateString, culture); + Console.WriteLine($"{dateString,-12} {(string.IsNullOrEmpty(culture.Name) ? + "Invariant" : culture.Name),10} {date.Month,8} {date.Day,8}"); + } + } } // The example displays the following output: // Date String Culture Month Day -// +// // 07/10/2011 Invariant 7 10 // 07/10/2011 en-GB 10 7 // 07/10/2011 en-US 7 10 diff --git a/snippets/csharp/System/String/Overview/program.cs b/snippets/csharp/System/String/Overview/program.cs index 57ca343b1e4..d8339b3eda1 100644 --- a/snippets/csharp/System/String/Overview/program.cs +++ b/snippets/csharp/System/String/Overview/program.cs @@ -2,113 +2,113 @@ public class Example { - public static void Main() - { - InstantiateByAssignment(); - Console.WriteLine("-----"); - CallConstructors(); - Console.WriteLine("-----"); - Concatenate(); - Console.WriteLine("-----"); - ExtractString(); - Console.WriteLine("-----"); - Formatting(); - } + public static void Main() + { + InstantiateByAssignment(); + Console.WriteLine("-----"); + CallConstructors(); + Console.WriteLine("-----"); + Concatenate(); + Console.WriteLine("-----"); + ExtractString(); + Console.WriteLine("-----"); + Formatting(); + } - private static void InstantiateByAssignment() - { - // - string string1 = "This is a string created by assignment."; - Console.WriteLine(string1); - string string2a = "The path is C:\\PublicDocuments\\Report1.doc"; - Console.WriteLine(string2a); - string string2b = @"The path is C:\PublicDocuments\Report1.doc"; - Console.WriteLine(string2b); - // The example displays the following output: - // This is a string created by assignment. - // The path is C:\PublicDocuments\Report1.doc - // The path is C:\PublicDocuments\Report1.doc - // - } + private static void InstantiateByAssignment() + { + // + string string1 = "This is a string created by assignment."; + Console.WriteLine(string1); + string string2a = "The path is C:\\PublicDocuments\\Report1.doc"; + Console.WriteLine(string2a); + string string2b = @"The path is C:\PublicDocuments\Report1.doc"; + Console.WriteLine(string2b); + // The example displays the following output: + // This is a string created by assignment. + // The path is C:\PublicDocuments\Report1.doc + // The path is C:\PublicDocuments\Report1.doc + // + } - private static void CallConstructors() - { - // - char[] chars = { 'w', 'o', 'r', 'd' }; - sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 }; + private static void CallConstructors() + { + // + char[] chars = ['w', 'o', 'r', 'd']; + sbyte[] bytes = [0x41, 0x42, 0x43, 0x44, 0x45, 0x00]; - // Create a string from a character array. - string string1 = new string(chars); - Console.WriteLine(string1); + // Create a string from a character array. + string string1 = new(chars); + Console.WriteLine(string1); - // Create a string that consists of a character repeated 20 times. - string string2 = new string('c', 20); - Console.WriteLine(string2); + // Create a string that consists of a character repeated 20 times. + string string2 = new('c', 20); + Console.WriteLine(string2); - string stringFromBytes = null; - string stringFromChars = null; - unsafe - { - fixed (sbyte* pbytes = bytes) - { - // Create a string from a pointer to a signed byte array. - stringFromBytes = new string(pbytes); - } - fixed (char* pchars = chars) - { - // Create a string from a pointer to a character array. - stringFromChars = new string(pchars); - } - } - Console.WriteLine(stringFromBytes); - Console.WriteLine(stringFromChars); - // The example displays the following output: - // word - // cccccccccccccccccccc - // ABCDE - // word - // - } + string stringFromBytes = null; + string stringFromChars = null; + unsafe + { + fixed (sbyte* pbytes = bytes) + { + // Create a string from a pointer to a signed byte array. + stringFromBytes = new(pbytes); + } + fixed (char* pchars = chars) + { + // Create a string from a pointer to a character array. + stringFromChars = new(pchars); + } + } + Console.WriteLine(stringFromBytes); + Console.WriteLine(stringFromChars); + // The example displays the following output: + // word + // cccccccccccccccccccc + // ABCDE + // word + // + } - private static void Concatenate() - { - // - string string1 = "Today is " + DateTime.Now.ToString("D") + "."; - Console.WriteLine(string1); + private static void Concatenate() + { + // + string string1 = $"Today is {DateTime.Now:D}."; + Console.WriteLine(string1); - string string2 = "This is one sentence. " + "This is a second. "; - string2 += "This is a third sentence."; - Console.WriteLine(string2); - // The example displays output like the following: - // Today is Tuesday, July 06, 2011. - // This is one sentence. This is a second. This is a third sentence. - // - } + string string2 = "This is one sentence. " + "This is a second. "; + string2 += "This is a third sentence."; + Console.WriteLine(string2); + // The example displays output like the following: + // Today is Tuesday, July 06, 2011. + // This is one sentence. This is a second. This is a third sentence. + // + } - private static void ExtractString() - { - // - string sentence = "This sentence has five words."; - // Extract the second word. - int startPosition = sentence.IndexOf(" ") + 1; - string word2 = sentence.Substring(startPosition, - sentence.IndexOf(" ", startPosition) - startPosition); - Console.WriteLine("Second word: " + word2); - // The example displays the following output: - // Second word: sentence - // - } + private static void ExtractString() + { + // + string sentence = "This sentence has five words."; + // Extract the second word. + int startPosition = sentence.IndexOf(" ") + 1; + string word2 = sentence.Substring(startPosition, + sentence.IndexOf(" ", startPosition) - startPosition); + Console.WriteLine("Second word: " + word2); + // The example displays the following output: + // Second word: sentence + // + } - private static void Formatting() - { - // - DateTime dateAndTime = new DateTime(2011, 7, 6, 7, 32, 0); - double temperature = 68.3; - string result = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.", - dateAndTime, temperature); - Console.WriteLine(result); - // The example displays the following output: - // At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit. - // - } + private static void Formatting() + { + // + DateTime dateAndTime = new(2011, 7, 6, 7, 32, 0); + double temperature = 68.3; + string result = string.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.", + dateAndTime, temperature); + Console.WriteLine(result); + // The example displays the following output: + // At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit. + // + } } diff --git a/snippets/csharp/System/String/Overview/search1.cs b/snippets/csharp/System/String/Overview/search1.cs index f49f123d156..12585300030 100644 --- a/snippets/csharp/System/String/Overview/search1.cs +++ b/snippets/csharp/System/String/Overview/search1.cs @@ -4,24 +4,23 @@ public class Example { - public static void Main() - { - String[] cultureNames = { "da-DK", "en-US" }; - CompareInfo ci; - String str = "aerial"; - Char ch = 'æ'; // U+00E6 - - Console.Write("Ordinal comparison -- "); - Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str, - str.IndexOf(ch)); - - foreach (var cultureName in cultureNames) { - ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo; - Console.Write("{0} cultural comparison -- ", cultureName); - Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str, - ci.IndexOf(str, ch)); - } - } + public static void Main() + { + string[] cultureNames = ["da-DK", "en-US"]; + CompareInfo ci; + string str = "aerial"; + char ch = 'æ'; // U+00E6 + + Console.Write("Ordinal comparison -- "); + Console.WriteLine($"Position of '{ch}' in {str}: {str.IndexOf(ch)}"); + + foreach (string cultureName in cultureNames) + { + ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo; + Console.Write($"{cultureName} cultural comparison -- "); + Console.WriteLine($"Position of '{ch}' in {str}: {ci.IndexOf(str, ch)}"); + } + } } // The example displays the following output: // Ordinal comparison -- Position of 'æ' in aerial: -1 diff --git a/snippets/csharp/System/String/Overview/sort1.cs b/snippets/csharp/System/String/Overview/sort1.cs index d982852d438..1cd30508b14 100644 --- a/snippets/csharp/System/String/Overview/sort1.cs +++ b/snippets/csharp/System/String/Overview/sort1.cs @@ -1,44 +1,44 @@ // using System; -using System.Globalization; + using System.Threading; public class ArraySort { - public static void Main(String[] args) - { - // Create and initialize a new array to store the strings. - string[] stringArray = { "Apple", "Æble", "Zebra"}; + public static void Main(string[] args) + { + // Create and initialize a new array to store the strings. + string[] stringArray = ["Apple", "Æble", "Zebra"]; - // Display the values of the array. - Console.WriteLine( "The original string array:"); - PrintIndexAndValues(stringArray); + // Display the values of the array. + Console.WriteLine("The original string array:"); + PrintIndexAndValues(stringArray); - // Set the CurrentCulture to "en-US". - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - // Sort the values of the array. - Array.Sort(stringArray); + // Set the CurrentCulture to "en-US". + Thread.CurrentThread.CurrentCulture = new("en-US"); + // Sort the values of the array. + Array.Sort(stringArray); - // Display the values of the array. - Console.WriteLine("After sorting for the culture \"en-US\":"); - PrintIndexAndValues(stringArray); + // Display the values of the array. + Console.WriteLine("After sorting for the culture \"en-US\":"); + PrintIndexAndValues(stringArray); - // Set the CurrentCulture to "da-DK". - Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK"); - // Sort the values of the Array. - Array.Sort(stringArray); + // Set the CurrentCulture to "da-DK". + Thread.CurrentThread.CurrentCulture = new("da-DK"); + // Sort the values of the Array. + Array.Sort(stringArray); - // Display the values of the array. - Console.WriteLine("After sorting for the culture \"da-DK\":"); - PrintIndexAndValues(stringArray); - } - public static void PrintIndexAndValues(string[] myArray) - { - for (int i = myArray.GetLowerBound(0); i <= - myArray.GetUpperBound(0); i++ ) - Console.WriteLine("[{0}]: {1}", i, myArray[i]); - Console.WriteLine(); - } + // Display the values of the array. + Console.WriteLine("After sorting for the culture \"da-DK\":"); + PrintIndexAndValues(stringArray); + } + public static void PrintIndexAndValues(string[] myArray) + { + for (int i = myArray.GetLowerBound(0); i <= + myArray.GetUpperBound(0); i++) + Console.WriteLine($"[{i}]: {myArray[i]}"); + Console.WriteLine(); + } } // The example displays the following output: // The original string array: @@ -55,4 +55,4 @@ public static void PrintIndexAndValues(string[] myArray) // [0]: Apple // [1]: Zebra // [2]: Æble -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Overview/surrogate1.cs b/snippets/csharp/System/String/Overview/surrogate1.cs index 923b60e8845..87d973c2774 100644 --- a/snippets/csharp/System/String/Overview/surrogate1.cs +++ b/snippets/csharp/System/String/Overview/surrogate1.cs @@ -2,19 +2,18 @@ public class Example { - public static void Main() - { - // - string surrogate = "\uD800\uDC03"; - for (int ctr = 0; ctr < surrogate.Length; ctr++) - Console.Write($"U+{(ushort)surrogate[ctr]:X2} "); + public static void Main() + { + // + string surrogate = "\uD800\uDC03"; + for (int ctr = 0; ctr < surrogate.Length; ctr++) + Console.Write($"U+{(ushort)surrogate[ctr]:X2} "); - Console.WriteLine(); - Console.WriteLine(" Is Surrogate Pair: {0}", - Char.IsSurrogatePair(surrogate[0], surrogate[1])); - // The example displays the following output: - // U+D800 U+DC03 - // Is Surrogate Pair: True - // - } + Console.WriteLine(); + Console.WriteLine($" Is Surrogate Pair: {char.IsSurrogatePair(surrogate[0], surrogate[1])}"); + // The example displays the following output: + // U+D800 U+DC03 + // Is Surrogate Pair: True + // + } } diff --git a/snippets/csharp/System/String/PadLeft/Program.cs b/snippets/csharp/System/String/PadLeft/Program.cs new file mode 100644 index 00000000000..a95d98f8dd5 --- /dev/null +++ b/snippets/csharp/System/String/PadLeft/Program.cs @@ -0,0 +1,2 @@ +PadLeftWidthSample.Run(); +PadLeftCharacterSample.Run(); diff --git a/snippets/csharp/System/String/PadLeft/Project.csproj b/snippets/csharp/System/String/PadLeft/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/PadLeft/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/PadLeft/source.cs b/snippets/csharp/System/String/PadLeft/source.cs index 24438db7052..f84af9ba61c 100644 --- a/snippets/csharp/System/String/PadLeft/source.cs +++ b/snippets/csharp/System/String/PadLeft/source.cs @@ -1,13 +1,13 @@ using System; -public class Sample +public class PadLeftWidthSample { - public static void Main() + public static void Run() { - // - string str = "BBQ and Slaw"; - Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw". - Console.WriteLine(str.PadLeft(5)); // Displays "BBQ and Slaw". - // + // + string str = "BBQ and Slaw"; + Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw". + Console.WriteLine(str.PadLeft(5)); // Displays "BBQ and Slaw". + // } } diff --git a/snippets/csharp/System/String/PadLeft/source1.cs b/snippets/csharp/System/String/PadLeft/source1.cs index ad388a1e34a..3ccd13369ad 100644 --- a/snippets/csharp/System/String/PadLeft/source1.cs +++ b/snippets/csharp/System/String/PadLeft/source1.cs @@ -1,16 +1,16 @@ // using System; -class Sample +class PadLeftCharacterSample { - public static void Main() - { - string str = "forty-two"; - char pad = '.'; + public static void Run() + { + string str = "forty-two"; + char pad = '.'; - Console.WriteLine(str.PadLeft(15, pad)); - Console.WriteLine(str.PadLeft(2, pad)); - } + Console.WriteLine(str.PadLeft(15, pad)); + Console.WriteLine(str.PadLeft(2, pad)); + } } // The example displays the following output: // ......forty-two diff --git a/snippets/csharp/System/String/PadRight/Program.cs b/snippets/csharp/System/String/PadRight/Program.cs new file mode 100644 index 00000000000..aa9fc72f2f3 --- /dev/null +++ b/snippets/csharp/System/String/PadRight/Program.cs @@ -0,0 +1,2 @@ +PadRightWidthSample.Run(); +PadRightCharacterSample.Run(); diff --git a/snippets/csharp/System/String/PadRight/Project.csproj b/snippets/csharp/System/String/PadRight/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/PadRight/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/PadRight/source.cs b/snippets/csharp/System/String/PadRight/source.cs index 2af784dba15..8c69974086d 100644 --- a/snippets/csharp/System/String/PadRight/source.cs +++ b/snippets/csharp/System/String/PadRight/source.cs @@ -1,20 +1,20 @@ using System; -public class Sample +public class PadRightWidthSample { - public static void Main() - { - // - string str; - str = "BBQ and Slaw"; + public static void Run() + { + // + string str; + str = "BBQ and Slaw"; - Console.Write("|"); - Console.Write(str.PadRight(15)); - Console.WriteLine("|"); // Displays "|BBQ and Slaw |". + Console.Write("|"); + Console.Write(str.PadRight(15)); + Console.WriteLine("|"); // Displays "|BBQ and Slaw |". - Console.Write("|"); - Console.Write(str.PadRight(5)); - Console.WriteLine("|"); // Displays "|BBQ and Slaw|". - // - } + Console.Write("|"); + Console.Write(str.PadRight(5)); + Console.WriteLine("|"); // Displays "|BBQ and Slaw|". + // + } } diff --git a/snippets/csharp/System/String/PadRight/source1.cs b/snippets/csharp/System/String/PadRight/source1.cs index 5f7e6aea9e3..39bcafdaec1 100644 --- a/snippets/csharp/System/String/PadRight/source1.cs +++ b/snippets/csharp/System/String/PadRight/source1.cs @@ -1,15 +1,15 @@ using System; -public class Sample +public class PadRightCharacterSample { - public static void Main() - { - // - string str = "forty-two"; - char pad = '.'; + public static void Run() + { + // + string str = "forty-two"; + char pad = '.'; - Console.WriteLine(str.PadRight(15, pad)); // Displays "forty-two......". - Console.WriteLine(str.PadRight(2, pad)); // Displays "forty-two". - // - } + Console.WriteLine(str.PadRight(15, pad)); // Displays "forty-two......". + Console.WriteLine(str.PadRight(2, pad)); // Displays "forty-two". + // + } } diff --git a/snippets/csharp/System/String/Remove/r.cs b/snippets/csharp/System/String/Remove/r.cs index 6d369b951c0..db2a7d0f085 100644 --- a/snippets/csharp/System/String/Remove/r.cs +++ b/snippets/csharp/System/String/Remove/r.cs @@ -9,9 +9,9 @@ public static void Main() string s = "abc---def"; Console.WriteLine("Index: 012345678"); - Console.WriteLine("1) {0}", s); - Console.WriteLine("2) {0}", s.Remove(3)); - Console.WriteLine("3) {0}", s.Remove(3, 3)); + Console.WriteLine($"1) {s}"); + Console.WriteLine($"2) {s.Remove(3)}"); + Console.WriteLine($"3) {s.Remove(3, 3)}"); } } /* diff --git a/snippets/csharp/System/String/Remove/stringremove.cs b/snippets/csharp/System/String/Remove/stringremove.cs index 303a5bebb35..fa953c02e32 100644 --- a/snippets/csharp/System/String/Remove/stringremove.cs +++ b/snippets/csharp/System/String/Remove/stringremove.cs @@ -8,7 +8,7 @@ public static void Main() string name = "Michelle Violet Banks"; - Console.WriteLine("The entire name is '{0}'", name); + Console.WriteLine($"The entire name is '{name}'"); // Remove the middle name, identified by finding the spaces in the name. int foundS1 = name.IndexOf(" "); @@ -18,7 +18,7 @@ public static void Main() { name = name.Remove(foundS1 + 1, foundS2 - foundS1); - Console.WriteLine("After removing the middle name, we are left with '{0}'", name); + Console.WriteLine($"After removing the middle name, we are left with '{name}'"); } } } diff --git a/snippets/csharp/System/String/Split/basic.cs b/snippets/csharp/System/String/Split/basic.cs index 351c75adca9..dc95e3c2c35 100644 --- a/snippets/csharp/System/String/Split/basic.cs +++ b/snippets/csharp/System/String/Split/basic.cs @@ -10,7 +10,7 @@ public static void Basic1() string s = "Today\tI'm going to school"; string[] subs = s.Split(' ', '\t'); - foreach (var sub in subs) + foreach (string sub in subs) { Console.WriteLine($"Substring: {sub}"); } diff --git a/snippets/csharp/System/String/Split/compiler-resolution.cs b/snippets/csharp/System/String/Split/compiler-resolution.cs index 8f5ba87d080..2b8497c4800 100644 --- a/snippets/csharp/System/String/Split/compiler-resolution.cs +++ b/snippets/csharp/System/String/Split/compiler-resolution.cs @@ -10,7 +10,7 @@ public static void Main6() string value = "This is a short string."; char delimiter = 's'; string[] substrings = value.Split(delimiter); - foreach (var substring in substrings) + foreach (string substring in substrings) Console.WriteLine(substring); // The example displays the following output: diff --git a/snippets/csharp/System/String/Split/intro.cs b/snippets/csharp/System/String/Split/intro.cs index f24bdbcfbd6..b8ad25f46b5 100644 --- a/snippets/csharp/System/String/Split/intro.cs +++ b/snippets/csharp/System/String/Split/intro.cs @@ -11,7 +11,7 @@ public static void Intro1() string[] subs = s.Split(' '); - foreach (var sub in subs) + foreach (string sub in subs) { Console.WriteLine($"Substring: {sub}"); } @@ -34,7 +34,7 @@ public static void Intro2() string[] subs = s.Split(' ', '.'); - foreach (var sub in subs) + foreach (string sub in subs) { Console.WriteLine($"Substring: {sub}"); } @@ -56,11 +56,11 @@ public static void Intro3() { // string s = "You win some. You lose some."; - char[] separators = new char[] { ' ', '.' }; + char[] separators = [' ', '.']; string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries); - foreach (var sub in subs) + foreach (string sub in subs) { Console.WriteLine($"Substring: {sub}"); } diff --git a/snippets/csharp/System/String/Split/limit.cs b/snippets/csharp/System/String/Split/limit.cs index cbb0a8ad306..44327120100 100644 --- a/snippets/csharp/System/String/Split/limit.cs +++ b/snippets/csharp/System/String/Split/limit.cs @@ -1,4 +1,4 @@ -using System; + namespace Split { diff --git a/snippets/csharp/System/String/Split/options.cs b/snippets/csharp/System/String/Split/options.cs index 964ef4a990b..a499088860c 100644 --- a/snippets/csharp/System/String/Split/options.cs +++ b/snippets/csharp/System/String/Split/options.cs @@ -14,7 +14,7 @@ public static void Main3() Console.WriteLine("1) Split a string delimited by characters:\n"); string s1 = ",ONE,, TWO,, , THREE,,"; - char[] charSeparators = new char[] { ',' }; + char[] charSeparators = [',']; string[] result; Console.WriteLine($"The original string is: \"{s1}\"."); @@ -69,7 +69,7 @@ public static void Main3() "ONE[stop] [stop]" + "TWO [stop][stop] [stop]" + "THREE[stop][stop] "; - string[] stringSeparators = new string[] { "[stop]" }; + string[] stringSeparators = ["[stop]"]; Console.WriteLine($"The original string is: \"{s2}\"."); Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n"); @@ -212,7 +212,7 @@ public static void Main4() { // string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"; - string[] stringSeparators = new string[] { "[stop]" }; + string[] stringSeparators = ["[stop]"]; string[] result; // Display the original string and delimiter string. @@ -227,7 +227,7 @@ public static void Main4() Console.Write(" "); foreach (string s in result) { - Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s); + Console.Write($"'{(string.IsNullOrEmpty(s) ? "<>" : s)}' "); } Console.WriteLine(); Console.WriteLine(); @@ -238,7 +238,7 @@ public static void Main4() Console.Write(" "); foreach (string s in result) { - Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s); + Console.Write($"'{(string.IsNullOrEmpty(s) ? "<>" : s)}' "); } Console.WriteLine(); @@ -260,10 +260,10 @@ public static void Main4() public static void Main2() { // - string[] separators = { ",", ".", "!", "?", ";", ":", " " }; + string[] separators = [",", ".", "!", "?", ";", ":", " "]; string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."; string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); - foreach (var word in words) + foreach (string word in words) Console.WriteLine(word); // The example displays the following output: diff --git a/snippets/csharp/System/String/Split/program.cs b/snippets/csharp/System/String/Split/program.cs index a2a14e1af27..1880d18d1d2 100644 --- a/snippets/csharp/System/String/Split/program.cs +++ b/snippets/csharp/System/String/Split/program.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + + + + + namespace Split { diff --git a/snippets/csharp/System/String/StartsWith/Program.cs b/snippets/csharp/System/String/StartsWith/Program.cs new file mode 100644 index 00000000000..5541cff96e7 --- /dev/null +++ b/snippets/csharp/System/String/StartsWith/Program.cs @@ -0,0 +1,4 @@ +StartsWithComparisonExample.Run(); +StartsWithInvariantExample.Run(); +StartsWithTagsExample.Run(); +Sample.Run(); diff --git a/snippets/csharp/System/String/StartsWith/Project.csproj b/snippets/csharp/System/String/StartsWith/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/StartsWith/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/StartsWith/StartsWith2.cs b/snippets/csharp/System/String/StartsWith/StartsWith2.cs index 2e3379063b0..08805e435dc 100644 --- a/snippets/csharp/System/String/StartsWith/StartsWith2.cs +++ b/snippets/csharp/System/String/StartsWith/StartsWith2.cs @@ -1,23 +1,19 @@ // using System; -public class Example +public class StartsWithInvariantExample { - public static void Main() - { - String title = "The House of the Seven Gables"; - String searchString = "the"; - StringComparison comparison = StringComparison.InvariantCulture; - Console.WriteLine("'{0}':", title); - Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}", - searchString, comparison, - title.StartsWith(searchString, comparison)); + public static void Run() + { + string title = "The House of the Seven Gables"; + string searchString = "the"; + StringComparison comparison = StringComparison.InvariantCulture; + Console.WriteLine($"'{title}':"); + Console.WriteLine($" Starts with '{searchString}' ({comparison:G} comparison): {title.StartsWith(searchString, comparison)}"); - comparison = StringComparison.InvariantCultureIgnoreCase; - Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}", - searchString, comparison, - title.StartsWith(searchString, comparison)); - } + comparison = StringComparison.InvariantCultureIgnoreCase; + Console.WriteLine($" Starts with '{searchString}' ({comparison:G} comparison): {title.StartsWith(searchString, comparison)}"); + } } // The example displays the following output: // 'The House of the Seven Gables': diff --git a/snippets/csharp/System/String/StartsWith/startswith1.cs b/snippets/csharp/System/String/StartsWith/startswith1.cs index ff9556bea64..e80576269b4 100644 --- a/snippets/csharp/System/String/StartsWith/startswith1.cs +++ b/snippets/csharp/System/String/StartsWith/startswith1.cs @@ -1,30 +1,27 @@ // using System; -public class Example +public class StartsWithComparisonExample { - public static void Main() - { - string[,] strings = { {"ABCdef", "abc" }, - {"ABCdef", "abc" }, + public static void Run() + { + string[,] strings = { {"ABCdef", "abc" }, + {"ABCdef", "abc" }, {"œil","oe" }, { "læring}", "lae" } }; - for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++) - { + for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++) + { foreach (string cmpName in Enum.GetNames(typeof(StringComparison))) - { - StringComparison strCmp = (StringComparison) Enum.Parse(typeof(StringComparison), - cmpName); - string instance = strings[ctr1, 0]; - string value = strings[ctr1, 1]; - Console.WriteLine("{0} starts with {1}: {2} ({3} comparison)", - instance, value, - instance.StartsWith(value, strCmp), - strCmp); + { + StringComparison strCmp = (StringComparison)Enum.Parse(typeof(StringComparison), + cmpName); + string instance = strings[ctr1, 0]; + string value = strings[ctr1, 1]; + Console.WriteLine($"{instance} starts with {value}: {instance.StartsWith(value, strCmp)} ({strCmp} comparison)"); } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output: // ABCdef starts with abc: False (CurrentCulture comparison) @@ -33,25 +30,25 @@ public static void Main() // ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison) // ABCdef starts with abc: False (Ordinal comparison) // ABCdef starts with abc: True (OrdinalIgnoreCase comparison) -// +// // ABCdef starts with abc: False (CurrentCulture comparison) // ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison) // ABCdef starts with abc: False (InvariantCulture comparison) // ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison) // ABCdef starts with abc: False (Ordinal comparison) // ABCdef starts with abc: True (OrdinalIgnoreCase comparison) -// +// // œil starts with oe: True (CurrentCulture comparison) // œil starts with oe: True (CurrentCultureIgnoreCase comparison) // œil starts with oe: True (InvariantCulture comparison) // œil starts with oe: True (InvariantCultureIgnoreCase comparison) // œil starts with oe: False (Ordinal comparison) // œil starts with oe: False (OrdinalIgnoreCase comparison) -// +// // læring} starts with lae: True (CurrentCulture comparison) // læring} starts with lae: True (CurrentCultureIgnoreCase comparison) // læring} starts with lae: True (InvariantCulture comparison) // læring} starts with lae: True (InvariantCultureIgnoreCase comparison) // læring} starts with lae: False (Ordinal comparison) // læring} starts with lae: False (OrdinalIgnoreCase comparison) -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/StartsWith/stringstartswith.cs b/snippets/csharp/System/String/StartsWith/stringstartswith.cs index 26240f86501..37c6f275cef 100644 --- a/snippets/csharp/System/String/StartsWith/stringstartswith.cs +++ b/snippets/csharp/System/String/StartsWith/stringstartswith.cs @@ -1,46 +1,49 @@ // using System; -public class Example +public class StartsWithTagsExample { - public static void Main() { - string [] strSource = { "This is bold text", "

This is large Text

", + public static void Run() + { + string[] strSource = [ "This is bold text", "

This is large Text

", "This has multiple tags", "This has embedded tags.", - "" ); - // Remove the tag. - if (lastLocation >= 0) { - item = item.Substring( lastLocation + 1 ); + private static string StripStartTags(string item) + { + // Determine whether a tag begins the string. + if (item.Trim().StartsWith("<")) + { + // Find the closing tag. + int lastLocation = item.IndexOf(">"); + // Remove the tag. + if (lastLocation >= 0) + { + item = item.Substring(lastLocation + 1); - // Remove any additional starting tags. - item = StripStartTags(item); - } - } + // Remove any additional starting tags. + item = StripStartTags(item); + } + } - return item; - } + return item; + } } // The example displays the following output: // The original strings: @@ -58,4 +61,4 @@ private static string StripStartTags(string item) // This has multiple tags
// This has embedded tags.
// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/StartsWith/swci.cs b/snippets/csharp/System/String/StartsWith/swci.cs index a99f88de7ae..84c89bef219 100644 --- a/snippets/csharp/System/String/StartsWith/swci.cs +++ b/snippets/csharp/System/String/StartsWith/swci.cs @@ -1,66 +1,66 @@ // -// This code example demonstrates the +// This code example demonstrates the // System.String.StartsWith(String, ..., CultureInfo) method. using System; -using System.Threading; + using System.Globalization; -class Sample +class Sample { - public static void Main() + public static void Run() { - string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n"; - string msg2 = "Using the {0} - \"{1}\" culture:"; - string msg3 = " The string to search ends with the target string: {0}"; - bool result = false; - CultureInfo ci; - -// Define a target string to search for. -// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE - string capitalARing = "\u00c5"; - -// Define a string to search. -// The result of combining the characters LATIN SMALL LETTER A and COMBINING -// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character -// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). - string aRingXYZ = "\u0061\u030a" + "xyz"; - -// Clear the screen and display an introduction. - Console.Clear(); - -// Display the string to search for and the string to search. - Console.WriteLine(msg1, capitalARing, aRingXYZ); - -// Search using English-United States culture. - ci = new CultureInfo("en-US"); - Console.WriteLine(msg2, ci.DisplayName, ci.Name); - - Console.WriteLine("Case sensitive:"); - result = aRingXYZ.StartsWith(capitalARing, false, ci); - Console.WriteLine(msg3, result); - - Console.WriteLine("Case insensitive:"); - result = aRingXYZ.StartsWith(capitalARing, true, ci); - Console.WriteLine(msg3, result); - Console.WriteLine(); - -// Search using Swedish-Sweden culture. - ci = new CultureInfo("sv-SE"); - Console.WriteLine(msg2, ci.DisplayName, ci.Name); - - Console.WriteLine("Case sensitive:"); - result = aRingXYZ.StartsWith(capitalARing, false, ci); - Console.WriteLine(msg3, result); - - Console.WriteLine("Case insensitive:"); - result = aRingXYZ.StartsWith(capitalARing, true, ci); - Console.WriteLine(msg3, result); + string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n"; + string msg2 = "Using the {0} - \"{1}\" culture:"; + string msg3 = " The string to search ends with the target string: {0}"; + bool result = false; + CultureInfo ci; + + // Define a target string to search for. + // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE + string capitalARing = "\u00c5"; + + // Define a string to search. + // The result of combining the characters LATIN SMALL LETTER A and COMBINING + // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character + // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5). + string aRingXYZ = "\u0061\u030a" + "xyz"; + + // Clear the screen and display an introduction. + Console.Clear(); + + // Display the string to search for and the string to search. + Console.WriteLine(msg1, capitalARing, aRingXYZ); + + // Search using English-United States culture. + ci = new("en-US"); + Console.WriteLine(msg2, ci.DisplayName, ci.Name); + + Console.WriteLine("Case sensitive:"); + result = aRingXYZ.StartsWith(capitalARing, false, ci); + Console.WriteLine(msg3, result); + + Console.WriteLine("Case insensitive:"); + result = aRingXYZ.StartsWith(capitalARing, true, ci); + Console.WriteLine(msg3, result); + Console.WriteLine(); + + // Search using Swedish-Sweden culture. + ci = new("sv-SE"); + Console.WriteLine(msg2, ci.DisplayName, ci.Name); + + Console.WriteLine("Case sensitive:"); + result = aRingXYZ.StartsWith(capitalARing, false, ci); + Console.WriteLine(msg3, result); + + Console.WriteLine("Case insensitive:"); + result = aRingXYZ.StartsWith(capitalARing, true, ci); + Console.WriteLine(msg3, result); } } /* -Note: This code example was executed on a console whose user interface +Note: This code example was executed on a console whose user interface culture is "en-US" (English-United States). Search for the target string "Å" in the string "a°xyz". @@ -78,4 +78,4 @@ Using the Swedish (Sweden) - "sv-SE" culture: The string to search ends with the target string: False */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/Substring/Program.cs b/snippets/csharp/System/String/Substring/Program.cs new file mode 100644 index 00000000000..19753f5314c --- /dev/null +++ b/snippets/csharp/System/String/Substring/Program.cs @@ -0,0 +1,6 @@ +Sample.Run(); +SubstringPairsExample.Run(); +SubStringTest.Run(); +SubstringRangeExample.Run(); +SubstringMarkupExample.Run(); +SubstringLengthExample.Run(); diff --git a/snippets/csharp/System/String/Substring/Project.csproj b/snippets/csharp/System/String/Substring/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/Substring/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/Substring/Substring1.cs b/snippets/csharp/System/String/Substring/Substring1.cs index 402eb41815e..fea8525f5f9 100644 --- a/snippets/csharp/System/String/Substring/Substring1.cs +++ b/snippets/csharp/System/String/Substring/Substring1.cs @@ -1,21 +1,19 @@ using System; -public class Example +public class SubstringPairsExample { - public static void Main() + public static void Run() { // - String[] pairs = { "Color1=red", "Color2=green", "Color3=blue", - "Title=Code Repository" }; - foreach (var pair in pairs) + string[] pairs = [ "Color1=red", "Color2=green", "Color3=blue", + "Title=Code Repository" ]; + foreach (string pair in pairs) { int position = pair.IndexOf("="); if (position < 0) continue; - Console.WriteLine("Key: {0}, Value: '{1}'", - pair.Substring(0, position), - pair.Substring(position + 1)); - } + Console.WriteLine($"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"); + } // The example displays the following output: // Key: Color1, Value: 'red' diff --git a/snippets/csharp/System/String/Substring/Substring10.cs b/snippets/csharp/System/String/Substring/Substring10.cs index 506c299b6a9..b842eee94ea 100644 --- a/snippets/csharp/System/String/Substring/Substring10.cs +++ b/snippets/csharp/System/String/Substring/Substring10.cs @@ -1,23 +1,23 @@ using System; -public class SubStringTest +public class SubStringTest { - public static void Main() + public static void Run() { // - string [] info = { "Name: Felica Walker", "Title: Mz.", - "Age: 47", "Location: Paris", "Gender: F"}; + string[] info = [ "Name: Felica Walker", "Title: Mz.", + "Age: 47", "Location: Paris", "Gender: F"]; int found = 0; Console.WriteLine("The initial values in the array are:"); foreach (string s in info) Console.WriteLine(s); - Console.WriteLine("\nWe want to retrieve only the key information. That is:"); - foreach (string s in info) + Console.WriteLine("\nWe want to retrieve only the key information. That is:"); + foreach (string s in info) { found = s.IndexOf(": "); - Console.WriteLine(" {0}", s.Substring(found + 2)); + Console.WriteLine($" {s.Substring(found + 2)}"); } // The example displays the following output: @@ -27,7 +27,7 @@ public static void Main() // Age: 47 // Location: Paris // Gender: F - // + // // We want to retrieve only the key information. That is: // Felica Walker // Mz. diff --git a/snippets/csharp/System/String/Substring/Substring2.cs b/snippets/csharp/System/String/Substring/Substring2.cs index acd79845e84..0421cf41a7a 100644 --- a/snippets/csharp/System/String/Substring/Substring2.cs +++ b/snippets/csharp/System/String/Substring/Substring2.cs @@ -1,18 +1,16 @@ using System; -public class Example +public class SubstringRangeExample { - public static void Main() + public static void Run() { // - String s = "aaaaabbbcccccccdd"; - Char charRange = 'b'; + string s = "aaaaabbbcccccccdd"; + char charRange = 'b'; int startIndex = s.IndexOf(charRange); int endIndex = s.LastIndexOf(charRange); int length = endIndex - startIndex + 1; - Console.WriteLine("{0}.Substring({1}, {2}) = {3}", - s, startIndex, length, - s.Substring(startIndex, length)); + Console.WriteLine($"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}"); // The example displays the following output: // aaaaabbbcccccccdd.Substring(5, 3) = bbb diff --git a/snippets/csharp/System/String/Substring/Substring3.cs b/snippets/csharp/System/String/Substring/Substring3.cs index 416aec100d2..21c73e29168 100644 --- a/snippets/csharp/System/String/Substring/Substring3.cs +++ b/snippets/csharp/System/String/Substring/Substring3.cs @@ -1,18 +1,18 @@ using System; -public class Example +public class SubstringMarkupExample { - public static void Main() + public static void Run() { // - String s = "extantstill in existence"; - String searchString = ""; + string s = "extantstill in existence"; + string searchString = ""; int startIndex = s.IndexOf(searchString); searchString = "extantstill in existence diff --git a/snippets/csharp/System/String/Substring/Substring4.cs b/snippets/csharp/System/String/Substring/Substring4.cs index 2e53ac13007..9ab1084956c 100644 --- a/snippets/csharp/System/String/Substring/Substring4.cs +++ b/snippets/csharp/System/String/Substring/Substring4.cs @@ -1,14 +1,14 @@ using System; -public class Example +public class SubstringLengthExample { - public static void Main() + public static void Run() { // - String value = "This is a string."; + string value = "This is a string."; int startIndex = 5; int length = 2; - String substring = value.Substring(startIndex, length); + string substring = value.Substring(startIndex, length); Console.WriteLine(substring); // The example displays the following output: diff --git a/snippets/csharp/System/String/Substring/source.cs b/snippets/csharp/System/String/Substring/source.cs index 9d0c99d6bd4..704c7b40266 100644 --- a/snippets/csharp/System/String/Substring/source.cs +++ b/snippets/csharp/System/String/Substring/source.cs @@ -1,30 +1,30 @@ -using System; +using System; public class Sample { - public static void Main() - { - // - string myString = "abc"; - bool test1 = myString.Substring(2, 1).Equals("c"); // This is true. - Console.WriteLine(test1); - bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true. - Console.WriteLine(test2); - try - { - string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException. - Console.WriteLine(str3); - } - catch (ArgumentOutOfRangeException e) - { - Console.WriteLine(e.Message); - } + public static void Run() + { + // + string myString = "abc"; + bool test1 = myString.Substring(2, 1).Equals("c"); // This is true. + Console.WriteLine(test1); + bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true. + Console.WriteLine(test2); + try + { + string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException. + Console.WriteLine(str3); + } + catch (ArgumentOutOfRangeException e) + { + Console.WriteLine(e.Message); + } - // The example displays the following output: - // True - // True - // Index and length must refer to a location within the string. - // Parameter name: length - // - } + // The example displays the following output: + // True + // True + // Index and length must refer to a location within the string. + // Parameter name: length + // + } } diff --git a/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs b/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs index eaa4a9ac086..1889b89b6fc 100644 --- a/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs +++ b/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - string s = "AaBbCcDd"; - char[] chars = s.ToCharArray(); - Console.WriteLine("Original string: {0}", s); - Console.WriteLine("Character array:"); - for (int ctr = 0; ctr < chars.Length; ctr++) - { - Console.WriteLine(" {0}: {1}", ctr, chars[ctr]); - } - } + public static void Main() + { + string s = "AaBbCcDd"; + char[] chars = s.ToCharArray(); + Console.WriteLine($"Original string: {s}"); + Console.WriteLine("Character array:"); + for (int ctr = 0; ctr < chars.Length; ctr++) + { + Console.WriteLine($" {ctr}: {chars[ctr]}"); + } + } } // The example displays the following output: diff --git a/snippets/csharp/System/String/ToCharArray/tocharry1.cs b/snippets/csharp/System/String/ToCharArray/tocharry1.cs index f35b6d2385c..eeb7f76b7ee 100644 --- a/snippets/csharp/System/String/ToCharArray/tocharry1.cs +++ b/snippets/csharp/System/String/ToCharArray/tocharry1.cs @@ -2,18 +2,20 @@ // Sample for String.ToCharArray(Int32, Int32) using System; -class Sample { - public static void Main() { - string str = "012wxyz789"; - char[] arr; +class Sample +{ + public static void Main() + { + string str = "012wxyz789"; + char[] arr; - arr = str.ToCharArray(3, 4); - Console.Write("The letters in '{0}' are: '", str); - Console.Write(arr); - Console.WriteLine("'"); - Console.WriteLine("Each letter in '{0}' is:", str); - foreach (char c in arr) - Console.WriteLine(c); + arr = str.ToCharArray(3, 4); + Console.Write($"The letters in '{str}' are: '"); + Console.Write(arr); + Console.WriteLine("'"); + Console.WriteLine($"Each letter in '{str}' is:"); + foreach (char c in arr) + Console.WriteLine(c); } } /* @@ -25,4 +27,4 @@ public static void Main() { y z */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/ToLower/stringtolower.cs b/snippets/csharp/System/String/ToLower/stringtolower.cs index 29ef7208e9d..2adee0fd49c 100644 --- a/snippets/csharp/System/String/ToLower/stringtolower.cs +++ b/snippets/csharp/System/String/ToLower/stringtolower.cs @@ -1,21 +1,23 @@ // using System; -public class ToLowerTest { - public static void Main() { +public class ToLowerTest +{ + public static void Main() + { - string [] info = {"Name", "Title", "Age", "Location", "Gender"}; + string[] info = ["Name", "Title", "Age", "Location", "Gender"]; Console.WriteLine("The initial values in the array are:"); foreach (string s in info) Console.WriteLine(s); - Console.WriteLine("{0}The lowercase of these values is:", Environment.NewLine); + Console.WriteLine($"{Environment.NewLine}The lowercase of these values is:"); foreach (string s in info) Console.WriteLine(s.ToLower()); - Console.WriteLine("{0}The uppercase of these values is:", Environment.NewLine); + Console.WriteLine($"{Environment.NewLine}The uppercase of these values is:"); foreach (string s in info) Console.WriteLine(s.ToUpper()); diff --git a/snippets/csharp/System/String/ToLower/tolower.cs b/snippets/csharp/System/String/ToLower/tolower.cs index bbb29b0fb76..4c08e859d75 100644 --- a/snippets/csharp/System/String/ToLower/tolower.cs +++ b/snippets/csharp/System/String/ToLower/tolower.cs @@ -8,43 +8,41 @@ class Sample { public static void Main() { - String str1 = "INDIGO"; - // str2 = str1, except each 'I' is '\u0130' (Unicode LATIN CAPITAL I WITH DOT ABOVE). - String str2 = new String(new Char[] {'\u0130', 'N', 'D', '\u0130', 'G', 'O'}); - String str3, str4; - - Console.WriteLine(); - Console.WriteLine("str1 = '{0}'", str1); - - Console.WriteLine(); - Console.WriteLine("str1 is {0} to str2.", - ((0 == String.CompareOrdinal(str1, str2)) ? "equal" : "not equal")); - CodePoints("str1", str1); - CodePoints("str2", str2); - - Console.WriteLine(); - // str3 is a lower case copy of str2, using English-United States culture. - Console.WriteLine("str3 = Lower case copy of str2 using English-United States culture."); - str3 = str2.ToLower(new CultureInfo("en-US", false)); - - // str4 is a lower case copy of str2, using Turkish-Turkey culture. - Console.WriteLine("str4 = Lower case copy of str2 using Turkish-Turkey culture."); - str4 = str2.ToLower(new CultureInfo("tr-TR", false)); - - // Compare the code points in str3 and str4. - Console.WriteLine(); - Console.WriteLine("str3 is {0} to str4.", - ((0 == String.CompareOrdinal(str3, str4)) ? "equal" : "not equal")); - CodePoints("str3", str3); - CodePoints("str4", str4); + string str1 = "INDIGO"; + // str2 = str1, except each 'I' is '\u0130' (Unicode LATIN CAPITAL I WITH DOT ABOVE). + string str2 = new(['\u0130', 'N', 'D', '\u0130', 'G', 'O']); + string str3, str4; + + Console.WriteLine(); + Console.WriteLine($"str1 = '{str1}'"); + + Console.WriteLine(); + Console.WriteLine($"str1 is {((0 == string.CompareOrdinal(str1, str2)) ? "equal" : "not equal")} to str2."); + CodePoints("str1", str1); + CodePoints("str2", str2); + + Console.WriteLine(); + // str3 is a lower case copy of str2, using English-United States culture. + Console.WriteLine("str3 = Lower case copy of str2 using English-United States culture."); + str3 = str2.ToLower(new CultureInfo("en-US", false)); + + // str4 is a lower case copy of str2, using Turkish-Turkey culture. + Console.WriteLine("str4 = Lower case copy of str2 using Turkish-Turkey culture."); + str4 = str2.ToLower(new CultureInfo("tr-TR", false)); + + // Compare the code points in str3 and str4. + Console.WriteLine(); + Console.WriteLine($"str3 is {((0 == string.CompareOrdinal(str3, str4)) ? "equal" : "not equal")} to str4."); + CodePoints("str3", str3); + CodePoints("str4", str4); } - public static void CodePoints(String title, String s) + public static void CodePoints(string title, string s) { - Console.Write("{0}The code points in {1} are: {0}", Environment.NewLine, title); - foreach (ushort u in s) - Console.Write("{0:x4} ", u); - Console.WriteLine(); + Console.Write("{0}The code points in {1} are: {0}", Environment.NewLine, title); + foreach (ushort u in s) + Console.Write($"{u:x4} "); + Console.WriteLine(); } } /* @@ -71,4 +69,4 @@ 0069 006e 0064 0069 0067 006f The code points in str4 are: 0069 006e 0064 0069 0067 006f */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs b/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs index 6ecbc70c5dc..17689075c97 100644 --- a/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs +++ b/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs @@ -3,28 +3,28 @@ public class Example { - public static void Main() - { - string[] words = { "Tuesday", "Salı", "Вторник", "Mardi", - "Τρίτη", "Martes", "יום שלישי", - "الثلاثاء", "วันอังคาร" }; - // Display array in unsorted order. - foreach (string word in words) - Console.WriteLine(word); - Console.WriteLine(); + public static void Main() + { + string[] words = [ "Tuesday", "Salı", "Вторник", "Mardi", + "Τρίτη", "Martes", "יום שלישי", + "الثلاثاء", "วันอังคาร" ]; + // Display array in unsorted order. + foreach (string word in words) + Console.WriteLine(word); + Console.WriteLine(); - // Create parallel array of words by calling ToLowerInvariant. - string[] lowerWords = new string[words.Length]; - for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++) - lowerWords[ctr] = words[ctr].ToLowerInvariant(); - - // Sort the words array based on the order of lowerWords. - Array.Sort(lowerWords, words, StringComparer.InvariantCulture); - - // Display the sorted array. - foreach (string word in words) - Console.WriteLine(word); - } + // Create parallel array of words by calling ToLowerInvariant. + string[] lowerWords = new string[words.Length]; + for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++) + lowerWords[ctr] = words[ctr].ToLowerInvariant(); + + // Sort the words array based on the order of lowerWords. + Array.Sort(lowerWords, words, StringComparer.InvariantCulture); + + // Display the sorted array. + foreach (string word in words) + Console.WriteLine(word); + } } // The example displays the following output: // Tuesday @@ -36,7 +36,7 @@ public static void Main() // יום שלישי // الثلاثاء // วันอังคาร -// +// // Mardi // Martes // Salı diff --git a/snippets/csharp/System/String/ToString/string.tostring.cs b/snippets/csharp/System/String/ToString/string.tostring.cs index b5a903fb20d..e8776a2d65f 100644 --- a/snippets/csharp/System/String/ToString/string.tostring.cs +++ b/snippets/csharp/System/String/ToString/string.tostring.cs @@ -1,19 +1,21 @@ // using System; -class stringToString { - public static void Main() { - String str1 = "123"; - String str2 = "abc"; +class stringToString +{ + public static void Main() + { + string str1 = "123"; + string str2 = "abc"; - Console.WriteLine("Original str1: {0}", str1); - Console.WriteLine("Original str2: {0}", str2); - Console.WriteLine("str1 same as str2?: {0}", Object.ReferenceEquals(str1, str2)); + Console.WriteLine($"Original str1: {str1}"); + Console.WriteLine($"Original str2: {str2}"); + Console.WriteLine($"str1 same as str2?: {object.ReferenceEquals(str1, str2)}"); - str2 = str1.ToString(); - Console.WriteLine(); - Console.WriteLine("New str2: {0}", str2); - Console.WriteLine("str1 same as str2?: {0}", Object.ReferenceEquals(str1, str2)); + str2 = str1.ToString(); + Console.WriteLine(); + Console.WriteLine($"New str2: {str2}"); + Console.WriteLine($"str1 same as str2?: {object.ReferenceEquals(str1, str2)}"); } } /* @@ -25,4 +27,4 @@ public static void Main() { New str2: 123 str1 same as str2?: True */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/String/ToUpper/Program.cs b/snippets/csharp/System/String/ToUpper/Program.cs new file mode 100644 index 00000000000..a41aa44bd7f --- /dev/null +++ b/snippets/csharp/System/String/ToUpper/Program.cs @@ -0,0 +1,2 @@ +ToUpperCultureExample.Run(); +ToUpperRangeExample.Run(); diff --git a/snippets/csharp/System/String/ToUpper/Project.csproj b/snippets/csharp/System/String/ToUpper/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/ToUpper/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/ToUpper/ToUpperEx.cs b/snippets/csharp/System/String/ToUpper/ToUpperEx.cs index cf55d2f9448..9579fc4a815 100644 --- a/snippets/csharp/System/String/ToUpper/ToUpperEx.cs +++ b/snippets/csharp/System/String/ToUpper/ToUpperEx.cs @@ -1,25 +1,23 @@ // using System; -public class Example +public class ToUpperRangeExample { - public static void Main() - { - int n = 0; - for (int ctr = 0x20; ctr <= 0x017F; ctr++) { - string string1 = ((char)ctr).ToString(); - string upperString = string1.ToUpper(); - if (string1 != upperString) { - Console.Write(@"{0} (\u+{1}) --> {2} (\u+{3}) ", - string1, - Convert.ToUInt16(string1[0]).ToString("X4"), - upperString, - Convert.ToUInt16(upperString[0]).ToString("X4")); - n++; - if (n % 2 == 0) Console.WriteLine(); - } - } - } + public static void Run() + { + int n = 0; + for (int ctr = 0x20; ctr <= 0x017F; ctr++) + { + string string1 = ((char)ctr).ToString(); + string upperString = string1.ToUpper(); + if (string1 != upperString) + { + Console.Write($"{string1} (\\u+{Convert.ToUInt16(string1[0]):X4}) --> {upperString} (\\u+{Convert.ToUInt16(upperString[0]):X4}) "); + n++; + if (n % 2 == 0) Console.WriteLine(); + } + } + } } // The example displays the following output: // a (\u+0061) --> A (\u+0041) b (\u+0062) --> B (\u+0042) diff --git a/snippets/csharp/System/String/ToUpper/toupper.cs b/snippets/csharp/System/String/ToUpper/toupper.cs index 1e92fd80243..bd17eb38918 100644 --- a/snippets/csharp/System/String/ToUpper/toupper.cs +++ b/snippets/csharp/System/String/ToUpper/toupper.cs @@ -2,33 +2,32 @@ using System; using System.Globalization; -class Example +class ToUpperCultureExample { - public static void Main() + public static void Run() { - string str1 = "indigo"; - string str2, str3; + string str1 = "indigo"; + string str2, str3; - // str2 is an uppercase copy of str1, using English-United States culture. - str2 = str1.ToUpper(new CultureInfo("en-US", false)); + // str2 is an uppercase copy of str1, using English-United States culture. + str2 = str1.ToUpper(new CultureInfo("en-US", false)); - // str3 is an uppercase copy of str1, using Turkish-Turkey culture. - str3 = str1.ToUpper(new CultureInfo("tr-TR", false)); + // str3 is an uppercase copy of str1, using Turkish-Turkey culture. + str3 = str1.ToUpper(new CultureInfo("tr-TR", false)); - // Compare the code points and compare the uppercase strings. - ShowCodePoints("str1", str1); - ShowCodePoints("str2", str2); - ShowCodePoints("str3", str3); - Console.WriteLine("str2 is {0} to str3.", - String.CompareOrdinal(str2, str3) == 0 ? "equal" : "not equal"); + // Compare the code points and compare the uppercase strings. + ShowCodePoints("str1", str1); + ShowCodePoints("str2", str2); + ShowCodePoints("str3", str3); + Console.WriteLine($"str2 is {(string.CompareOrdinal(str2, str3) == 0 ? "equal" : "not equal")} to str3."); } public static void ShowCodePoints(string varName, string s) { - Console.Write("{0} = {1}: ", varName, s); - foreach (ushort u in s) - Console.Write("{0:x4} ", u); - Console.WriteLine(); + Console.Write($"{varName} = {s}: "); + foreach (ushort u in s) + Console.Write($"{u:x4} "); + Console.WriteLine(); } } // This example displays the following output: diff --git a/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs b/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs index 9dce95d3ae0..e7257e08f70 100644 --- a/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs +++ b/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs @@ -4,33 +4,33 @@ public class Example { - public static void Main() - { - string[] words = { "Tuesday", "Salı", "Вторник", "Mardi", - "Τρίτη", "Martes", "יום שלישי", - "الثلاثاء", "วันอังคาร" }; - StreamWriter sw = new StreamWriter(@".\output.txt"); - - // Display array in unsorted order. - foreach (string word in words) - sw.WriteLine(word); + public static void Main() + { + string[] words = [ "Tuesday", "Salı", "Вторник", "Mardi", + "Τρίτη", "Martes", "יום שלישי", + "الثلاثاء", "วันอังคาร" ]; + StreamWriter sw = new(@".\output.txt"); - sw.WriteLine(); + // Display array in unsorted order. + foreach (string word in words) + sw.WriteLine(word); - // Create parallel array of words by calling ToUpperInvariant. - string[] upperWords = new string[words.Length]; - for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++) - upperWords[ctr] = words[ctr].ToUpperInvariant(); - - // Sort the words array based on the order of upperWords. - Array.Sort(upperWords, words, StringComparer.InvariantCulture); - - // Display the sorted array. - foreach (string word in words) - sw.WriteLine(word); + sw.WriteLine(); - sw.Close(); - } + // Create parallel array of words by calling ToUpperInvariant. + string[] upperWords = new string[words.Length]; + for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++) + upperWords[ctr] = words[ctr].ToUpperInvariant(); + + // Sort the words array based on the order of upperWords. + Array.Sort(upperWords, words, StringComparer.InvariantCulture); + + // Display the sorted array. + foreach (string word in words) + sw.WriteLine(word); + + sw.Close(); + } } // The example produces the following output: // Tuesday @@ -42,7 +42,7 @@ public static void Main() // יום שלישי // الثلاثاء // วันอังคาร -// +// // Mardi // Martes // Salı diff --git a/snippets/csharp/System/String/Trim/Program.cs b/snippets/csharp/System/String/Trim/Program.cs new file mode 100644 index 00000000000..66a3b1a9e9b --- /dev/null +++ b/snippets/csharp/System/String/Trim/Program.cs @@ -0,0 +1,2 @@ +TrimCharactersExample.Run(); +TrimWhitespaceExample.Run(); diff --git a/snippets/csharp/System/String/Trim/Project.csproj b/snippets/csharp/System/String/Trim/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/Trim/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/Trim/Trim1.cs b/snippets/csharp/System/String/Trim/Trim1.cs index 26691f7a314..9d426873d8b 100644 --- a/snippets/csharp/System/String/Trim/Trim1.cs +++ b/snippets/csharp/System/String/Trim/Trim1.cs @@ -1,14 +1,14 @@ using System; -public class Example +public class TrimCharactersExample { - public static void Main() + public static void Run() { // - char[] charsToTrim = { '*', ' ', '\''}; + char[] charsToTrim = ['*', ' ', '\'']; string banner = "*** Much Ado About Nothing ***"; string result = banner.Trim(charsToTrim); - Console.WriteLine("Trimmed\n {0}\nto\n '{1}'", banner, result); + Console.WriteLine($"Trimmed\n {banner}\nto\n '{result}'"); // The example displays the following output: // Trimmed diff --git a/snippets/csharp/System/String/Trim/Trim2.cs b/snippets/csharp/System/String/Trim/Trim2.cs index 0bdc80fa401..71c9db9e2a5 100644 --- a/snippets/csharp/System/String/Trim/Trim2.cs +++ b/snippets/csharp/System/String/Trim/Trim2.cs @@ -1,24 +1,23 @@ // using System; -public class Example +public class TrimWhitespaceExample { - public static void Main() + public static void Run() { Console.Write("Enter your first name: "); string firstName = Console.ReadLine(); - + Console.Write("Enter your middle name or initial: "); string middleName = Console.ReadLine(); - + Console.Write("Enter your last name: "); string lastName = Console.ReadLine(); - + Console.WriteLine(); - Console.WriteLine("You entered '{0}', '{1}', and '{2}'.", - firstName, middleName, lastName); - - string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " + + Console.WriteLine($"You entered '{firstName}', '{middleName}', and '{lastName}'."); + + string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " + lastName.Trim()).Trim(); Console.WriteLine("The result is " + name + "."); @@ -26,7 +25,7 @@ public static void Main() // Enter your first name: John // Enter your middle name or initial: // Enter your last name: Doe - // + // // You entered ' John ', '', and ' Doe'. // The result is John Doe. } diff --git a/snippets/csharp/System/String/TrimEnd/sample.cs b/snippets/csharp/System/String/TrimEnd/sample.cs index b2afd221a1d..cb6f273dfd9 100644 --- a/snippets/csharp/System/String/TrimEnd/sample.cs +++ b/snippets/csharp/System/String/TrimEnd/sample.cs @@ -10,14 +10,14 @@ public static void Main() // Create a string that will be trimmed. string path = "c:/temp//"; - // Create an array of characters + // Create an array of characters // that represent characters to trim. - char[] charsToTrim = {'/'}; + char[] charsToTrim = ['/']; // Thim the string. string trimmedPath = path.TrimEnd(charsToTrim); - Console.WriteLine("The trimmed value is: {0}.", trimmedPath); + Console.WriteLine($"The trimmed value is: {trimmedPath}."); // Create a string that will be trimmed. string pathWhitespace = "c:/temp/ "; @@ -25,7 +25,7 @@ public static void Main() // Trim white spaces by passing null. string trimmedWhiteSpace = pathWhitespace.TrimEnd(null); - Console.WriteLine("The trimmed value is: {0}.", trimmedWhiteSpace); + Console.WriteLine($"The trimmed value is: {trimmedWhiteSpace}."); // This code example displays the following // to the console: diff --git a/snippets/csharp/System/String/TrimEnd/sample2.cs b/snippets/csharp/System/String/TrimEnd/sample2.cs index 5633c27b470..b8a12116816 100644 --- a/snippets/csharp/System/String/TrimEnd/sample2.cs +++ b/snippets/csharp/System/String/TrimEnd/sample2.cs @@ -2,26 +2,26 @@ public class TrimEnd { - public static void Main() - { - // - string sentence = "The dog had a bone, a ball, and other toys."; - char[] charsToTrim = {',', '.', ' '}; - string[] words = sentence.Split(); - foreach (string word in words) - Console.WriteLine(word.TrimEnd(charsToTrim)); + public static void Main() + { + // + string sentence = "The dog had a bone, a ball, and other toys."; + char[] charsToTrim = [',', '.', ' ']; + string[] words = sentence.Split(); + foreach (string word in words) + Console.WriteLine(word.TrimEnd(charsToTrim)); - // The example displays the following output: - // The - // dog - // had - // a - // bone - // a - // ball - // and - // other - // toys - // - } + // The example displays the following output: + // The + // dog + // had + // a + // bone + // a + // ball + // and + // other + // toys + // + } } diff --git a/snippets/csharp/System/String/TrimStart/Program.cs b/snippets/csharp/System/String/TrimStart/Program.cs new file mode 100644 index 00000000000..ec639d3a19d --- /dev/null +++ b/snippets/csharp/System/String/TrimStart/Program.cs @@ -0,0 +1,2 @@ +TrimExample.Run(); +TrimExample.Run(args); diff --git a/snippets/csharp/System/String/TrimStart/Project.csproj b/snippets/csharp/System/String/TrimStart/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/String/TrimStart/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/String/TrimStart/sample.cs b/snippets/csharp/System/String/TrimStart/sample.cs index a6ad6c030c5..77e49547fef 100644 --- a/snippets/csharp/System/String/TrimStart/sample.cs +++ b/snippets/csharp/System/String/TrimStart/sample.cs @@ -4,9 +4,9 @@ public class TrimExample { // - public static void Main() + public static void Run() { - string[] lines = {"using System;", + string[] lines = ["using System;", "", "public class HelloWorld", "{", @@ -16,20 +16,20 @@ public static void Main() " // to the console.", " Console.WriteLine(\"Hello, World.\");", " }", - "}"}; + "}"]; Console.WriteLine("Before call to StripComments:"); foreach (string line in lines) - Console.WriteLine(" {0}", line); + Console.WriteLine($" {line}"); string[] strippedLines = StripComments(lines); Console.WriteLine("After call to StripComments:"); foreach (string line in strippedLines) - Console.WriteLine(" {0}", line); + Console.WriteLine($" {line}"); } // This code produces the following output to the console: // Before call to StripComments: // using System; - // + // // public class HelloWorld // { // public static void Main() @@ -38,7 +38,7 @@ public static void Main() // // to the console. // Console.WriteLine("Hello, World."); // } - // } + // } // After call to StripComments: // This code displays a simple greeting // to the console. @@ -47,17 +47,17 @@ public static void Main() // public static string[] StripComments(string[] lines) { - List lineList = new List(); + List lineList = new(); foreach (string line in lines) { if (line.TrimStart(' ').StartsWith("//")) lineList.Add(line.TrimStart(' ', '/')); } - return lineList.ToArray(); + return [.. lineList]; } // - public static void Main(string[] args) + public static void Run(string[] args) { // // TrimStart examples @@ -68,9 +68,9 @@ public static void Main(string[] args) string lineAfterTrimStart = string.Empty; // Make it easy to print out and work with all of the examples - string[] lines = { lineWithLeadingSpaces, lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters }; + string[] lines = [lineWithLeadingSpaces, lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters]; - foreach (var line in lines) + foreach (string line in lines) { Console.WriteLine($"This line has leading characters: {line}"); } @@ -83,19 +83,19 @@ public static void Main(string[] args) // A basic demonstration of TrimStart in action lineAfterTrimStart = lineWithLeadingSpaces.TrimStart(' '); Console.WriteLine($"This is the result after calling TrimStart: {lineAfterTrimStart}"); - // This is the result after calling TrimStart: Hello World! + // This is the result after calling TrimStart: Hello World! // Since TrimStart accepts a character array of leading items to be removed as an argument, - // it's possible to do things like trim multiple pieces of data that each have different + // it's possible to do things like trim multiple pieces of data that each have different // leading characters, - foreach (var lineToEdit in lines) + foreach (string lineToEdit in lines) { Console.WriteLine(lineToEdit.TrimStart(' ', '$', '_', 'x')); } // Result for each: Hello World! - // or handle pieces of data that have multiple kinds of leading characters - var lineToBeTrimmed = "__###__ John Smith"; + // or handle pieces of data that have multiple kinds of leading characters + string lineToBeTrimmed = "__###__ John Smith"; lineAfterTrimStart = lineToBeTrimmed.TrimStart('_', '#', ' '); Console.WriteLine(lineAfterTrimStart); // Result: John Smith diff --git a/snippets/csharp/System/String/op_Equality/equalityop.cs b/snippets/csharp/System/String/op_Equality/equalityop.cs index 774547302c4..7eb30304a97 100644 --- a/snippets/csharp/System/String/op_Equality/equalityop.cs +++ b/snippets/csharp/System/String/op_Equality/equalityop.cs @@ -2,31 +2,29 @@ // Example for the String Equality operator. using System; -class EqualityOp +class EqualityOp { - public static void Main() + public static void Main() { - Console.WriteLine( + Console.WriteLine( "This example of the String Equality operator\n" + - "generates the following output.\n" ); + "generates the following output.\n"); - CompareAndDisplay( "ijkl" ); - CompareAndDisplay( "ABCD" ); - CompareAndDisplay( "abcd" ); + CompareAndDisplay("ijkl"); + CompareAndDisplay("ABCD"); + CompareAndDisplay("abcd"); } - static void CompareAndDisplay( string Comparand ) + static void CompareAndDisplay(string Comparand) { - String Lower = "abcd"; + string Lower = "abcd"; - Console.WriteLine( - "\"{0}\" == \"{1}\" ? {2}", - Lower, Comparand, Lower == Comparand ); + Console.WriteLine($"\"{Lower}\" == \"{Comparand}\" ? {Lower == Comparand}"); } } /* -This example of the String Equality operator +This example of the String Equality operator generates the following output. "abcd" == "ijkl" ? False diff --git a/snippets/csharp/System/String/op_Inequality/inequalityop.cs b/snippets/csharp/System/String/op_Inequality/inequalityop.cs index af9df24bc50..41f5fd78572 100644 --- a/snippets/csharp/System/String/op_Inequality/inequalityop.cs +++ b/snippets/csharp/System/String/op_Inequality/inequalityop.cs @@ -2,26 +2,24 @@ // Example for the String Inequality operator. using System; -class InequalityOp +class InequalityOp { - public static void Main() + public static void Main() { - Console.WriteLine( + Console.WriteLine( "This example of the String Inequality operator\n" + - "generates the following output.\n" ); + "generates the following output.\n"); - CompareAndDisplay( "ijkl" ); - CompareAndDisplay( "ABCD" ); - CompareAndDisplay( "abcd" ); + CompareAndDisplay("ijkl"); + CompareAndDisplay("ABCD"); + CompareAndDisplay("abcd"); } - static void CompareAndDisplay( String Comparand ) + static void CompareAndDisplay(string Comparand) { - String Lower = "abcd"; + string Lower = "abcd"; - Console.WriteLine( - "\"{0}\" != \"{1}\" ? {2}", - Lower, Comparand, Lower != Comparand ); + Console.WriteLine($"\"{Lower}\" != \"{Comparand}\" ? {Lower != Comparand}"); } } diff --git a/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs b/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs index 3bfc91e491d..d740f2bb442 100644 --- a/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs +++ b/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs @@ -2,33 +2,33 @@ public class StringComparerTest { - public static void Main() - { - StringComparerTest test = new StringComparerTest(); - test.CompareCurrentCultureStringComparer(); - test.CompareCurrentCultureInsensitiveStringComparer(); - } + public static void Main() + { + StringComparerTest test = new(); + test.CompareCurrentCultureStringComparer(); + test.CompareCurrentCultureInsensitiveStringComparer(); + } - // - private void CompareCurrentCultureStringComparer() - { - StringComparer stringComparer1 = StringComparer.CurrentCulture; - StringComparer stringComparer2 = StringComparer.CurrentCulture; - // Displays false - Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1, - stringComparer2)); - } - // + // + private void CompareCurrentCultureStringComparer() + { + StringComparer stringComparer1 = StringComparer.CurrentCulture; + StringComparer stringComparer2 = StringComparer.CurrentCulture; + // Displays false + Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1, + stringComparer2)); + } + // - // - private void CompareCurrentCultureInsensitiveStringComparer() - { - StringComparer stringComparer1, stringComparer2; - stringComparer1 = StringComparer.CurrentCultureIgnoreCase; - stringComparer2 = StringComparer.CurrentCultureIgnoreCase; - // Displays false - Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1, - stringComparer2)); - } - // + // + private void CompareCurrentCultureInsensitiveStringComparer() + { + StringComparer stringComparer1, stringComparer2; + stringComparer1 = StringComparer.CurrentCultureIgnoreCase; + stringComparer2 = StringComparer.CurrentCultureIgnoreCase; + // Displays false + Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1, + stringComparer2)); + } + // } diff --git a/snippets/csharp/System/StringComparer/Overview/omni.cs b/snippets/csharp/System/StringComparer/Overview/omni.cs index c008dab1a26..d4d49884848 100644 --- a/snippets/csharp/System/StringComparer/Overview/omni.cs +++ b/snippets/csharp/System/StringComparer/Overview/omni.cs @@ -1,28 +1,28 @@ // -// This example demonstrates members of the +// This example demonstrates members of the // System.StringComparer class. using System; -using System.Collections; + using System.Collections.Generic; using System.Globalization; using System.Threading; -class Sample +class Sample { - public static void Main() + public static void Main() { // Create a list of string. - List list = new List(); + List list = new(); // Get the tr-TR (Turkish-Turkey) culture. - CultureInfo turkish = new CultureInfo("tr-TR"); + CultureInfo turkish = new("tr-TR"); // Get the culture that is associated with the current thread. CultureInfo thisCulture = Thread.CurrentThread.CurrentCulture; // Get the standard StringComparers. - StringComparer invCmp = StringComparer.InvariantCulture; + StringComparer invCmp = StringComparer.InvariantCulture; StringComparer invICCmp = StringComparer.InvariantCultureIgnoreCase; StringComparer currCmp = StringComparer.CurrentCulture; StringComparer currICCmp = StringComparer.CurrentCultureIgnoreCase; @@ -34,10 +34,10 @@ public static void Main() // Define three strings consisting of different versions of the letter I. // LATIN CAPITAL LETTER I (U+0049) - string capitalLetterI = "I"; + string capitalLetterI = "I"; // LATIN SMALL LETTER I (U+0069) - string smallLetterI = "i"; + string smallLetterI = "i"; // LATIN SMALL LETTER DOTLESS I (U+0131) string smallLetterDotlessI = "\u0131"; @@ -57,7 +57,7 @@ public static void Main() Display(list, "Invariant culture, ignore case..."); // Sort the list using the current culture. - Console.WriteLine("The current culture is \"{0}\".", thisCulture.Name); + Console.WriteLine($"The current culture is \"{thisCulture.Name}\"."); list.Sort(currCmp); Display(list, "Current culture..."); list.Sort(currICCmp); @@ -69,7 +69,7 @@ public static void Main() list.Sort(ordICCmp); Display(list, "Ordinal, ignore case..."); - // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER + // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER // DOTLESS I differently than LATIN SMALL LETTER I. list.Sort(turkICComp); Display(list, "Turkish culture, ignore case..."); @@ -77,14 +77,14 @@ public static void Main() public static void Display(List lst, string title) { - Char c; - int codePoint; + char c; + int codePoint; Console.WriteLine(title); foreach (string s in lst) { c = s[0]; codePoint = Convert.ToInt32(c); - Console.WriteLine("0x{0:x}", codePoint); + Console.WriteLine($"0x{codePoint:x}"); } Console.WriteLine(); } From 4a3eddb65b474c136dba0086b12f17eec925090b Mon Sep 17 00:00:00 2001 From: Steve Pfister Date: Fri, 14 Aug 2026 13:19:40 -0400 Subject: [PATCH 7/9] Fix XmlReader.GetAttribute return documentation (#12986) * Fix XmlReader GetAttribute return docs Clarify that the named GetAttribute overloads return null only when the requested attribute is absent. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- xml/System.Xml/XmlReader.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xml/System.Xml/XmlReader.xml b/xml/System.Xml/XmlReader.xml index 58c5fbf1579..750bc51cc8e 100644 --- a/xml/System.Xml/XmlReader.xml +++ b/xml/System.Xml/XmlReader.xml @@ -1933,7 +1933,7 @@ This means that the can access any locations that do The qualified name of the attribute. When overridden in a derived class, gets the value of the attribute with the specified . - The value of the specified attribute. If the attribute is not found or the value is , is returned. + The value of the specified attribute. If the attribute is not found, is returned. If the attribute is present but has an empty value, is returned. can access any locations that do The local name of the attribute. The namespace URI of the attribute. When overridden in a derived class, gets the value of the attribute with the specified and . - The value of the specified attribute. If the attribute is not found or the value is , is returned. This method does not move the reader. + The value of the specified attribute. If the attribute is not found, is returned. This method does not move the reader. Date: Fri, 14 Aug 2026 10:23:34 -0700 Subject: [PATCH 8/9] Modernize C# code snippets - System/U*, System/V*, System/W* (#12974) --- .../csharp/System/UInt16/CompareTo/source.cs | 600 +++++++++--------- .../System/UInt16/Equals/equalsoverl.cs | 66 +- .../System/UInt16/Equals/uint16_equals.cs | 6 +- .../csharp/System/UInt16/MaxValue/MaxValue.cs | 34 +- .../csharp/System/UInt16/Parse/Program.cs | 4 + .../csharp/System/UInt16/Parse/Project.csproj | 8 + .../csharp/System/UInt16/Parse/parseex2.cs | 66 +- .../csharp/System/UInt16/Parse/parseex3.cs | 61 +- .../csharp/System/UInt16/Parse/parseex4.cs | 66 +- .../csharp/System/UInt16/Parse/parseex5.cs | 46 +- .../csharp/System/UInt16/ToString/Program.cs | 4 + .../System/UInt16/ToString/Project.csproj | 8 + .../System/UInt16/ToString/tostring1.cs | 29 +- .../System/UInt16/ToString/tostring2.cs | 38 +- .../System/UInt16/ToString/tostring3.cs | 22 +- .../System/UInt16/ToString/tostring4.cs | 48 +- .../csharp/System/UInt16/TryParse/Program.cs | 3 + .../System/UInt16/TryParse/Project.csproj | 8 + .../System/UInt16/TryParse/tryparse11.cs | 62 +- .../System/UInt16/TryParse/tryparse2.cs | 96 +-- .../System/UInt16/TryParse/tryparse21.cs | 96 +-- .../csharp/System/UInt32/CompareTo/source.cs | 600 +++++++++--------- .../System/UInt32/Equals/equalsoverl.cs | 66 +- .../System/UInt32/Equals/uint32_equals.cs | 46 +- .../System/UInt32/MaxValue/MaxValue1.cs | 66 +- .../csharp/System/UInt32/Parse/Program.cs | 3 + .../csharp/System/UInt32/Parse/Project.csproj | 8 + snippets/csharp/System/UInt32/Parse/parse1.cs | 71 ++- .../csharp/System/UInt32/Parse/parseex2.cs | 76 +-- .../csharp/System/UInt32/Parse/parseex4.cs | 68 +- .../csharp/System/UInt32/ToString/Program.cs | 4 + .../System/UInt32/ToString/Project.csproj | 8 + .../System/UInt32/ToString/tostring1.cs | 31 +- .../System/UInt32/ToString/tostring2.cs | 38 +- .../System/UInt32/ToString/tostring3.cs | 22 +- .../System/UInt32/ToString/tostring4.cs | 48 +- .../csharp/System/UInt64/CompareTo/source.cs | 600 +++++++++--------- .../csharp/System/UInt64/Equals/Program.cs | 3 + .../System/UInt64/Equals/Project.csproj | 8 + .../csharp/System/UInt64/Equals/equals1.cs | 25 +- .../System/UInt64/Equals/equalsoverl.cs | 68 +- .../System/UInt64/Equals/uint64_equals.cs | 23 +- .../System/UInt64/MaxValue/MaxValue1.cs | 69 +- .../csharp/System/UInt64/Parse/Program.cs | 3 + .../csharp/System/UInt64/Parse/Project.csproj | 8 + snippets/csharp/System/UInt64/Parse/parse1.cs | 67 +- .../csharp/System/UInt64/Parse/parseex2.cs | 74 +-- .../csharp/System/UInt64/Parse/parseex4.cs | 66 +- .../csharp/System/UInt64/ToString/Program.cs | 4 + .../System/UInt64/ToString/Project.csproj | 8 + .../System/UInt64/ToString/tostring1.cs | 31 +- .../System/UInt64/ToString/tostring2.cs | 38 +- .../System/UInt64/ToString/tostring3.cs | 22 +- .../System/UInt64/ToString/tostring4.cs | 30 +- .../csharp/System/UInt64/TryParse/Program.cs | 2 + .../System/UInt64/TryParse/Project.csproj | 8 + .../System/UInt64/TryParse/tryparse1.cs | 60 +- .../System/UInt64/TryParse/tryparse2.cs | 96 +-- snippets/csharp/System/UIntPtr/Add/add1.cs | 22 +- .../System/UIntPtr/Subtract/subtract1.cs | 22 +- .../System/UIntPtr/op_Addition/Program.cs | 2 + .../System/UIntPtr/op_Addition/Project.csproj | 8 + .../UIntPtr/op_Addition/op_addition1.cs | 26 +- .../UIntPtr/op_Addition/op_subtraction1.cs | 26 +- .../Overview/withio.cs | 50 +- .../csharp/System/Uri/.ctor/Project.csproj | 9 + .../System/Uri/.ctor/nclurienhancements.cs | 48 +- snippets/csharp/System/Uri/.ctor/source.cs | 16 +- snippets/csharp/System/Uri/.ctor/source2.cs | 21 +- .../csharp/System/Uri/AbsolutePath/source.cs | 12 +- .../csharp/System/Uri/AbsoluteUri/source.cs | 12 +- .../csharp/System/Uri/Authority/source.cs | 22 +- .../csharp/System/Uri/CheckHostName/source.cs | 18 +- .../System/Uri/CheckSchemeName/uriexamples.cs | 171 +++-- snippets/csharp/System/Uri/Host/source.cs | 12 +- .../System/Uri/HostComparison/source.cs | 14 +- snippets/csharp/System/Uri/Overview/source.cs | 122 ++-- .../csharp/System/Uri/PathAndQuery/source.cs | 18 +- snippets/csharp/System/Uri/Port/source.cs | 12 +- snippets/csharp/System/Uri/Scheme/source.cs | 8 +- .../System/UriBuilder/.ctor/Project.csproj | 9 + .../csharp/System/UriBuilder/.ctor/source.cs | 16 +- .../csharp/System/UriBuilder/.ctor/source1.cs | 16 +- .../csharp/System/UriBuilder/.ctor/source2.cs | 16 +- .../csharp/System/UriBuilder/.ctor/source3.cs | 16 +- .../System/UriBuilder/Fragment/source.cs | 26 +- .../csharp/System/UriBuilder/Query/main.cs | 36 +- .../System/ValueType/Equals/Project.csproj | 8 + .../csharp/System/ValueType/Equals/source.cs | 43 +- .../System/ValueType/Overview/example1.cs | 154 +++-- .../System/ValueType/ToString/ToString2.cs | 29 +- snippets/csharp/System/Version/.ctor/rev.cs | 24 +- .../Version/Overview/GettingVersions1.cs | 1 - .../System/Version/Overview/comparisons1.cs | 46 +- .../System/Version/Overview/comparisons2.cs | 31 +- .../System/Version/Overview/currentapp.cs | 16 +- .../System/Version/Overview/currentassem.cs | 16 +- .../System/Version/Overview/example1.cs | 19 +- .../csharp/System/Version/Parse/parse1.cs | 103 +-- .../System/Version/TryParse/tryparse1.cs | 69 +- .../System/WeakReference/Overview/program.cs | 50 +- 101 files changed, 2676 insertions(+), 2578 deletions(-) create mode 100644 snippets/csharp/System/UInt16/Parse/Program.cs create mode 100644 snippets/csharp/System/UInt16/Parse/Project.csproj create mode 100644 snippets/csharp/System/UInt16/ToString/Program.cs create mode 100644 snippets/csharp/System/UInt16/ToString/Project.csproj create mode 100644 snippets/csharp/System/UInt16/TryParse/Program.cs create mode 100644 snippets/csharp/System/UInt16/TryParse/Project.csproj create mode 100644 snippets/csharp/System/UInt32/Parse/Program.cs create mode 100644 snippets/csharp/System/UInt32/Parse/Project.csproj create mode 100644 snippets/csharp/System/UInt32/ToString/Program.cs create mode 100644 snippets/csharp/System/UInt32/ToString/Project.csproj create mode 100644 snippets/csharp/System/UInt64/Equals/Program.cs create mode 100644 snippets/csharp/System/UInt64/Equals/Project.csproj create mode 100644 snippets/csharp/System/UInt64/Parse/Program.cs create mode 100644 snippets/csharp/System/UInt64/Parse/Project.csproj create mode 100644 snippets/csharp/System/UInt64/ToString/Program.cs create mode 100644 snippets/csharp/System/UInt64/ToString/Project.csproj create mode 100644 snippets/csharp/System/UInt64/TryParse/Program.cs create mode 100644 snippets/csharp/System/UInt64/TryParse/Project.csproj create mode 100644 snippets/csharp/System/UIntPtr/op_Addition/Program.cs create mode 100644 snippets/csharp/System/UIntPtr/op_Addition/Project.csproj create mode 100644 snippets/csharp/System/Uri/.ctor/Project.csproj create mode 100644 snippets/csharp/System/UriBuilder/.ctor/Project.csproj create mode 100644 snippets/csharp/System/ValueType/Equals/Project.csproj diff --git a/snippets/csharp/System/UInt16/CompareTo/source.cs b/snippets/csharp/System/UInt16/CompareTo/source.cs index d5e48a9c9b7..18aa0072d82 100644 --- a/snippets/csharp/System/UInt16/CompareTo/source.cs +++ b/snippets/csharp/System/UInt16/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt16 - /// and delegates most of the functionality - /// to the UInt16 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt16.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt16 + /// and delegates most of the functionality + /// to the UInt16 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ushort.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static ushort MinValue { - get { - return UInt16.MinValue; - } - } - - public static ushort MaxValue { - get { - return UInt16.MaxValue; - } - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static ushort MinValue => ushort.MinValue; + + public static ushort MaxValue => ushort.MaxValue; + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt16.Parse(s); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = ushort.Parse(s); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt16.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = ushort.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt16.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = ushort.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt16.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt16.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ushort m_value; - - public ushort Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ushort.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ushort.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ushort m_value; + + public ushort Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt16/Equals/equalsoverl.cs b/snippets/csharp/System/UInt16/Equals/equalsoverl.cs index b14ee0a95c1..6cb59e8a592 100644 --- a/snippets/csharp/System/UInt16/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt16/Equals/equalsoverl.cs @@ -3,42 +3,36 @@ public class Example { - static ushort value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); - - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); - - int int1 = 112; - Console.WriteLine("value = int1: {0,19}", value.Equals(int1)); - TestObjectForEquality(int1); - - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); - - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); - - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } - - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + static ushort value = 112; + + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); + + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); + + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),19}"); + TestObjectForEquality(int1); + + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); + + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); + + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt16/Equals/uint16_equals.cs b/snippets/csharp/System/UInt16/Equals/uint16_equals.cs index 491153d04f5..7fc6e0c14b2 100644 --- a/snippets/csharp/System/UInt16/Equals/uint16_equals.cs +++ b/snippets/csharp/System/UInt16/Equals/uint16_equals.cs @@ -15,8 +15,8 @@ public static void MyMethod() try { // - UInt16 myVariable1 = 10; - UInt16 myVariable2 = 10; + ushort myVariable1 = 10; + ushort myVariable2 = 10; //Display the declaring type. Console.WriteLine("\nType of 'myVariable1' is '{0}' and" + @@ -36,7 +36,7 @@ public static void MyMethod() } catch (Exception e) { - Console.WriteLine("Exception :{0}", e.Message); + Console.WriteLine($"Exception :{e.Message}"); } } } diff --git a/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs b/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs index 2a8b2056e75..07f7049d003 100644 --- a/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs +++ b/snippets/csharp/System/UInt16/MaxValue/MaxValue.cs @@ -2,21 +2,21 @@ public class Class1 { - public static void Main() - { - // - int integerValue = 1216; - ushort uIntegerValue; - - if (integerValue >= ushort.MinValue & integerValue <= ushort.MaxValue) - { - uIntegerValue = (ushort) integerValue; - Console.WriteLine(uIntegerValue); - } - else - { - Console.WriteLine("Unable to convert {0} to a UInt16t.", integerValue); - } - // - } + public static void Main() + { + // + int integerValue = 1216; + ushort uIntegerValue; + + if (integerValue >= ushort.MinValue && integerValue <= ushort.MaxValue) + { + uIntegerValue = (ushort)integerValue; + Console.WriteLine(uIntegerValue); + } + else + { + Console.WriteLine($"Unable to convert {integerValue} to a UInt16."); + } + // + } } diff --git a/snippets/csharp/System/UInt16/Parse/Program.cs b/snippets/csharp/System/UInt16/Parse/Program.cs new file mode 100644 index 00000000000..48b8ef24291 --- /dev/null +++ b/snippets/csharp/System/UInt16/Parse/Program.cs @@ -0,0 +1,4 @@ +UInt16ParseExample2.Run(); +UInt16ParseExample3.Run(); +UInt16ParseExample4.Run(); +UInt16ParseExample5.Run(); diff --git a/snippets/csharp/System/UInt16/Parse/Project.csproj b/snippets/csharp/System/UInt16/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/Parse/parseex2.cs b/snippets/csharp/System/UInt16/Parse/parseex2.cs index 8f62ab5df7c..1b570b10a8a 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex2.cs @@ -2,34 +2,36 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample2 { - public static void Main() - { - string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles = { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + public static void Run() + { + string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }; + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - ushort number = UInt16.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) + { + try + { + ushort number = ushort.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example display the following output: // Attempting to convert ' 214 ': @@ -38,56 +40,56 @@ public static void Main() // Integer, AllowTrailingSign: 214 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 1241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 214 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +214 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 214 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '2153.0': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 2153 -// +// // Attempting to convert '1e03': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 1000 -// +// // Attempting to convert '1300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format diff --git a/snippets/csharp/System/UInt16/Parse/parseex3.cs b/snippets/csharp/System/UInt16/Parse/parseex3.cs index ec51129ab1d..0e3f0e06292 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex3.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex3.cs @@ -2,37 +2,40 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample3 { - public static void Main() - { - // Define a custom culture that uses "++" as a positive sign. - CultureInfo ci = new CultureInfo(""); - ci.NumberFormat.PositiveSign = "++"; - // Create an array of cultures. - CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture }; - // Create an array of strings to parse. - string[] values = { "++1403", "-0", "+0", "+16034", - Int16.MinValue.ToString(), "14.0", "18012" }; - // Parse the strings using each culture. - foreach (CultureInfo culture in cultures) - { - Console.WriteLine("Parsing with the '{0}' culture.", culture.Name); - foreach (string value in values) - { - try { - ushort number = UInt16.Parse(value, culture); - Console.WriteLine(" Converted '{0}' to {1}.", value, number); + public static void Run() + { + // Define a custom culture that uses "++" as a positive sign. + CultureInfo ci = new(""); + ci.NumberFormat.PositiveSign = "++"; + // Create an array of cultures. + CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture }; + // Create an array of strings to parse. + string[] values = { "++1403", "-0", "+0", "+16034", + short.MinValue.ToString(), "14.0", "18012" }; + // Parse the strings using each culture. + foreach (CultureInfo culture in cultures) + { + Console.WriteLine($"Parsing with the '{culture.Name}' culture."); + foreach (string value in values) + { + try + { + ushort number = ushort.Parse(value, culture); + Console.WriteLine($" Converted '{value}' to {number}."); + } + catch (FormatException) + { + Console.WriteLine($" The format of '{value}' is invalid."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is outside the range of a UInt16 value."); + } } - catch (FormatException) { - Console.WriteLine(" The format of '{0}' is invalid.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value); - } - } - } - } + } + } } // The example displays the following output: // Parsing with the culture. diff --git a/snippets/csharp/System/UInt16/Parse/parseex4.cs b/snippets/csharp/System/UInt16/Parse/parseex4.cs index 84d41b378da..1ef871ac156 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class UInt16ParseExample4 { - public static void Main() - { - string[] cultureNames = { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00", + string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00", "-1032,00", "1045.1", "1045,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt16.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt16 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {ushort.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt16 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Parsing strings using the English (United States) culture diff --git a/snippets/csharp/System/UInt16/Parse/parseex5.cs b/snippets/csharp/System/UInt16/Parse/parseex5.cs index aff233c5bbf..889f620b5cb 100644 --- a/snippets/csharp/System/UInt16/Parse/parseex5.cs +++ b/snippets/csharp/System/UInt16/Parse/parseex5.cs @@ -1,29 +1,33 @@ // using System; -public class Example +public class UInt16ParseExample5 { - public static void Main() - { - string[] values = { "-0", "17", "-12", "185", "66012", "+0", + public static void Run() + { + string[] values = { "-0", "17", "-12", "185", "66012", "+0", "", null, "16.1", "28.0", "1,034" }; - foreach (string value in values) - { - try { - ushort number = UInt16.Parse(value); - Console.WriteLine("'{0}' --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("'{0}' --> Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("'{0}' --> OverflowException", value); - } - catch (ArgumentNullException) { - Console.WriteLine("'{0}' --> Null", value); - } - } - } + foreach (string value in values) + { + try + { + ushort number = ushort.Parse(value); + Console.WriteLine($"'{value}' --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"'{value}' --> Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"'{value}' --> OverflowException"); + } + catch (ArgumentNullException) + { + Console.WriteLine($"'{value}' --> Null"); + } + } + } } // The example displays the following output: // '-0' --> 0 diff --git a/snippets/csharp/System/UInt16/ToString/Program.cs b/snippets/csharp/System/UInt16/ToString/Program.cs new file mode 100644 index 00000000000..860773be472 --- /dev/null +++ b/snippets/csharp/System/UInt16/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt16ToStringExample1.Run(); +UInt16ToStringExample2.Run(); +UInt16ToStringExample3.Run(); +UInt16ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt16/ToString/Project.csproj b/snippets/csharp/System/UInt16/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/ToString/tostring1.cs b/snippets/csharp/System/UInt16/ToString/tostring1.cs index e81bfddcffc..6acfb024b97 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring1.cs @@ -1,22 +1,21 @@ // using System; -public class Example +public class UInt16ToStringExample1 { - public static void Main() - { - ushort value = 16324; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,12}", - format, value.ToString(format)); - } + public static void Run() + { + ushort value = 16324; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),12}"); + } } // The example displays the following output: // 16324 diff --git a/snippets/csharp/System/UInt16/ToString/tostring2.cs b/snippets/csharp/System/UInt16/ToString/tostring2.cs index 1075f803ea9..6324bf04a36 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt16ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - UInt16 value = 18924; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + ushort value = 18924; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt16/ToString/tostring3.cs b/snippets/csharp/System/UInt16/ToString/tostring3.cs index a8793f054b2..236354a6c8c 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt16ToStringExample3 { - public static void Main() - { - ushort value = 21708; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + ushort value = 21708; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 21708 diff --git a/snippets/csharp/System/UInt16/ToString/tostring4.cs b/snippets/csharp/System/UInt16/ToString/tostring4.cs index 8df6ae52e67..4c3a57d7e2a 100644 --- a/snippets/csharp/System/UInt16/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt16/ToString/tostring4.cs @@ -2,56 +2,54 @@ using System; using System.Globalization; -public class Example +public class UInt16ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("fr-FR"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - ushort value = 22042; - - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 16}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + ushort value = 22042; + + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),16}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 22042 // G format using fr-FR culture: 22042 // G format using es-ES culture: 22042 -// +// // C format using en-US culture: $22,042.00 // C format using fr-FR culture: 22 042,00 € // C format using es-ES culture: 22.042,00 € -// +// // D4 format using en-US culture: 22042 // D4 format using fr-FR culture: 22042 // D4 format using es-ES culture: 22042 -// +// // E2 format using en-US culture: 2.20E+004 // E2 format using fr-FR culture: 2,20E+004 // E2 format using es-ES culture: 2,20E+004 -// +// // F format using en-US culture: 22042.00 // F format using fr-FR culture: 22042,00 // F format using es-ES culture: 22042,00 -// +// // N format using en-US culture: 22,042.00 // N format using fr-FR culture: 22 042,00 // N format using es-ES culture: 22.042,00 -// +// // P format using en-US culture: 2,204,200.00 % // P format using fr-FR culture: 2 204 200,00 % // P format using es-ES culture: 2.204.200,00 % -// +// // X2 format using en-US culture: 561A // X2 format using fr-FR culture: 561A // X2 format using es-ES culture: 561A diff --git a/snippets/csharp/System/UInt16/TryParse/Program.cs b/snippets/csharp/System/UInt16/TryParse/Program.cs new file mode 100644 index 00000000000..1958e43db86 --- /dev/null +++ b/snippets/csharp/System/UInt16/TryParse/Program.cs @@ -0,0 +1,3 @@ +UInt16TryParseStylesExample.Run(); +UInt32TryParseBasicExample.Run(); +UInt32TryParseStylesExample.Run(); diff --git a/snippets/csharp/System/UInt16/TryParse/Project.csproj b/snippets/csharp/System/UInt16/TryParse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt16/TryParse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse11.cs b/snippets/csharp/System/UInt16/TryParse/tryparse11.cs index 24a2fa998b5..c068b5d4c35 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse11.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse11.cs @@ -1,36 +1,36 @@ using System; -public class Example +public class UInt32TryParseBasicExample { - public static void Main() - { - // - string[] numericStrings = { "1293.8", "+1671.7", "28347.", - " 33113684 ", "(0)", "-0", "-1", - "+1293617", "18-", "119870", "31,024", + public static void Run() + { + // + string[] numericStrings = { "1293.8", "+1671.7", "28347.", + " 33113684 ", "(0)", "-0", "-1", + "+1293617", "18-", "119870", "31,024", " 3127094 ", "00700000" }; - uint number; - foreach (string numericString in numericStrings) - { - if (UInt32.TryParse(numericString, out number)) - Console.WriteLine("Converted '{0}' to {1}.", numericString, number); - else - Console.WriteLine("Cannot convert '{0}' to a UInt32.", numericString); - } - // The example displays the following output: - // Cannot convert '1293.8' to a UInt32. - // Cannot convert '+1671.7' to a UInt32. - // Cannot convert '28347.' to a UInt32. - // Converted ' 33113684 ' to 33113684. - // Cannot convert '(0)' to a UInt32. - // Converted '-0' to 0. - // Cannot convert '-1' to a UInt32. - // Converted '+1293617' to 1293617. - // Cannot convert '18-' to a UInt32. - // Converted '119870' to 119870. - // Cannot convert '31,024' to a UInt32. - // Converted ' 3127094 ' to 3127094. - // Converted '0070000' to 70000. - // - } + uint number; + foreach (string numericString in numericStrings) + { + if (uint.TryParse(numericString, out number)) + Console.WriteLine($"Converted '{numericString}' to {number}."); + else + Console.WriteLine($"Cannot convert '{numericString}' to a UInt32."); + } + // The example displays the following output: + // Cannot convert '1293.8' to a UInt32. + // Cannot convert '+1671.7' to a UInt32. + // Cannot convert '28347.' to a UInt32. + // Converted ' 33113684 ' to 33113684. + // Cannot convert '(0)' to a UInt32. + // Converted '-0' to 0. + // Cannot convert '-1' to a UInt32. + // Converted '+1293617' to 1293617. + // Cannot convert '18-' to a UInt32. + // Converted '119870' to 119870. + // Cannot convert '31,024' to a UInt32. + // Converted ' 3127094 ' to 3127094. + // Converted '0070000' to 70000. + // + } } diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse2.cs b/snippets/csharp/System/UInt16/TryParse/tryparse2.cs index d97093927b3..226fa126d16 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse2.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse2.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt16TryParseStylesExample { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "10603"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "2210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC8"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - ushort number; - bool result = UInt16.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "10603"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "2210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC8"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + ushort number; + bool result = ushort.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '10603' to 10603. diff --git a/snippets/csharp/System/UInt16/TryParse/tryparse21.cs b/snippets/csharp/System/UInt16/TryParse/tryparse21.cs index 8c55b83e78e..dec240c9d9c 100644 --- a/snippets/csharp/System/UInt16/TryParse/tryparse21.cs +++ b/snippets/csharp/System/UInt16/TryParse/tryparse21.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt32TryParseStylesExample { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "2106034"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103674.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "41792210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC86DA1"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - uint number; - bool result = UInt32.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "2106034"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103674.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "41792210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC86DA1"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + uint number; + bool result = uint.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '2106034' to 2106034. diff --git a/snippets/csharp/System/UInt32/CompareTo/source.cs b/snippets/csharp/System/UInt32/CompareTo/source.cs index 31f0f2ce977..e2496483bef 100644 --- a/snippets/csharp/System/UInt32/CompareTo/source.cs +++ b/snippets/csharp/System/UInt32/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt32 - /// and delegates most of the functionality - /// to the UInt32 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt32.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt32 + /// and delegates most of the functionality + /// to the UInt32 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = uint.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static uint MinValue { - get { - return UInt32.MinValue; - } - } - - public static uint MaxValue { - get { - return UInt32.MaxValue; - } - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static uint MinValue => uint.MinValue; + + public static uint MaxValue => uint.MaxValue; + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt32.Parse(s); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = uint.Parse(s); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt32.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = uint.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt32.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = uint.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt32.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt32.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected uint m_value; - - public uint Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = uint.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = uint.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected uint m_value; + + public uint Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt32/Equals/equalsoverl.cs b/snippets/csharp/System/UInt32/Equals/equalsoverl.cs index 53f0ee58e22..186405bfe27 100644 --- a/snippets/csharp/System/UInt32/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt32/Equals/equalsoverl.cs @@ -3,50 +3,44 @@ public class Example { - static uint value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + static uint value = 112; - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - long long1 = 112; - Console.WriteLine("value = long1: {0,18}", value.Equals(long1)); - TestObjectForEquality(long1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + long long1 = 112; + Console.WriteLine($"value = long1: {value.Equals(long1),18}"); + TestObjectForEquality(long1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); - ulong ulong1 = 112; - Console.WriteLine("value = ulong1: {0,18}", value.Equals(ulong1)); - TestObjectForEquality(ulong1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + ulong ulong1 = 112; + Console.WriteLine($"value = ulong1: {value.Equals(ulong1),18}"); + TestObjectForEquality(ulong1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt32/Equals/uint32_equals.cs b/snippets/csharp/System/UInt32/Equals/uint32_equals.cs index f5966b5ac63..6fe36d5cf47 100644 --- a/snippets/csharp/System/UInt32/Equals/uint32_equals.cs +++ b/snippets/csharp/System/UInt32/Equals/uint32_equals.cs @@ -9,32 +9,32 @@ of struct 'UInt32'. This compares an instance of 'UInt32' with the using System; class MyUInt32_Equals { - public static void Main() - { - try - { -// - UInt32 myVariable1 = 20; - UInt32 myVariable2 = 20; + public static void Main() + { + try + { + // + uint myVariable1 = 20; + uint myVariable2 = 20; // Display the declaring type. - Console.WriteLine("\nType of 'myVariable1' is '{0}' and"+ - " value is :{1}",myVariable1.GetType(), myVariable1); - Console.WriteLine("Type of 'myVariable2' is '{0}' and"+ - " value is :{1}",myVariable2.GetType(), myVariable2); + Console.WriteLine("\nType of 'myVariable1' is '{0}' and" + + " value is :{1}", myVariable1.GetType(), myVariable1); + Console.WriteLine("Type of 'myVariable2' is '{0}' and" + + " value is :{1}", myVariable2.GetType(), myVariable2); // Compare 'myVariable1' instance with 'myVariable2' Object. - if( myVariable1.Equals( myVariable2 ) ) - Console.WriteLine( "\nStructures 'myVariable1' and "+ - "'myVariable2' are equal"); + if (myVariable1.Equals(myVariable2)) + Console.WriteLine("\nStructures 'myVariable1' and " + + "'myVariable2' are equal"); else - Console.WriteLine( "\nStructures 'myVariable1' and "+ - "'myVariable2' are not equal"); -// - } - catch(Exception e) - { - Console.WriteLine("Exception :{0}", e.Message); - } - } + Console.WriteLine("\nStructures 'myVariable1' and " + + "'myVariable2' are not equal"); + // + } + catch (Exception e) + { + Console.WriteLine($"Exception :{e.Message}"); + } + } } diff --git a/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs b/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs index e468978f860..74a2b056a11 100644 --- a/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs +++ b/snippets/csharp/System/UInt32/MaxValue/MaxValue1.cs @@ -2,40 +2,36 @@ public class ULongRangeExample { - public static void Main() - { - // - long longValue = long.MaxValue / 2; - uint integerValue; - - if (longValue <= uint.MaxValue && - longValue >= uint.MinValue) - { - integerValue = (uint) longValue; - Console.WriteLine("Converted long integer value to {0:n0}.", - integerValue); - } - else - { - uint rangeLimit; - string relationship; - - if (longValue > uint.MaxValue) - { - rangeLimit = uint.MaxValue; - relationship = "greater"; - } - else - { - rangeLimit = uint.MinValue; - relationship = "less"; - } + public static void Main() + { + // + long longValue = long.MaxValue / 2; + uint integerValue; - Console.WriteLine("Conversion failure: {0:n0} is {1} than {2:n0}", - longValue, - relationship, - rangeLimit); - } - // - } + if (longValue <= uint.MaxValue && + longValue >= uint.MinValue) + { + integerValue = (uint)longValue; + Console.WriteLine($"Converted long integer value to {integerValue:n0}."); + } + else + { + uint rangeLimit; + string relationship; + + if (longValue > uint.MaxValue) + { + rangeLimit = uint.MaxValue; + relationship = "greater"; + } + else + { + rangeLimit = uint.MinValue; + relationship = "less"; + } + + Console.WriteLine($"Conversion failure: {longValue:n0} is {relationship} than {rangeLimit:n0}"); + } + // + } } diff --git a/snippets/csharp/System/UInt32/Parse/Program.cs b/snippets/csharp/System/UInt32/Parse/Program.cs new file mode 100644 index 00000000000..457da988a89 --- /dev/null +++ b/snippets/csharp/System/UInt32/Parse/Program.cs @@ -0,0 +1,3 @@ +ParseExample1.Run(); +ParseExample2.Run(); +ParseExample4.Run(); diff --git a/snippets/csharp/System/UInt32/Parse/Project.csproj b/snippets/csharp/System/UInt32/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt32/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt32/Parse/parse1.cs b/snippets/csharp/System/UInt32/Parse/parse1.cs index ec04e314312..faa339fdbac 100644 --- a/snippets/csharp/System/UInt32/Parse/parse1.cs +++ b/snippets/csharp/System/UInt32/Parse/parse1.cs @@ -1,39 +1,42 @@ using System; -public class Example +public class ParseExample1 { - public static void Main() - { - // - string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", - "0xFA1B", "163042", "-10", "2147483648", + public static void Run() + { + // + string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", + "0xFA1B", "163042", "-10", "2147483648", "14065839182", "16e07", "134985.0", "-12034" }; - foreach (string value in values) - { - try { - uint number = UInt32.Parse(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); - } - } - // The example displays the following output: - // +13230 --> 13230 - // -0 --> 0 - // 1,390,146: Bad Format - // $190,235,421,127: Bad Format - // 0xFA1B: Bad Format - // 163042 --> 163042 - // -10: Overflow - // 2147483648 --> 2147483648 - // 14065839182: Overflow - // 16e07: Bad Format - // 134985.0: Bad Format - // -12034: Overflow - // - } + foreach (string value in values) + { + try + { + uint number = uint.Parse(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"{value}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{value}: Overflow"); + } + } + // The example displays the following output: + // +13230 --> 13230 + // -0 --> 0 + // 1,390,146: Bad Format + // $190,235,421,127: Bad Format + // 0xFA1B: Bad Format + // 163042 --> 163042 + // -10: Overflow + // 2147483648 --> 2147483648 + // 14065839182: Overflow + // 16e07: Bad Format + // 134985.0: Bad Format + // -12034: Overflow + // + } } diff --git a/snippets/csharp/System/UInt32/Parse/parseex2.cs b/snippets/csharp/System/UInt32/Parse/parseex2.cs index 3879074fa19..7b0e9470ab5 100644 --- a/snippets/csharp/System/UInt32/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt32/Parse/parseex2.cs @@ -2,39 +2,41 @@ using System; using System.Globalization; -public class Example +public class ParseExample2 { - public static void Main() - { - string[] values= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", + public static void Run() + { + string[] values = { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", " +21499 ", "122153.00", "1e03ff", "91300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles= { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - uint number = UInt32.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); - } - catch (OverflowException) + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) { - Console.WriteLine(" {0}: Overflow", value); - } - } - Console.WriteLine(); - } - } + try + { + uint number = uint.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($" {value}: Overflow"); + } + } + Console.WriteLine(); + } + } } // The example displays the following output: // Attempting to convert ' 214309 ': @@ -43,60 +45,60 @@ public static void Main() // Integer, AllowTrailingSign: 214309 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064,181': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064181 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '10241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 10241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 21499 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '122153.00': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 122153 -// +// // Attempting to convert '1e03ff': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '91300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 913 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt32/Parse/parseex4.cs b/snippets/csharp/System/UInt32/Parse/parseex4.cs index b079e33ddef..43cc4a11b44 100644 --- a/snippets/csharp/System/UInt32/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt32/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class ParseExample4 { - public static void Main() - { - string[] cultureNames= { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", + string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", "-103214,00", "104561.1", "104561,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt32.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt32 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {uint.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt32 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Parsing strings using the English (United States) culture @@ -76,4 +76,4 @@ public static void Main() // '-103214,00' is out of range of the UInt32 type. // Unable to parse '104561.1'. // '104561,1' is out of range of the UInt32 type. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt32/ToString/Program.cs b/snippets/csharp/System/UInt32/ToString/Program.cs new file mode 100644 index 00000000000..7af5a190e4e --- /dev/null +++ b/snippets/csharp/System/UInt32/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt32ToStringExample1.Run(); +UInt32ToStringExample2.Run(); +UInt32ToStringExample3.Run(); +UInt32ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt32/ToString/Project.csproj b/snippets/csharp/System/UInt32/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt32/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt32/ToString/tostring1.cs b/snippets/csharp/System/UInt32/ToString/tostring1.cs index 0194e67d9af..61dc245107b 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring1.cs @@ -1,26 +1,25 @@ // using System; -public class Example +public class UInt32ToStringExample1 { - public static void Main() - { - uint value = 1632490; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,16}", - format, value.ToString(format)); - } + public static void Run() + { + uint value = 1632490; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),16}"); + } } // The example displays the following output: // 1632490 -// +// // G format specifier: 1632490 // C format specifier: $1,632,490.00 // D format specifier: 1632490 diff --git a/snippets/csharp/System/UInt32/ToString/tostring2.cs b/snippets/csharp/System/UInt32/ToString/tostring2.cs index b10fee2ce2d..4cc6a2e9891 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt32ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - uint value = 1870924; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + uint value = 1870924; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt32/ToString/tostring3.cs b/snippets/csharp/System/UInt32/ToString/tostring3.cs index 297d0a1b02e..00260898a00 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt32ToStringExample3 { - public static void Main() - { - uint value = 2179608; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + uint value = 2179608; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 2179608 diff --git a/snippets/csharp/System/UInt32/ToString/tostring4.cs b/snippets/csharp/System/UInt32/ToString/tostring4.cs index ffa9e04c388..0f522f30fb2 100644 --- a/snippets/csharp/System/UInt32/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt32/ToString/tostring4.cs @@ -2,56 +2,54 @@ using System; using System.Globalization; -public class Example +public class UInt32ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), - CultureInfo.CreateSpecificCulture("fr-FR"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - uint value = 2222402; - - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 18}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + uint value = 2222402; + + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),18}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 2222402 // G format using fr-FR culture: 2222402 // G format using es-ES culture: 2222402 -// +// // C format using en-US culture: $2,222,402.00 // C format using fr-FR culture: 2 222 402,00 € // C format using es-ES culture: 2.222.402,00 € -// +// // D4 format using en-US culture: 2222402 // D4 format using fr-FR culture: 2222402 // D4 format using es-ES culture: 2222402 -// +// // E2 format using en-US culture: 2.22E+006 // E2 format using fr-FR culture: 2,22E+006 // E2 format using es-ES culture: 2,22E+006 -// +// // F format using en-US culture: 2222402.00 // F format using fr-FR culture: 2222402,00 // F format using es-ES culture: 2222402,00 -// +// // N format using en-US culture: 2,222,402.00 // N format using fr-FR culture: 2 222 402,00 // N format using es-ES culture: 2.222.402,00 -// +// // P format using en-US culture: 222,240,200.00 % // P format using fr-FR culture: 222 240 200,00 % // P format using es-ES culture: 222.240.200,00 % -// +// // X2 format using en-US culture: 21E942 // X2 format using fr-FR culture: 21E942 // X2 format using es-ES culture: 21E942 diff --git a/snippets/csharp/System/UInt64/CompareTo/source.cs b/snippets/csharp/System/UInt64/CompareTo/source.cs index 068f462c181..52c992f0407 100644 --- a/snippets/csharp/System/UInt64/CompareTo/source.cs +++ b/snippets/csharp/System/UInt64/CompareTo/source.cs @@ -1,314 +1,314 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("G", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - - Console.ReadLine(); - } - } - // - /// - /// Temperature class stores the value as UInt64 - /// and delegates most of the functionality - /// to the UInt64 implementation. - /// - public class Temperature : IComparable, IFormattable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt64.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets +{ + class Launcher + { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Integer, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("G", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Integer, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("30'F", NumberStyles.Integer, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + + Console.ReadLine(); + } + } + // + /// + /// Temperature class stores the value as UInt64 + /// and delegates most of the functionality + /// to the UInt64 implementation. + /// + public class Temperature : IComparable, IFormattable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ulong.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static ulong MinValue { - get { - return UInt64.MinValue; - } - } - - public static ulong MaxValue { - get { - return UInt64.MaxValue; - } - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static ulong MinValue => ulong.MinValue; + + public static ulong MaxValue => ulong.MaxValue; + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable { - /// - /// IComparable.CompareTo implementation. - /// - public int CompareTo(object obj) { - if(obj is Temperature) { - Temperature temp = (Temperature) obj; - - return m_value.CompareTo(temp.m_value); - } - - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets3 +{ + // + public class Temperature : IComparable + { + /// + /// IComparable.CompareTo implementation. + /// + public int CompareTo(object obj) + { + if (obj is Temperature) + { + Temperature temp = (Temperature)obj; + + return m_value.CompareTo(temp.m_value); + } + + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - /// - /// IFormattable.ToString implementation. - /// - public string ToString(string format, IFormatProvider provider) { - if( format != null && format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + /// + /// IFormattable.ToString implementation. + /// + public string ToString(string format, IFormatProvider provider) + { + if (format != null && format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = UInt64.Parse(s); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = ulong.Parse(s); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = UInt64.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = ulong.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = UInt64.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = ulong.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - /// - /// Parses the temperature from a string in form - /// [ws][sign]digits['F|'C][ws] - /// - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = UInt64.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = UInt64.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected ulong m_value; - - public ulong Value { - get { - return m_value; - } - set { - m_value = value; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + /// + /// Parses the temperature from a string in form + /// [ws][sign]digits['F|'C][ws] + /// + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = ulong.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = ulong.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected ulong m_value; + + public ulong Value { + get => m_value; + set => m_value = value; + } + } + // } diff --git a/snippets/csharp/System/UInt64/Equals/Program.cs b/snippets/csharp/System/UInt64/Equals/Program.cs new file mode 100644 index 00000000000..3319f2f339f --- /dev/null +++ b/snippets/csharp/System/UInt64/Equals/Program.cs @@ -0,0 +1,3 @@ +UInt64EqualsObjectExample.Run(); +UInt64EqualsOverloadExample.Run(); +UInt64EqualsExample.Run(); diff --git a/snippets/csharp/System/UInt64/Equals/Project.csproj b/snippets/csharp/System/UInt64/Equals/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/Equals/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/Equals/equals1.cs b/snippets/csharp/System/UInt64/Equals/equals1.cs index d7efc60d198..6ba81b5abfb 100644 --- a/snippets/csharp/System/UInt64/Equals/equals1.cs +++ b/snippets/csharp/System/UInt64/Equals/equals1.cs @@ -1,23 +1,20 @@ // using System; -public class Example +public class UInt64EqualsObjectExample { - public static void Main() - { - object[] values = { (short) 10, (short) 20, 10, 20, + public static void Run() + { + object[] values = { (short) 10, (short) 20, 10, 20, 10L, 20L, 10D, 20D, (ushort) 10, (ushort) 20, 10U, 20U, 10ul, 20ul }; - UInt64 baseValue = 20; - String baseType = baseValue.GetType().Name; - - foreach (var value in values) - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", - baseValue, baseType, - value, value.GetType().Name, - baseValue.Equals(value)); - } + ulong baseValue = 20; + string baseType = baseValue.GetType().Name; + + foreach (object value in values) + Console.WriteLine($"{baseValue} ({baseType}) = {value} ({value.GetType().Name}): {baseValue.Equals(value)}"); + } } // The example displays the following output: // 20 (UInt64) = 10 (Int16): False @@ -34,4 +31,4 @@ public static void Main() // 20 (UInt64) = 20 (UInt32): False // 20 (UInt64) = 10 (UInt64): False // 20 (UInt64) = 20 (UInt64): True -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UInt64/Equals/equalsoverl.cs b/snippets/csharp/System/UInt64/Equals/equalsoverl.cs index 3ecff88cf30..99e4b7384d2 100644 --- a/snippets/csharp/System/UInt64/Equals/equalsoverl.cs +++ b/snippets/csharp/System/UInt64/Equals/equalsoverl.cs @@ -1,52 +1,46 @@ // using System; -public class Example +public class UInt64EqualsOverloadExample { - static ulong value = 112; - - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + static ulong value = 112; - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); + public static void Run() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - int int1 = 112; - Console.WriteLine("value = int1: {0,19}", value.Equals(int1)); - TestObjectForEquality(int1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),19}"); + TestObjectForEquality(int1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); - uint uint1 = 112; - Console.WriteLine("value = uint1: {0,18}", value.Equals(uint1)); - TestObjectForEquality(uint1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + uint uint1 = 112; + Console.WriteLine($"value = uint1: {value.Equals(uint1),18}"); + TestObjectForEquality(uint1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}"); + TestObjectForEquality(dbl1); + } + + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/UInt64/Equals/uint64_equals.cs b/snippets/csharp/System/UInt64/Equals/uint64_equals.cs index e98b47116d2..e303f5ef7bc 100644 --- a/snippets/csharp/System/UInt64/Equals/uint64_equals.cs +++ b/snippets/csharp/System/UInt64/Equals/uint64_equals.cs @@ -1,23 +1,20 @@ // using System; -class Example +class UInt64EqualsExample { - public static void Main() - { - UInt64 value1 = 50; - UInt64 value2 = 50; + public static void Run() + { + ulong value1 = 50; + ulong value2 = 50; - // Display the values. - Console.WriteLine("value1: Type: {0} Value: {1}", - value1.GetType().Name, value1); - Console.WriteLine("value2: Type: {0} Value: {1}", - value2.GetType().Name, value2); + // Display the values. + Console.WriteLine($"value1: Type: {value1.GetType().Name} Value: {value1}"); + Console.WriteLine($"value2: Type: {value2.GetType().Name} Value: {value2}"); // Compare the two values. - Console.WriteLine("value1 and value2 are equal: {0}", - value1.Equals(value2)); - } + Console.WriteLine($"value1 and value2 are equal: {value1.Equals(value2)}"); + } } // The example displays the following output: // value1: Type: UInt64 Value: 50 diff --git a/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs b/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs index 8b8e3045eb6..a08ada6029a 100644 --- a/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs +++ b/snippets/csharp/System/UInt64/MaxValue/MaxValue1.cs @@ -2,42 +2,39 @@ public class ULongRangeExample { - public static void Main() - { - // - double decimalValue = -1.5; - ulong integerValue; - - // Discard fractional portion of Double value - double decimalInteger = Math.Floor(decimalValue); + public static void Main() + { + // + double decimalValue = -1.5; + ulong integerValue; - if (decimalInteger <= ulong.MaxValue && - decimalInteger >= ulong.MinValue) - { - integerValue = (ulong) decimalValue; - Console.WriteLine("Converted {0} to {1}.", decimalValue, integerValue); - } - else - { - ulong rangeLimit; - string relationship; - - if (decimalInteger > ulong.MaxValue) - { - rangeLimit = ulong.MaxValue; - relationship = "greater"; - } - else - { - rangeLimit = ulong.MinValue; - relationship = "less"; - } + // Discard fractional portion of Double value + double decimalInteger = Math.Floor(decimalValue); - Console.WriteLine("Conversion failure: {0} is {1} than {2}.", - decimalInteger, - relationship, - rangeLimit); - } - // - } + if (decimalInteger <= ulong.MaxValue && + decimalInteger >= ulong.MinValue) + { + integerValue = (ulong)decimalValue; + Console.WriteLine($"Converted {decimalValue} to {integerValue}."); + } + else + { + ulong rangeLimit; + string relationship; + + if (decimalInteger > ulong.MaxValue) + { + rangeLimit = ulong.MaxValue; + relationship = "greater"; + } + else + { + rangeLimit = ulong.MinValue; + relationship = "less"; + } + + Console.WriteLine($"Conversion failure: {decimalInteger} is {relationship} than {rangeLimit}."); + } + // + } } diff --git a/snippets/csharp/System/UInt64/Parse/Program.cs b/snippets/csharp/System/UInt64/Parse/Program.cs new file mode 100644 index 00000000000..a463149ef55 --- /dev/null +++ b/snippets/csharp/System/UInt64/Parse/Program.cs @@ -0,0 +1,3 @@ +UInt64ParseExample1.Run(); +UInt64ParseExample2.Run(); +UInt64ParseExample4.Run(); diff --git a/snippets/csharp/System/UInt64/Parse/Project.csproj b/snippets/csharp/System/UInt64/Parse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/Parse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/Parse/parse1.cs b/snippets/csharp/System/UInt64/Parse/parse1.cs index 0b59d80938a..7633545766a 100644 --- a/snippets/csharp/System/UInt64/Parse/parse1.cs +++ b/snippets/csharp/System/UInt64/Parse/parse1.cs @@ -1,38 +1,41 @@ using System; -public class Example +public class UInt64ParseExample1 { - public static void Main() - { - // - string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", + public static void Run() + { + // + string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127", "0xFA1B", "163042", "-10", "14065839182", "16e07", "134985.0", "-12034" }; - foreach (string value in values) - { - try { - ulong number = UInt64.Parse(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); - } - catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); - } - } - // The example displays the following output: - // +13230 --> 13230 - // -0 --> 0 - // 1,390,146: Bad Format - // $190,235,421,127: Bad Format - // 0xFA1B: Bad Format - // 163042 --> 163042 - // -10: Overflow - // 14065839182 --> 14065839182 - // 16e07: Bad Format - // 134985.0: Bad Format - // -12034: Overflow - // - } + foreach (string value in values) + { + try + { + ulong number = ulong.Parse(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (FormatException) + { + Console.WriteLine($"{value}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($"{value}: Overflow"); + } + } + // The example displays the following output: + // +13230 --> 13230 + // -0 --> 0 + // 1,390,146: Bad Format + // $190,235,421,127: Bad Format + // 0xFA1B: Bad Format + // 163042 --> 163042 + // -10: Overflow + // 14065839182 --> 14065839182 + // 16e07: Bad Format + // 134985.0: Bad Format + // -12034: Overflow + // + } } diff --git a/snippets/csharp/System/UInt64/Parse/parseex2.cs b/snippets/csharp/System/UInt64/Parse/parseex2.cs index 3f704399295..dd8db283108 100644 --- a/snippets/csharp/System/UInt64/Parse/parseex2.cs +++ b/snippets/csharp/System/UInt64/Parse/parseex2.cs @@ -2,39 +2,41 @@ using System; using System.Globalization; -public class Example +public class UInt64ParseExample2 { - public static void Main() - { - string[] values= { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", + public static void Run() + { + string[] values = { " 214309 ", "1,064,181", "(0)", "10241+", " + 21499 ", " +21499 ", "122153.00", "1e03ff", "91300.0e-2" }; - NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; - NumberStyles[] styles= { NumberStyles.None, whitespace, - NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, - NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, + NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; + NumberStyles[] styles = { NumberStyles.None, whitespace, + NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace, + NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint }; - // Attempt to convert each number using each style combination. - foreach (string value in values) - { - Console.WriteLine("Attempting to convert '{0}':", value); - foreach (NumberStyles style in styles) - { - try { - ulong number = UInt64.Parse(value, style); - Console.WriteLine(" {0}: {1}", style, number); - } - catch (FormatException) { - Console.WriteLine(" {0}: Bad Format", style); - } - catch (OverflowException) + // Attempt to convert each number using each style combination. + foreach (string value in values) + { + Console.WriteLine($"Attempting to convert '{value}':"); + foreach (NumberStyles style in styles) { - Console.WriteLine(" {0}: Overflow", value); - } - } - Console.WriteLine(); - } - } + try + { + ulong number = ulong.Parse(value, style); + Console.WriteLine($" {style}: {number}"); + } + catch (FormatException) + { + Console.WriteLine($" {style}: Bad Format"); + } + catch (OverflowException) + { + Console.WriteLine($" {value}: Overflow"); + } + } + Console.WriteLine(); + } + } } // The example displays the following output: // Attempting to convert ' 214309 ': @@ -43,56 +45,56 @@ public static void Main() // Integer, AllowTrailingSign: 214309 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '1,064,181': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: 1064181 // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '(0)': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '10241+': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 10241 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' + 21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert ' +21499 ': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: 21499 // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '122153.00': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: 122153 -// +// // Attempting to convert '1e03ff': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format // Integer, AllowTrailingSign: Bad Format // AllowThousands, AllowCurrencySymbol: Bad Format // AllowDecimalPoint, AllowExponent: Bad Format -// +// // Attempting to convert '91300.0e-2': // None: Bad Format // AllowLeadingWhite, AllowTrailingWhite: Bad Format diff --git a/snippets/csharp/System/UInt64/Parse/parseex4.cs b/snippets/csharp/System/UInt64/Parse/parseex4.cs index aff85eb102b..caa5e31c30f 100644 --- a/snippets/csharp/System/UInt64/Parse/parseex4.cs +++ b/snippets/csharp/System/UInt64/Parse/parseex4.cs @@ -2,44 +2,44 @@ using System; using System.Globalization; -public class Example +public class UInt64ParseExample4 { - public static void Main() - { - string[] cultureNames= { "en-US", "fr-FR" }; - NumberStyles[] styles= { NumberStyles.Integer, + public static void Run() + { + string[] cultureNames = { "en-US", "fr-FR" }; + NumberStyles[] styles = { NumberStyles.Integer, NumberStyles.Integer | NumberStyles.AllowDecimalPoint }; - string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", + string[] values = { "170209", "+170209.0", "+170209,0", "-103214.00", "-103214,00", "104561.1", "104561,1" }; - - // Parse strings using each culture - foreach (string cultureName in cultureNames) - { - CultureInfo ci = new CultureInfo(cultureName); - Console.WriteLine("Parsing strings using the {0} culture", - ci.DisplayName); - // Use each style. - foreach (NumberStyles style in styles) - { - Console.WriteLine(" Style: {0}", style.ToString()); - // Parse each numeric string. - foreach (string value in values) + + // Parse strings using each culture + foreach (string cultureName in cultureNames) + { + CultureInfo ci = new(cultureName); + Console.WriteLine($"Parsing strings using the {ci.DisplayName} culture"); + // Use each style. + foreach (NumberStyles style in styles) { - try { - Console.WriteLine(" Converted '{0}' to {1}.", value, - UInt64.Parse(value, style, ci)); - } - catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'.", value); - } - catch (OverflowException) { - Console.WriteLine(" '{0}' is out of range of the UInt64 type.", - value); - } + Console.WriteLine($" Style: {style.ToString()}"); + // Parse each numeric string. + foreach (string value in values) + { + try + { + Console.WriteLine($" Converted '{value}' to {ulong.Parse(value, style, ci)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to parse '{value}'."); + } + catch (OverflowException) + { + Console.WriteLine($" '{value}' is out of range of the UInt64 type."); + } + } } - } - } - } + } + } } // The example displays the following output: // Style: Integer diff --git a/snippets/csharp/System/UInt64/ToString/Program.cs b/snippets/csharp/System/UInt64/ToString/Program.cs new file mode 100644 index 00000000000..442730bd75e --- /dev/null +++ b/snippets/csharp/System/UInt64/ToString/Program.cs @@ -0,0 +1,4 @@ +UInt64ToStringExample1.Run(); +UInt64ToStringExample2.Run(); +UInt64ToStringExample3.Run(); +UInt64ToStringExample4.Run(); diff --git a/snippets/csharp/System/UInt64/ToString/Project.csproj b/snippets/csharp/System/UInt64/ToString/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/ToString/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/ToString/tostring1.cs b/snippets/csharp/System/UInt64/ToString/tostring1.cs index a5f35b12be5..9e02244ebcf 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring1.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring1.cs @@ -1,26 +1,25 @@ // using System; -public class Example +public class UInt64ToStringExample1 { - public static void Main() - { - ulong value = 163249057; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); - Console.WriteLine(); - - // Define an array of format specifiers. - string[] formats = { "G", "C", "D", "F", "N", "X" }; - // Display value using the standard format specifiers. - foreach (string format in formats) - Console.WriteLine("{0} format specifier: {1,16}", - format, value.ToString(format)); - } + public static void Run() + { + ulong value = 163249057; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); + Console.WriteLine(); + + // Define an array of format specifiers. + string[] formats = { "G", "C", "D", "F", "N", "X" }; + // Display value using the standard format specifiers. + foreach (string format in formats) + Console.WriteLine($"{format} format specifier: {value.ToString(format),16}"); + } } // The example displays the following output: // 163249057 -// +// // G format specifier: 163249057 // C format specifier: $163,249,057.00 // D format specifier: 163249057 diff --git a/snippets/csharp/System/UInt64/ToString/tostring2.cs b/snippets/csharp/System/UInt64/ToString/tostring2.cs index 9aea3c57d79..53daa1d01eb 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring2.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring2.cs @@ -2,28 +2,26 @@ using System; using System.Globalization; -public class Example +public class UInt64ToStringExample2 { - public static void Main() - { - // Define an array of CultureInfo objects. - CultureInfo[] ci = { new CultureInfo("en-US"), - new CultureInfo("fr-FR"), - CultureInfo.InvariantCulture }; - ulong value = 18709243; - Console.WriteLine(" {0,12} {1,12} {2,12}", - GetName(ci[0]), GetName(ci[1]), GetName(ci[2])); - Console.WriteLine(" {0,12} {1,12} {2,12}", - value.ToString(ci[0]), value.ToString(ci[1]), value.ToString(ci[2])); - } + public static void Run() + { + // Define an array of CultureInfo objects. + CultureInfo[] ci = { new CultureInfo("en-US"), + new CultureInfo("fr-FR"), + CultureInfo.InvariantCulture }; + ulong value = 18709243; + Console.WriteLine($" {GetName(ci[0]),12} {GetName(ci[1]),12} {GetName(ci[2]),12}"); + Console.WriteLine($" {value.ToString(ci[0]),12} {value.ToString(ci[1]),12} {value.ToString(ci[2]),12}"); + } - private static string GetName(CultureInfo ci) - { - if (ci.Equals(CultureInfo.InvariantCulture)) - return "Invariant"; - else - return ci.Name; - } + private static string GetName(CultureInfo ci) + { + if (ci.Equals(CultureInfo.InvariantCulture)) + return "Invariant"; + else + return ci.Name; + } } // The example displays the following output: // en-US fr-FR Invariant diff --git a/snippets/csharp/System/UInt64/ToString/tostring3.cs b/snippets/csharp/System/UInt64/ToString/tostring3.cs index ceea836f284..62fcfd81044 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring3.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring3.cs @@ -1,19 +1,19 @@ // using System; -using System.Globalization; -public class Example + +public class UInt64ToStringExample3 { - public static void Main() - { - ulong value = 217960834; - string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", - "N", "P", "X", "000000.0", "#.0", + public static void Run() + { + ulong value = 217960834; + string[] specifiers = { "G", "C", "D3", "E2", "e3", "F", + "N", "P", "X", "000000.0", "#.0", "00000000;(0);**Zero**" }; - - foreach (string specifier in specifiers) - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - } + + foreach (string specifier in specifiers) + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + } } // The example displays the following output: // G: 217960834 diff --git a/snippets/csharp/System/UInt64/ToString/tostring4.cs b/snippets/csharp/System/UInt64/ToString/tostring4.cs index 2de875b7f2f..c625d786229 100644 --- a/snippets/csharp/System/UInt64/ToString/tostring4.cs +++ b/snippets/csharp/System/UInt64/ToString/tostring4.cs @@ -2,26 +2,24 @@ using System; using System.Globalization; -public class Example +public class UInt64ToStringExample4 { - public static void Main() - { - // Define cultures whose formatting conventions are to be used. - CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), + public static void Run() + { + // Define cultures whose formatting conventions are to be used. + CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"), CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("es-ES") }; - string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"}; - ulong value = 22224021; + string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" }; + ulong value = 22224021; - foreach (string specifier in specifiers) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0,2} format using {1} culture: {2, 18}", - specifier, culture.Name, - value.ToString(specifier, culture)); - Console.WriteLine(); - } - } + foreach (string specifier in specifiers) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {value.ToString(specifier, culture),18}"); + Console.WriteLine(); + } + } } // The example displays the following output: // G format using en-US culture: 22224021 diff --git a/snippets/csharp/System/UInt64/TryParse/Program.cs b/snippets/csharp/System/UInt64/TryParse/Program.cs new file mode 100644 index 00000000000..afaba9c2d4b --- /dev/null +++ b/snippets/csharp/System/UInt64/TryParse/Program.cs @@ -0,0 +1,2 @@ +UInt64TryParseExample1.Run(); +UInt64TryParseExample2.Run(); diff --git a/snippets/csharp/System/UInt64/TryParse/Project.csproj b/snippets/csharp/System/UInt64/TryParse/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UInt64/TryParse/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UInt64/TryParse/tryparse1.cs b/snippets/csharp/System/UInt64/TryParse/tryparse1.cs index a50c2947877..3225f876e7c 100644 --- a/snippets/csharp/System/UInt64/TryParse/tryparse1.cs +++ b/snippets/csharp/System/UInt64/TryParse/tryparse1.cs @@ -1,35 +1,35 @@ using System; -public class Example +public class UInt64TryParseExample1 { - public static void Main() - { - // - string[] numericStrings = { "1293.8", "+1671.7", "28347.", - " 33113684 ", "(0)", "-0", "+1293617", - "18-", "119870", "31,024", " 3127094 ", + public static void Run() + { + // + string[] numericStrings = { "1293.8", "+1671.7", "28347.", + " 33113684 ", "(0)", "-0", "+1293617", + "18-", "119870", "31,024", " 3127094 ", "00700000" }; - ulong number; - foreach (string numericString in numericStrings) - { - if (UInt64.TryParse(numericString, out number)) - Console.WriteLine("Converted '{0}' to {1}.", numericString, number); - else - Console.WriteLine("Cannot convert '{0}' to a UInt64.", numericString); - } - // The example displays the following output: - // Cannot convert '1293.8' to a UInt64. - // Cannot convert '+1671.7' to a UInt64. - // Cannot convert '28347.' to a UInt64. - // Converted ' 33113684 ' to 33113684. - // Cannot convert '(0)' to a UInt64. - // Converted '-0' to 0. - // Converted '+1293617' to 1293617. - // Cannot convert '18-' to a UInt64. - // Converted '119870' to 119870. - // Cannot convert '31,024' to a UInt64. - // Converted ' 3127094 ' to 3127094. - // Converted '0070000' to 70000. - // - } + ulong number; + foreach (string numericString in numericStrings) + { + if (ulong.TryParse(numericString, out number)) + Console.WriteLine($"Converted '{numericString}' to {number}."); + else + Console.WriteLine($"Cannot convert '{numericString}' to a UInt64."); + } + // The example displays the following output: + // Cannot convert '1293.8' to a UInt64. + // Cannot convert '+1671.7' to a UInt64. + // Cannot convert '28347.' to a UInt64. + // Converted ' 33113684 ' to 33113684. + // Cannot convert '(0)' to a UInt64. + // Converted '-0' to 0. + // Converted '+1293617' to 1293617. + // Cannot convert '18-' to a UInt64. + // Converted '119870' to 119870. + // Cannot convert '31,024' to a UInt64. + // Converted ' 3127094 ' to 3127094. + // Converted '0070000' to 70000. + // + } } diff --git a/snippets/csharp/System/UInt64/TryParse/tryparse2.cs b/snippets/csharp/System/UInt64/TryParse/tryparse2.cs index 895259d975f..0a7e8271dcd 100644 --- a/snippets/csharp/System/UInt64/TryParse/tryparse2.cs +++ b/snippets/csharp/System/UInt64/TryParse/tryparse2.cs @@ -2,56 +2,56 @@ using System; using System.Globalization; -public class Example +public class UInt64TryParseExample2 { - public static void Main() - { - string numericString; - NumberStyles styles; - - numericString = "2106034"; - styles = NumberStyles.Integer; - CallTryParse(numericString, styles); - - numericString = "-10603"; - styles = NumberStyles.None; - CallTryParse(numericString, styles); - - numericString = "29103674.00"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); - - numericString = "10345.72"; - styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; - CallTryParse(numericString, styles); + public static void Run() + { + string numericString; + NumberStyles styles; - numericString = "41792210E-01"; - styles = NumberStyles.Integer | NumberStyles.AllowExponent; - CallTryParse(numericString, styles); - - numericString = "9112E-01"; - CallTryParse(numericString, styles); - - numericString = "312E01"; - CallTryParse(numericString, styles); - - numericString = "FFC86DA1"; - CallTryParse(numericString, NumberStyles.HexNumber); - - numericString = "0x8F8C"; - CallTryParse(numericString, NumberStyles.HexNumber); - } - - private static void CallTryParse(string stringToConvert, NumberStyles styles) - { - ulong number; - bool result = UInt64.TryParse(stringToConvert, styles, - CultureInfo.InvariantCulture, out number); - if (result) - Console.WriteLine($"Converted '{stringToConvert}' to {number}."); - else - Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); - } + numericString = "2106034"; + styles = NumberStyles.Integer; + CallTryParse(numericString, styles); + + numericString = "-10603"; + styles = NumberStyles.None; + CallTryParse(numericString, styles); + + numericString = "29103674.00"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "10345.72"; + styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint; + CallTryParse(numericString, styles); + + numericString = "41792210E-01"; + styles = NumberStyles.Integer | NumberStyles.AllowExponent; + CallTryParse(numericString, styles); + + numericString = "9112E-01"; + CallTryParse(numericString, styles); + + numericString = "312E01"; + CallTryParse(numericString, styles); + + numericString = "FFC86DA1"; + CallTryParse(numericString, NumberStyles.HexNumber); + + numericString = "0x8F8C"; + CallTryParse(numericString, NumberStyles.HexNumber); + } + + private static void CallTryParse(string stringToConvert, NumberStyles styles) + { + ulong number; + bool result = ulong.TryParse(stringToConvert, styles, + CultureInfo.InvariantCulture, out number); + if (result) + Console.WriteLine($"Converted '{stringToConvert}' to {number}."); + else + Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed."); + } } // The example displays the following output: // Converted '2106034' to 2106034. diff --git a/snippets/csharp/System/UIntPtr/Add/add1.cs b/snippets/csharp/System/UIntPtr/Add/add1.cs index dc0af559267..141d744bd1b 100644 --- a/snippets/csharp/System/UIntPtr/Add/add1.cs +++ b/snippets/csharp/System/UIntPtr/Add/add1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - UIntPtr ptr = (UIntPtr) arr[0]; - for (int ctr = 0; ctr < arr.Length; ctr++) - { - UIntPtr newPtr = UIntPtr.Add(ptr, ctr); - Console.Write("{0} ", newPtr); - } - } + public static void Main() + { + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[0]; + for (int ctr = 0; ctr < arr.Length; ctr++) + { + UIntPtr newPtr = UIntPtr.Add(ptr, ctr); + Console.Write($"{newPtr} "); + } + } } // The example displays the following output: // 1 2 3 4 5 6 7 8 9 10 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs b/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs index 30d39b365d2..2811102f504 100644 --- a/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs +++ b/snippets/csharp/System/UIntPtr/Subtract/subtract1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - UIntPtr ptr = (UIntPtr) arr[arr.GetUpperBound(0)]; - for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) - { - UIntPtr newPtr = UIntPtr.Subtract(ptr, ctr); - Console.Write("{0} ", newPtr); - } - } + public static void Main() + { + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[arr.GetUpperBound(0)]; + for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) + { + UIntPtr newPtr = UIntPtr.Subtract(ptr, ctr); + Console.Write($"{newPtr} "); + } + } } // The example displays the following output: // 10 9 8 7 6 5 4 3 2 1 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/UIntPtr/op_Addition/Program.cs b/snippets/csharp/System/UIntPtr/op_Addition/Program.cs new file mode 100644 index 00000000000..5114f22057c --- /dev/null +++ b/snippets/csharp/System/UIntPtr/op_Addition/Program.cs @@ -0,0 +1,2 @@ +UIntPtrAdditionExample.Run(); +UIntPtrSubtractionExample.Run(); diff --git a/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj b/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System/UIntPtr/op_Addition/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs b/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs index 8d5ff254ac6..50714f4911b 100644 --- a/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs +++ b/snippets/csharp/System/UIntPtr/op_Addition/op_addition1.cs @@ -1,17 +1,17 @@ using System; -public class Example +public class UIntPtrAdditionExample { - public static void Main() - { - // - int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - UIntPtr ptr = (UIntPtr) arr[0]; - for (int ctr = 0; ctr < arr.Length; ctr++) - { - UIntPtr newPtr = ptr + ctr; - Console.WriteLine(newPtr); - } - // - } + public static void Run() + { + // + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[0]; + for (int ctr = 0; ctr < arr.Length; ctr++) + { + UIntPtr newPtr = ptr + (nuint)ctr; + Console.WriteLine(newPtr); + } + // + } } diff --git a/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs b/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs index 22a4c7a5adf..3bfd2eadd0d 100644 --- a/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs +++ b/snippets/csharp/System/UIntPtr/op_Addition/op_subtraction1.cs @@ -1,17 +1,17 @@ using System; -public class Example +public class UIntPtrSubtractionExample { - public static void Main() - { - // - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - UIntPtr ptr = (UIntPtr) arr[arr.GetUpperBound(0)]; - for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) - { - UIntPtr newPtr = ptr - ctr; - Console.Write("{0} ", newPtr); - } - // - } + public static void Run() + { + // + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + UIntPtr ptr = (UIntPtr)arr[arr.GetUpperBound(0)]; + for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++) + { + UIntPtr newPtr = ptr - (nuint)ctr; + Console.Write($"{newPtr} "); + } + // + } } diff --git a/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs b/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs index 4b5b6eca616..8f2e06f9164 100644 --- a/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs +++ b/snippets/csharp/System/UnauthorizedAccessException/Overview/withio.cs @@ -4,30 +4,34 @@ public class Example { - public static void Main() - { - string filePath = @".\ROFile.txt"; - if (!File.Exists(filePath)) - File.Create(filePath); - // Keep existing attributes, and set ReadOnly attribute. - File.SetAttributes(filePath, - (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly); + public static void Main() + { + string filePath = @".\ROFile.txt"; + if (!File.Exists(filePath)) + File.Create(filePath).Dispose(); - StreamWriter sw = null; - try { - sw = new StreamWriter(filePath); - sw.Write("Test"); - } - catch (UnauthorizedAccessException) { - FileAttributes attr = (new FileInfo(filePath)).Attributes; - Console.Write("UnAuthorizedAccessException: Unable to access file. "); - if ((attr & FileAttributes.ReadOnly) > 0) - Console.Write("The file is read-only."); - } - finally { - if (sw != null) sw.Close(); - } - } + // Keep existing attributes, and set ReadOnly attribute. + File.SetAttributes(filePath, + (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly); + + StreamWriter sw = null; + try + { + sw = new(filePath); + sw.Write("Test"); + } + catch (UnauthorizedAccessException) + { + FileAttributes attr = (new FileInfo(filePath)).Attributes; + Console.Write("UnAuthorizedAccessException: Unable to access file. "); + if ((attr & FileAttributes.ReadOnly) > 0) + Console.Write("The file is read-only."); + } + finally + { + if (sw != null) sw.Close(); + } + } } // The example displays the following output: // UnAuthorizedAccessException: Unable to access file. The file is read-only. diff --git a/snippets/csharp/System/Uri/.ctor/Project.csproj b/snippets/csharp/System/Uri/.ctor/Project.csproj new file mode 100644 index 00000000000..4a6d98d26b7 --- /dev/null +++ b/snippets/csharp/System/Uri/.ctor/Project.csproj @@ -0,0 +1,9 @@ + + + + Exe + net10.0-windows + true + + + diff --git a/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs b/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs index a11001351b8..0b99914c193 100644 --- a/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs +++ b/snippets/csharp/System/Uri/.ctor/nclurienhancements.cs @@ -1,7 +1,7 @@ using System; -using System.Net; -using System.Text; -using System.Threading; + + + namespace Example { @@ -36,19 +36,23 @@ private static void SampleTryCreate() string addressString = "catalog/shownew.htm?date=today"; // Parse the string and create a new Uri instance, if possible. Uri result = null; - if (Uri.TryCreate(addressString, UriKind.RelativeOrAbsolute, out result)) { + if (Uri.TryCreate(addressString, UriKind.RelativeOrAbsolute, out result)) + { // The call was successful. Write the URI address to the console. Console.Write(result.ToString()); // Check whether new Uri instance is absolute or relative. - if (result.IsAbsoluteUri) { + if (result.IsAbsoluteUri) + { Console.WriteLine(" is an absolute Uri."); } - else { + else + { Console.WriteLine(" is a relative Uri."); } } - else { - // Let the user know that the call failed. + else + { + // Let the user know that the call failed. Console.WriteLine("addressString could not be parsed as a URI " + "address."); } @@ -60,18 +64,18 @@ private static void SampleConstructor() { // // Create an absolute Uri from a string. - Uri absoluteUri = new Uri("http://www.contoso.com/"); + Uri absoluteUri = new("http://www.contoso.com/"); // Create a relative Uri from a string. allowRelative = true to allow for // creating a relative Uri. - Uri relativeUri = new Uri("/catalog/shownew.htm?date=today", UriKind.Relative); + Uri relativeUri = new("/catalog/shownew.htm?date=today", UriKind.Relative); // Check whether the new Uri is absolute or relative. if (!relativeUri.IsAbsoluteUri) - Console.WriteLine("{0} is a relative Uri.", relativeUri); + Console.WriteLine($"{relativeUri} is a relative Uri."); // Create a new Uri from an absolute Uri and a relative Uri. - Uri combinedUri = new Uri(absoluteUri, relativeUri); + Uri combinedUri = new(absoluteUri, relativeUri); Console.WriteLine(combinedUri.AbsoluteUri); // } @@ -81,7 +85,7 @@ private static void SampleOriginalString() { // // Create a new Uri from a string address. - Uri uriAddress = new Uri("HTTP://www.ConToso.com:80//thick%20and%20thin.htm"); + Uri uriAddress = new("HTTP://www.ConToso.com:80//thick%20and%20thin.htm"); // Write the new Uri to the console and note the difference in the two values. // ToString() gives the canonical version. OriginalString gives the original @@ -100,7 +104,7 @@ private static void SampleDNSSafeHost() { // // Create new Uri using a string address. - Uri address = new Uri("http://[fe80::200:39ff:fe36:1a2d%254]/temp/example.htm"); + Uri address = new("http://[fe80::200:39ff:fe36:1a2d%254]/temp/example.htm"); // Make the address DNS safe. @@ -117,17 +121,17 @@ private static void SampleOperatorEqual() { // // Create some Uris. - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Uri address2 = new Uri("http://www.contoso.com/index.htm"); - Uri address3 = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Uri address2 = new("http://www.contoso.com/index.htm"); + Uri address3 = new("http://www.contoso.com/index.htm?date=today"); // The first two are equal because the fragment is ignored. if (address1 == address2) - Console.WriteLine("{0} is equal to {1}", address1.ToString(), address2.ToString()); + Console.WriteLine($"{address1.ToString()} is equal to {address2.ToString()}"); // The second two are not equal. if (address2 != address3) - Console.WriteLine("{0} is not equal to {1}", address2.ToString(), address3.ToString()); + Console.WriteLine($"{address2.ToString()} is not equal to {address3.ToString()}"); // } @@ -136,14 +140,14 @@ private static void SampleIsBaseOf() { // // Create a base Uri. - Uri baseUri = new Uri("http://www.contoso.com/"); + Uri baseUri = new("http://www.contoso.com/"); // Create a new Uri from a string. - Uri uriAddress = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri uriAddress = new("http://www.contoso.com/index.htm?date=today"); // Determine whether BaseUri is a base of UriAddress. if (baseUri.IsBaseOf(uriAddress)) - Console.WriteLine("{0} is the base of {1}", baseUri, uriAddress); + Console.WriteLine($"{baseUri} is the base of {uriAddress}"); // } } diff --git a/snippets/csharp/System/Uri/.ctor/source.cs b/snippets/csharp/System/Uri/.ctor/source.cs index 5e9260532e0..1bcfd2903c8 100644 --- a/snippets/csharp/System/Uri/.ctor/source.cs +++ b/snippets/csharp/System/Uri/.ctor/source.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriConstructorForm1 : Form { - protected void Method() - { -// -Uri myUri = new Uri("http://www.contoso.com/"); + protected void Method() + { + // + Uri myUri = new("http://www.contoso.com/"); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/.ctor/source2.cs b/snippets/csharp/System/Uri/.ctor/source2.cs index 32d5bcda07c..1ea7c279ce7 100644 --- a/snippets/csharp/System/Uri/.ctor/source2.cs +++ b/snippets/csharp/System/Uri/.ctor/source2.cs @@ -1,19 +1,16 @@ using System; -using System.Data; -using System.Security.Principal; -using System.IO; using System.Windows.Forms; -public class Form1: Form +public class UriConstructorForm2 : Form { - protected void Method() - { -// -Uri baseUri = new Uri("http://www.contoso.com"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm"); + protected void Method() + { + // + Uri baseUri = new("http://www.contoso.com"); + Uri myUri = new(baseUri, "catalog/shownew.htm"); -Console.WriteLine(myUri.ToString()); + Console.WriteLine(myUri.ToString()); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/AbsolutePath/source.cs b/snippets/csharp/System/Uri/AbsolutePath/source.cs index 9faa6f489aa..828ce4cca8f 100644 --- a/snippets/csharp/System/Uri/AbsolutePath/source.cs +++ b/snippets/csharp/System/Uri/AbsolutePath/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,11 +8,11 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.AbsolutePath); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/AbsoluteUri/source.cs b/snippets/csharp/System/Uri/AbsoluteUri/source.cs index 280a9a037a9..10b68dec3d2 100644 --- a/snippets/csharp/System/Uri/AbsoluteUri/source.cs +++ b/snippets/csharp/System/Uri/AbsoluteUri/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,9 +8,9 @@ public class Form1 protected void Method() { // - Uri baseUri= new Uri("http://www.contoso.com"); - Uri myUri = new Uri(baseUri,"catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.AbsoluteUri); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Authority/source.cs b/snippets/csharp/System/Uri/Authority/source.cs index 6ea24db8682..77a296ced25 100644 --- a/snippets/csharp/System/Uri/Authority/source.cs +++ b/snippets/csharp/System/Uri/Authority/source.cs @@ -1,18 +1,18 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// - Uri baseUri = new Uri("http://www.contoso.com:8080/"); - Uri myUri = new Uri(baseUri,"shownew.htm?date=today"); + protected void Method() + { + // + Uri baseUri = new("http://www.contoso.com:8080/"); + Uri myUri = new(baseUri, "shownew.htm?date=today"); - Console.WriteLine(myUri.Authority); + Console.WriteLine(myUri.Authority); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/CheckHostName/source.cs b/snippets/csharp/System/Uri/CheckHostName/source.cs index 837e5c6c6b1..73d988bfc0c 100644 --- a/snippets/csharp/System/Uri/CheckHostName/source.cs +++ b/snippets/csharp/System/Uri/CheckHostName/source.cs @@ -1,15 +1,15 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// -Console.WriteLine(Uri.CheckHostName("www.contoso.com")); + protected void Method() + { + // + Console.WriteLine(Uri.CheckHostName("www.contoso.com")); -// - } + // + } } diff --git a/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs b/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs index 05f60b1cd08..64e398d601a 100644 --- a/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs +++ b/snippets/csharp/System/Uri/CheckSchemeName/uriexamples.cs @@ -1,8 +1,8 @@ using System; -using System.Net; -using System.Text; -using System.Threading; -using System.Runtime.Serialization; + + + + namespace Example { @@ -38,9 +38,9 @@ public static void Main() private static void SampleToString() { - // + // // Create a new Uri from a string address. - Uri uriAddress = new Uri("HTTP://www.Contoso.com:80/thick%20and%20thin.htm"); + Uri uriAddress = new("HTTP://www.Contoso.com:80/thick%20and%20thin.htm"); // Write the new Uri to the console and note the difference in the two values. // ToString() gives the canonical version. OriginalString gives the orginal @@ -51,190 +51,189 @@ private static void SampleToString() // The following outputs "HTTP://www.Contoso.com:80/thick%20and%20thin.htm". Console.WriteLine(uriAddress.OriginalString); - // + // } private static void SampleEquals() { - // + // // Create some Uris. - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Uri address2 = new Uri("http://www.contoso.com/index.htm"); + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Uri address2 = new("http://www.contoso.com/index.htm"); if (address1.Equals(address2)) Console.WriteLine("The two addresses are equal"); else Console.WriteLine("The two addresses are not equal"); // Will output "The two addresses are equal" - // + // } private static void GetParts() { - // + // // Create Uri - Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search"); + Uri uriAddress = new("http://www.contoso.com/index.htm#search"); Console.WriteLine(uriAddress.Fragment); - Console.WriteLine("Uri {0} the default port ", uriAddress.IsDefaultPort ? "uses" : "does not use"); + Console.WriteLine($"Uri {(uriAddress.IsDefaultPort ? "uses" : "does not use")} the default port "); - Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Path)); - Console.WriteLine("Hash code {0}", uriAddress.GetHashCode()); + Console.WriteLine($"The path of this Uri is {uriAddress.GetLeftPart(UriPartial.Path)}"); + Console.WriteLine($"Hash code {uriAddress.GetHashCode()}"); // The example displays output similar to the following: // #search // Uri uses the default port // The path of this Uri is http://www.contoso.com/index.htm // Hash code -988419291 - // - // - Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm"); - Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]); - // - - // - Uri uriAddress2 = new Uri("file://server/filename.ext"); + // + // + Uri uriAddress1 = new("http://www.contoso.com/title/index.htm"); + Console.WriteLine($"The parts are {uriAddress1.Segments[0]}, {uriAddress1.Segments[1]}, {uriAddress1.Segments[2]}"); + // + + // + Uri uriAddress2 = new("file://server/filename.ext"); Console.WriteLine(uriAddress2.LocalPath); - Console.WriteLine("Uri {0} a UNC path", uriAddress2.IsUnc ? "is" : "is not"); - Console.WriteLine("Uri {0} a local host", uriAddress2.IsLoopback ? "is" : "is not"); - Console.WriteLine("Uri {0} a file", uriAddress2.IsFile ? "is" : "is not"); + Console.WriteLine($"Uri {(uriAddress2.IsUnc ? "is" : "is not")} a UNC path"); + Console.WriteLine($"Uri {(uriAddress2.IsLoopback ? "is" : "is not")} a local host"); + Console.WriteLine($"Uri {(uriAddress2.IsFile ? "is" : "is not")} a file"); // The example displays the following output: // \\server\filename.ext // Uri is a UNC path // Uri is not a local host // Uri is a file - // + // } private static void HexConversions() { - // - char testChar = 'e'; + // + char testChar = 'e'; if (Uri.IsHexDigit(testChar)) - Console.WriteLine("'{0}' is the hexadecimal representation of {1}", testChar, Uri.FromHex(testChar)); + Console.WriteLine($"'{testChar}' is the hexadecimal representation of {Uri.FromHex(testChar)}"); else - Console.WriteLine("'{0}' is not a hexadecimal character", testChar); + Console.WriteLine($"'{testChar}' is not a hexadecimal character"); string returnString = Uri.HexEscape(testChar); - Console.WriteLine("The hexadecimal value of '{0}' is {1}", testChar, returnString); - // + Console.WriteLine($"The hexadecimal value of '{testChar}' is {returnString}"); + // - // + // string testString = "%75"; int index = 0; if (Uri.IsHexEncoding(testString, index)) - Console.WriteLine("The character is {0}", Uri.HexUnescape(testString, ref index)); + Console.WriteLine($"The character is {Uri.HexUnescape(testString, ref index)}"); else - Console.WriteLine("The character is not hexadecimal encoded"); - // + Console.WriteLine("The character is not hexadecimal encoded"); + // } // MakeRelative private static void SampleMakeRelative() { - // + // // Create a base Uri. - Uri address1 = new Uri("http://www.contoso.com/"); + Uri address1 = new("http://www.contoso.com/"); // Create a new Uri from a string. - Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today"); + Uri address2 = new("http://www.contoso.com/index.htm?date=today"); // Determine the relative Uri. - Console.WriteLine("The difference is {0}", address1.MakeRelativeUri(address2)); - // + Console.WriteLine($"The difference is {address1.MakeRelativeUri(address2)}"); + // } //CheckSchemeName private static void SampleCheckSchemeName() { - // - Uri address1 = new Uri("http://www.contoso.com/index.htm#search"); - Console.WriteLine("address 1 {0} a valid scheme name", - Uri.CheckSchemeName(address1.Scheme) ? " has" : " does not have"); + // + Uri address1 = new("http://www.contoso.com/index.htm#search"); + Console.WriteLine($"address 1 {(Uri.CheckSchemeName(address1.Scheme) ? " has" : " does not have")} a valid scheme name"); if (address1.Scheme == Uri.UriSchemeHttp) Console.WriteLine("Uri is HTTP type"); Console.WriteLine(address1.HostNameType); - // + // - // - Uri address2 = new Uri("file://server/filename.ext"); + // + Uri address2 = new("file://server/filename.ext"); if (address2.Scheme == Uri.UriSchemeFile) Console.WriteLine("Uri is a file"); - // + // Console.WriteLine(address2.HostNameType); - // - Uri address3 = new Uri("mailto:user@contoso.com?subject=uri"); + // + Uri address3 = new("mailto:user@contoso.com?subject=uri"); if (address3.Scheme == Uri.UriSchemeMailto) Console.WriteLine("Uri is an email address"); - // + // - // - Uri address4 = new Uri("news:123456@contoso.com"); + // + Uri address4 = new("news:123456@contoso.com"); if (address4.Scheme == Uri.UriSchemeNews) Console.WriteLine("Uri is an Internet news group"); - // + // - // - Uri address5 = new Uri("nntp://news.contoso.com/123456@contoso.com"); + // + Uri address5 = new("nntp://news.contoso.com/123456@contoso.com"); if (address5.Scheme == Uri.UriSchemeNntp) Console.WriteLine("Uri is nntp protocol"); - // + // - // - Uri address6 = new Uri("gopher://example.contoso.com/"); + // + Uri address6 = new("gopher://example.contoso.com/"); if (address6.Scheme == Uri.UriSchemeGopher) Console.WriteLine("Uri is Gopher protocol"); - // + // - // - Uri address7 = new Uri("ftp://contoso/files/testfile.txt"); + // + Uri address7 = new("ftp://contoso/files/testfile.txt"); if (address7.Scheme == Uri.UriSchemeFtp) Console.WriteLine("Uri is Ftp protocol"); - // + // - // - Uri address8 = new Uri("https://example.contoso.com"); + // + Uri address8 = new("https://example.contoso.com"); if (address8.Scheme == Uri.UriSchemeHttps) Console.WriteLine("Uri is Https protocol."); - // + // - // + // string address = "www.contoso.com"; - string uriString = String.Format("{0}{1}{2}/", Uri.UriSchemeHttp, Uri.SchemeDelimiter, address); - #if OLDMETHOD + string uriString = $"{Uri.UriSchemeHttp}{Uri.SchemeDelimiter}{address}/"; +#if OLDMETHOD Uri result; if (Uri.TryParse(uriString, false, false, out result)) Console.WriteLine("{0} is a valid Uri", result.ToString()); else Console.WriteLine("Uri not created"); #endif - Uri result = new Uri(uriString); + Uri result = new(uriString); if (result.IsWellFormedOriginalString()) - Console.WriteLine("{0} is a well formed Uri", uriString); + Console.WriteLine($"{uriString} is a well formed Uri"); else - Console.WriteLine("{0} is not a well formed Uri", uriString); - // + Console.WriteLine($"{uriString} is not a well formed Uri"); + // } private static void SampleUserInfo() { - // - Uri uriAddress = new Uri ("http://user:password@www.contoso.com/index.htm "); + // + Uri uriAddress = new("http://user:password@www.contoso.com/index.htm "); Console.WriteLine(uriAddress.UserInfo); - Console.WriteLine("Fully Escaped {0}", uriAddress.UserEscaped ? "yes" : "no"); - // + Console.WriteLine($"Fully Escaped {(uriAddress.UserEscaped ? "yes" : "no")}"); + // } private static void UnescapeUriWithPlusConversion() { - // - String DataString = Uri.UnescapeDataString(".NET+Framework"); - Console.WriteLine("Unescaped string: {0}", DataString); + // + string DataString = Uri.UnescapeDataString(".NET+Framework"); + Console.WriteLine($"Unescaped string: {DataString}"); - String PlusString = DataString.Replace('+',' '); - Console.WriteLine("plus to space string: {0}", PlusString); - // + string PlusString = DataString.Replace('+', ' '); + Console.WriteLine($"plus to space string: {PlusString}"); + // } } } diff --git a/snippets/csharp/System/Uri/Host/source.cs b/snippets/csharp/System/Uri/Host/source.cs index 9b9051d84a3..ba1d4c4beeb 100644 --- a/snippets/csharp/System/Uri/Host/source.cs +++ b/snippets/csharp/System/Uri/Host/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,10 +8,10 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com:8080/"); - Uri myUri = new Uri(baseUri, "shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com:8080/"); + Uri myUri = new(baseUri, "shownew.htm?date=today"); Console.WriteLine(myUri.Host); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/HostComparison/source.cs b/snippets/csharp/System/Uri/HostComparison/source.cs index c8ebf4678ec..90e74411d51 100644 --- a/snippets/csharp/System/Uri/HostComparison/source.cs +++ b/snippets/csharp/System/Uri/HostComparison/source.cs @@ -1,4 +1,4 @@ -using System; +using System; public class UriHostComparison { @@ -9,7 +9,7 @@ public static void Main() // Example 1: Regular hostname (ASCII). Console.WriteLine("Example 1: Regular ASCII hostname"); - Uri uri1 = new Uri("http://www.contoso.com:8080/path"); + Uri uri1 = new("http://www.contoso.com:8080/path"); Console.WriteLine($" Host: {uri1.Host}"); // www.contoso.com Console.WriteLine($" IdnHost: {uri1.IdnHost}"); // www.contoso.com Console.WriteLine($" DnsSafeHost: {uri1.DnsSafeHost}"); // www.contoso.com @@ -17,7 +17,7 @@ public static void Main() // Example 2: International domain name (non-ASCII). Console.WriteLine("Example 2: International domain name"); - Uri uri2 = new Uri("http://münchen.de/path"); + Uri uri2 = new("http://münchen.de/path"); Console.WriteLine($" Host: {uri2.Host}"); // münchen.de (original) Console.WriteLine($" IdnHost: {uri2.IdnHost}"); // xn--mnchen-3ya.de (punycode) Console.WriteLine($" DnsSafeHost: {uri2.DnsSafeHost}"); // münchen.de or xn--mnchen-3ya.de, depending on configuration. @@ -25,7 +25,7 @@ public static void Main() // Example 3: International domain name already in punycode (encoded) form. Console.WriteLine("Example 3: Already-encoded international domain name"); - Uri uri2Encoded = new Uri("http://xn--mnchen-3ya.de/path"); + Uri uri2Encoded = new("http://xn--mnchen-3ya.de/path"); Console.WriteLine($" Host: {uri2Encoded.Host}"); // xn--mnchen-3ya.de (as provided) Console.WriteLine($" IdnHost: {uri2Encoded.IdnHost}"); // xn--mnchen-3ya.de (already punycode) Console.WriteLine($" DnsSafeHost: {uri2Encoded.DnsSafeHost}"); // xn--mnchen-3ya.de @@ -33,7 +33,7 @@ public static void Main() // Example 4: IPv6 address without zone ID. Console.WriteLine("Example 4: IPv6 address without zone ID"); - Uri uri3 = new Uri("http://[::1]:8080/path"); + Uri uri3 = new("http://[::1]:8080/path"); Console.WriteLine($" Host: {uri3.Host}"); // [::1] (with brackets) Console.WriteLine($" IdnHost: {uri3.IdnHost}"); // ::1 (without brackets) Console.WriteLine($" DnsSafeHost: {uri3.DnsSafeHost}"); // ::1 (without brackets) @@ -41,7 +41,7 @@ public static void Main() // Example 5: IPv6 link-local address with zone ID. Console.WriteLine("Example 5: IPv6 link-local address with zone ID"); - Uri uri4 = new Uri("http://[fe80::1%10]:8080/path"); + Uri uri4 = new("http://[fe80::1%10]:8080/path"); Console.WriteLine($" Host: {uri4.Host}"); // [fe80::1] (with brackets, no zone ID) Console.WriteLine($" IdnHost: {uri4.IdnHost}"); // fe80::1%10 (without brackets, with zone ID) Console.WriteLine($" DnsSafeHost: {uri4.DnsSafeHost}"); // fe80::1%10 (without brackets, with zone ID) @@ -49,7 +49,7 @@ public static void Main() // Example 6: IPv4 address. Console.WriteLine("Example 6: IPv4 address"); - Uri uri5 = new Uri("http://192.168.1.1:8080/path"); + Uri uri5 = new("http://192.168.1.1:8080/path"); Console.WriteLine($" Host: {uri5.Host}"); // 192.168.1.1 Console.WriteLine($" IdnHost: {uri5.IdnHost}"); // 192.168.1.1 Console.WriteLine($" DnsSafeHost: {uri5.DnsSafeHost}"); // 192.168.1.1 diff --git a/snippets/csharp/System/Uri/Overview/source.cs b/snippets/csharp/System/Uri/Overview/source.cs index cdcd2d216b8..e91b21816db 100644 --- a/snippets/csharp/System/Uri/Overview/source.cs +++ b/snippets/csharp/System/Uri/Overview/source.cs @@ -1,69 +1,67 @@ -using System; -using System.Net; +using System; using System.Net.Http; - public class Form1 { - protected void Method() - { - // - Uri siteUri = new Uri("http://www.contoso.com/"); + protected void Method() + { + // + Uri siteUri = new("http://www.contoso.com/"); + + // HttpClient lifecycle management best practices: + // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use + using HttpClient client = new(); + using HttpRequestMessage request = new(HttpMethod.Get, siteUri); + using HttpResponseMessage response = client.Send(request); + // + + // + Uri uri = new("https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName"); + + Console.WriteLine($"AbsolutePath: {uri.AbsolutePath}"); + Console.WriteLine($"AbsoluteUri: {uri.AbsoluteUri}"); + Console.WriteLine($"DnsSafeHost: {uri.DnsSafeHost}"); + Console.WriteLine($"Fragment: {uri.Fragment}"); + Console.WriteLine($"Host: {uri.Host}"); + Console.WriteLine($"HostNameType: {uri.HostNameType}"); + Console.WriteLine($"IdnHost: {uri.IdnHost}"); + Console.WriteLine($"IsAbsoluteUri: {uri.IsAbsoluteUri}"); + Console.WriteLine($"IsDefaultPort: {uri.IsDefaultPort}"); + Console.WriteLine($"IsFile: {uri.IsFile}"); + Console.WriteLine($"IsLoopback: {uri.IsLoopback}"); + Console.WriteLine($"IsUnc: {uri.IsUnc}"); + Console.WriteLine($"LocalPath: {uri.LocalPath}"); + Console.WriteLine($"OriginalString: {uri.OriginalString}"); + Console.WriteLine($"PathAndQuery: {uri.PathAndQuery}"); + Console.WriteLine($"Port: {uri.Port}"); + Console.WriteLine($"Query: {uri.Query}"); + Console.WriteLine($"Scheme: {uri.Scheme}"); + Console.WriteLine($"Segments: {string.Join(", ", uri.Segments)}"); + Console.WriteLine($"UserEscaped: {uri.UserEscaped}"); + Console.WriteLine($"UserInfo: {uri.UserInfo}"); - // HttpClient lifecycle management best practices: - // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use - HttpClient client = new HttpClient(); - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, siteUri); - HttpResponseMessage response = client.Send(request); - // - - // - Uri uri = new Uri("https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName"); - - Console.WriteLine($"AbsolutePath: {uri.AbsolutePath}"); - Console.WriteLine($"AbsoluteUri: {uri.AbsoluteUri}"); - Console.WriteLine($"DnsSafeHost: {uri.DnsSafeHost}"); - Console.WriteLine($"Fragment: {uri.Fragment}"); - Console.WriteLine($"Host: {uri.Host}"); - Console.WriteLine($"HostNameType: {uri.HostNameType}"); - Console.WriteLine($"IdnHost: {uri.IdnHost}"); - Console.WriteLine($"IsAbsoluteUri: {uri.IsAbsoluteUri}"); - Console.WriteLine($"IsDefaultPort: {uri.IsDefaultPort}"); - Console.WriteLine($"IsFile: {uri.IsFile}"); - Console.WriteLine($"IsLoopback: {uri.IsLoopback}"); - Console.WriteLine($"IsUnc: {uri.IsUnc}"); - Console.WriteLine($"LocalPath: {uri.LocalPath}"); - Console.WriteLine($"OriginalString: {uri.OriginalString}"); - Console.WriteLine($"PathAndQuery: {uri.PathAndQuery}"); - Console.WriteLine($"Port: {uri.Port}"); - Console.WriteLine($"Query: {uri.Query}"); - Console.WriteLine($"Scheme: {uri.Scheme}"); - Console.WriteLine($"Segments: {string.Join(", ", uri.Segments)}"); - Console.WriteLine($"UserEscaped: {uri.UserEscaped}"); - Console.WriteLine($"UserInfo: {uri.UserInfo}"); - - // AbsolutePath: /Home/Index.htm - // AbsoluteUri: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName - // DnsSafeHost: www.contoso.com - // Fragment: #FragmentName - // Host: www.contoso.com - // HostNameType: Dns - // IdnHost: www.contoso.com - // IsAbsoluteUri: True - // IsDefaultPort: False - // IsFile: False - // IsLoopback: False - // IsUnc: False - // LocalPath: /Home/Index.htm - // OriginalString: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName - // PathAndQuery: /Home/Index.htm?q1=v1&q2=v2 - // Port: 80 - // Query: ?q1=v1&q2=v2 - // Scheme: https - // Segments: /, Home/, Index.htm - // UserEscaped: False - // UserInfo: user:password + // AbsolutePath: /Home/Index.htm + // AbsoluteUri: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName + // DnsSafeHost: www.contoso.com + // Fragment: #FragmentName + // Host: www.contoso.com + // HostNameType: Dns + // IdnHost: www.contoso.com + // IsAbsoluteUri: True + // IsDefaultPort: False + // IsFile: False + // IsLoopback: False + // IsUnc: False + // LocalPath: /Home/Index.htm + // OriginalString: https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName + // PathAndQuery: /Home/Index.htm?q1=v1&q2=v2 + // Port: 80 + // Query: ?q1=v1&q2=v2 + // Scheme: https + // Segments: /, Home/, Index.htm + // UserEscaped: False + // UserInfo: user:password - // - } + // + } } diff --git a/snippets/csharp/System/Uri/PathAndQuery/source.cs b/snippets/csharp/System/Uri/PathAndQuery/source.cs index 8337964ac6a..bdfaa3c7b6b 100644 --- a/snippets/csharp/System/Uri/PathAndQuery/source.cs +++ b/snippets/csharp/System/Uri/PathAndQuery/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,8 +8,8 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.PathAndQuery); // @@ -19,10 +19,10 @@ public void Method2() { // - Uri baseUri = new Uri ("http://www.contoso.com/"); - Uri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); - Console.WriteLine (myUri.Query); + Console.WriteLine(myUri.Query); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Port/source.cs b/snippets/csharp/System/Uri/Port/source.cs index 77687e3cffc..6814c27f16b 100644 --- a/snippets/csharp/System/Uri/Port/source.cs +++ b/snippets/csharp/System/Uri/Port/source.cs @@ -1,6 +1,6 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 @@ -8,11 +8,11 @@ public class Form1 protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri,"catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.Port); // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System/Uri/Scheme/source.cs b/snippets/csharp/System/Uri/Scheme/source.cs index 59ca2860b89..b3b8b29ff42 100644 --- a/snippets/csharp/System/Uri/Scheme/source.cs +++ b/snippets/csharp/System/Uri/Scheme/source.cs @@ -1,14 +1,14 @@ using System; -using System.Data; -using System.Security.Principal; + + public class Form1 { protected void Method() { // - Uri baseUri = new Uri("http://www.contoso.com/"); - Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today"); + Uri baseUri = new("http://www.contoso.com/"); + Uri myUri = new(baseUri, "catalog/shownew.htm?date=today"); Console.WriteLine(myUri.Scheme); // diff --git a/snippets/csharp/System/UriBuilder/.ctor/Project.csproj b/snippets/csharp/System/UriBuilder/.ctor/Project.csproj new file mode 100644 index 00000000000..b62ae7deede --- /dev/null +++ b/snippets/csharp/System/UriBuilder/.ctor/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net10.0-windows + true + + + diff --git a/snippets/csharp/System/UriBuilder/.ctor/source.cs b/snippets/csharp/System/UriBuilder/.ctor/source.cs index 24d8691fc4f..b4906bea741 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source1.cs b/snippets/csharp/System/UriBuilder/.ctor/source1.cs index 311930fe00e..c1ab40bcede 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source1.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source1.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm1 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source2.cs b/snippets/csharp/System/UriBuilder/.ctor/source2.cs index 84b8d2283e1..8e9009a8caf 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source2.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source2.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm2 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080,"index.htm"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080, "index.htm"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/.ctor/source3.cs b/snippets/csharp/System/UriBuilder/.ctor/source3.cs index ba5a17a2204..2ec8799f768 100644 --- a/snippets/csharp/System/UriBuilder/.ctor/source3.cs +++ b/snippets/csharp/System/UriBuilder/.ctor/source3.cs @@ -1,15 +1,13 @@ using System; -using System.Data; -using System.Security.Principal; using System.Windows.Forms; -public class Form1: Form +public class UriBuilderConstructorForm3 : Form { - protected void Method() - { -// -UriBuilder myUri = new UriBuilder("http","www.contoso.com",8080,"index.htm","#top"); + protected void Method() + { + // + UriBuilder myUri = new("http", "www.contoso.com", 8080, "index.htm", "#top"); -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/Fragment/source.cs b/snippets/csharp/System/UriBuilder/Fragment/source.cs index 64ff7df4ed5..0064d4c1d1c 100644 --- a/snippets/csharp/System/UriBuilder/Fragment/source.cs +++ b/snippets/csharp/System/UriBuilder/Fragment/source.cs @@ -1,19 +1,21 @@ -using System; -using System.Data; -using System.Security.Principal; +using System; + + public class Form1 { - protected void Method() - { -// -UriBuilder uBuild = new UriBuilder("http://www.contoso.com/"); -uBuild.Path = "index.htm"; -uBuild.Fragment = "main"; + protected void Method() + { + // + UriBuilder uBuild = new("http://www.contoso.com/") + { + Path = "index.htm", + Fragment = "main" + }; -Uri myUri = uBuild.Uri; + Uri myUri = uBuild.Uri; -// - } + // + } } diff --git a/snippets/csharp/System/UriBuilder/Query/main.cs b/snippets/csharp/System/UriBuilder/Query/main.cs index f4971e6c279..bdc64dd4445 100644 --- a/snippets/csharp/System/UriBuilder/Query/main.cs +++ b/snippets/csharp/System/UriBuilder/Query/main.cs @@ -1,28 +1,28 @@ #region Using directives using System; -using System.Collections.Generic; -using System.Text; + + #endregion namespace ConsoleApplication1 { - class Program - { - static void Main(string[] args) - { - // - UriBuilder baseUri = new UriBuilder("http://www.contoso.com/default.aspx?Param1=7890"); - string queryToAppend = "param2=1234"; + class Program + { + static void Main(string[] args) + { + // + UriBuilder baseUri = new("http://www.contoso.com/default.aspx?Param1=7890"); + string queryToAppend = "param2=1234"; - if (baseUri.Query != null && baseUri.Query.Length > 1) - // Note: In .NET Core and .NET 5+, you can simplify by removing - // the call to Substring(), which removes the leading "?" character. - baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; - else - baseUri.Query = queryToAppend; - // - } - } + if (baseUri.Query != null && baseUri.Query.Length > 1) + // Note: In .NET Core and .NET 5+, you can simplify by removing + // the call to Substring(), which removes the leading "?" character. + baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; + else + baseUri.Query = queryToAppend; + // + } + } } diff --git a/snippets/csharp/System/ValueType/Equals/Project.csproj b/snippets/csharp/System/ValueType/Equals/Project.csproj new file mode 100644 index 00000000000..dfdef3fd2a7 --- /dev/null +++ b/snippets/csharp/System/ValueType/Equals/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/csharp/System/ValueType/Equals/source.cs b/snippets/csharp/System/ValueType/Equals/source.cs index 4b2be270f81..eb88125f284 100644 --- a/snippets/csharp/System/ValueType/Equals/source.cs +++ b/snippets/csharp/System/ValueType/Equals/source.cs @@ -1,26 +1,27 @@ -using System; + namespace Snippets { - // - public struct Complex - { - public double m_Re; - public double m_Im; + // + public struct Complex + { + public double m_Re; + public double m_Im; - public override bool Equals( object ob ){ - if( ob is Complex ) { - Complex c = (Complex) ob; - return m_Re==c.m_Re && m_Im==c.m_Im; - } - else { - return false; - } - } + public override bool Equals(object ob) + { + if (ob is Complex) + { + Complex c = (Complex)ob; + return m_Re == c.m_Re && m_Im == c.m_Im; + } + else + { + return false; + } + } - public override int GetHashCode(){ - return m_Re.GetHashCode() ^ m_Im.GetHashCode(); - } - } - // -} \ No newline at end of file + public override int GetHashCode() => m_Re.GetHashCode() ^ m_Im.GetHashCode(); + } + // +} diff --git a/snippets/csharp/System/ValueType/Overview/example1.cs b/snippets/csharp/System/ValueType/Overview/example1.cs index c626a8da7e5..59c610aff7d 100644 --- a/snippets/csharp/System/ValueType/Overview/example1.cs +++ b/snippets/csharp/System/ValueType/Overview/example1.cs @@ -4,92 +4,90 @@ public class Utility { - public enum NumericRelationship { - GreaterThan = 1, - EqualTo = 0, - LessThan = -1 - }; - - public static NumericRelationship Compare(ValueType value1, ValueType value2) - { - if (!IsNumeric(value1)) - throw new ArgumentException("value1 is not a number."); - else if (!IsNumeric(value2)) - throw new ArgumentException("value2 is not a number."); + public enum NumericRelationship + { + GreaterThan = 1, + EqualTo = 0, + LessThan = -1 + }; - // Use BigInteger as common integral type - if (IsInteger(value1) && IsInteger(value2)) { - BigInteger bigint1 = (BigInteger) value1; - BigInteger bigint2 = (BigInteger) value2; - return (NumericRelationship) BigInteger.Compare(bigint1, bigint2); - } - // At least one value is floating point; use Double. - else { - Double dbl1 = 0; - Double dbl2 = 0; - try { - dbl1 = Convert.ToDouble(value1); - } - catch (OverflowException) { - Console.WriteLine("value1 is outside the range of a Double."); - } - try { - dbl2 = Convert.ToDouble(value2); - } - catch (OverflowException) { - Console.WriteLine("value2 is outside the range of a Double."); - } - return (NumericRelationship) dbl1.CompareTo(dbl2); - } - } - - public static bool IsInteger(ValueType value) - { - return (value is SByte || value is Int16 || value is Int32 - || value is Int64 || value is Byte || value is UInt16 - || value is UInt32 || value is UInt64 - || value is BigInteger); - } + public static NumericRelationship Compare(ValueType value1, ValueType value2) + { + if (!IsNumeric(value1)) + throw new ArgumentException("value1 is not a number."); + else if (!IsNumeric(value2)) + throw new ArgumentException("value2 is not a number."); - public static bool IsFloat(ValueType value) - { - return (value is float || value is double || value is Decimal); - } + // Use BigInteger as common integral type + if (IsInteger(value1) && IsInteger(value2)) + { + BigInteger bigint1 = (BigInteger)value1; + BigInteger bigint2 = (BigInteger)value2; + return (NumericRelationship)BigInteger.Compare(bigint1, bigint2); + } + // At least one value is floating point; use Double. + else + { + double dbl1 = 0; + double dbl2 = 0; + try + { + dbl1 = Convert.ToDouble(value1); + } + catch (OverflowException) + { + Console.WriteLine("value1 is outside the range of a Double."); + } + try + { + dbl2 = Convert.ToDouble(value2); + } + catch (OverflowException) + { + Console.WriteLine("value2 is outside the range of a Double."); + } + return (NumericRelationship)dbl1.CompareTo(dbl2); + } + } - public static bool IsNumeric(ValueType value) - { - return (value is Byte || - value is Int16 || - value is Int32 || - value is Int64 || - value is SByte || - value is UInt16 || - value is UInt32 || - value is UInt64 || - value is BigInteger || - value is Decimal || - value is Double || - value is Single); - } + public static bool IsInteger(ValueType value) => (value is sbyte || value is short || value is int + || value is long || value is byte || value is ushort + || value is uint || value is ulong + || value is BigInteger); + + public static bool IsFloat(ValueType value) => (value is float || value is double || value is decimal); + + public static bool IsNumeric(ValueType value) => (value is byte || + value is short || + value is int || + value is long || + value is sbyte || + value is ushort || + value is uint || + value is ulong || + value is BigInteger || + value is decimal || + value is double || + value is float); } // -// +// public class Example { - public static void Main() - { - Console.WriteLine(Utility.IsNumeric(12)); - Console.WriteLine(Utility.IsNumeric(true)); - Console.WriteLine(Utility.IsNumeric('c')); - Console.WriteLine(Utility.IsNumeric(new DateTime(2012, 1, 1))); - Console.WriteLine(Utility.IsInteger(12.2)); - Console.WriteLine(Utility.IsInteger(123456789)); - Console.WriteLine(Utility.IsFloat(true)); - Console.WriteLine(Utility.IsFloat(12.2)); - Console.WriteLine(Utility.IsFloat(12)); - Console.WriteLine("{0} {1} {2}", 12.1, Utility.Compare(12.1, 12), 12); - } + public static void Main() + { + Console.WriteLine(Utility.IsNumeric(12)); + Console.WriteLine(Utility.IsNumeric(true)); + Console.WriteLine(Utility.IsNumeric('c')); + Console.WriteLine(Utility.IsNumeric(new DateTime(2012, 1, 1))); + Console.WriteLine(Utility.IsInteger(12.2)); + Console.WriteLine(Utility.IsInteger(123456789)); + Console.WriteLine(Utility.IsFloat(true)); + Console.WriteLine(Utility.IsFloat(12.2)); + Console.WriteLine(Utility.IsFloat(12)); + Console.WriteLine($"{12.1} {Utility.Compare(12.1, 12)} {12}"); + } } // The example displays the following output: // True diff --git a/snippets/csharp/System/ValueType/ToString/ToString2.cs b/snippets/csharp/System/ValueType/ToString/ToString2.cs index a1377024d90..8644062a0ed 100644 --- a/snippets/csharp/System/ValueType/ToString/ToString2.cs +++ b/snippets/csharp/System/ValueType/ToString/ToString2.cs @@ -4,32 +4,29 @@ public class Example { - public static void Main() - { - var empA = new EmployeeA{ Name = "Robert",}; - Console.WriteLine(empA.ToString()); - - var empB = new EmployeeB{ Name = "Robert",}; - Console.WriteLine(empB.ToString()); - } + public static void Main() + { + var empA = new EmployeeA { Name = "Robert", }; + Console.WriteLine(empA.ToString()); + + var empB = new EmployeeB { Name = "Robert", }; + Console.WriteLine(empB.ToString()); + } } namespace Corporate.EmployeeObjects { public struct EmployeeA { - public String Name { get; set; } + public string Name { get; set; } } - + public struct EmployeeB { - public String Name { get; set; } + public string Name { get; set; } - public override String ToString() - { - return Name; - } - } + public override string ToString() => Name; + } } // The example displays the following output: // Corporate.EmployeeObjects.EmployeeA diff --git a/snippets/csharp/System/Version/.ctor/rev.cs b/snippets/csharp/System/Version/.ctor/rev.cs index 8728a2ecb91..0c4c1da9aa5 100644 --- a/snippets/csharp/System/Version/.ctor/rev.cs +++ b/snippets/csharp/System/Version/.ctor/rev.cs @@ -3,22 +3,22 @@ // MajorRevision, and MinorRevision properties. using System; -class Sample +class Sample { - public static void Main() + public static void Main() { - string fmtStd = "Standard version:\n" + - " major.minor.build.revision = {0}.{1}.{2}.{3}"; - string fmtInt = "Interim version:\n" + - " major.minor.build.majRev/minRev = {0}.{1}.{2}.{3}/{4}"; + string fmtStd = "Standard version:\n" + + " major.minor.build.revision = {0}.{1}.{2}.{3}"; + string fmtInt = "Interim version:\n" + + " major.minor.build.majRev/minRev = {0}.{1}.{2}.{3}/{4}"; - Version std = new Version(2, 4, 1128, 2); - Version interim = new Version(2, 4, 1128, (100 << 16) + 2); + Version std = new(2, 4, 1128, 2); + Version interim = new(2, 4, 1128, (100 << 16) + 2); - Console.WriteLine(fmtStd, std.Major, std.Minor, std.Build, std.Revision); - Console.WriteLine(fmtInt, interim.Major, interim.Minor, interim.Build, - interim.MajorRevision, interim.MinorRevision); + Console.WriteLine(fmtStd, std.Major, std.Minor, std.Build, std.Revision); + Console.WriteLine(fmtInt, interim.Major, interim.Minor, interim.Build, + interim.MajorRevision, interim.MinorRevision); } } /* @@ -30,4 +30,4 @@ public static void Main() major.minor.build.majRev/minRev = 2.4.1128.100/2 */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Version/Overview/GettingVersions1.cs b/snippets/csharp/System/Version/Overview/GettingVersions1.cs index 7d914d90746..d775e45659b 100644 --- a/snippets/csharp/System/Version/Overview/GettingVersions1.cs +++ b/snippets/csharp/System/Version/Overview/GettingVersions1.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection; [assembly: CLSCompliant(true)] public class Class1 diff --git a/snippets/csharp/System/Version/Overview/comparisons1.cs b/snippets/csharp/System/Version/Overview/comparisons1.cs index 67c94f8978e..31749246054 100644 --- a/snippets/csharp/System/Version/Overview/comparisons1.cs +++ b/snippets/csharp/System/Version/Overview/comparisons1.cs @@ -2,33 +2,25 @@ public class Example7 { - public static void Main() - { - CompareSimple(); - } + public static void Main() => CompareSimple(); - private static void CompareSimple() - { - // - Version v1 = new(2, 0); - Version v2 = new("2.1"); - Console.Write("Version {0} is ", v1); - switch(v1.CompareTo(v2)) - { - case 0: - Console.Write("the same as"); - break; - case 1: - Console.Write("later than"); - break; - case -1: - Console.Write("earlier than"); - break; - } - Console.WriteLine($" Version {v2}."); + private static void CompareSimple() + { + // + Version v1 = new(2, 0); + Version v2 = new("2.1"); + string relationship = v1.CompareTo(v2) switch + { + -1 => "earlier than", + 0 => "the same as", + 1 => "later than", + _ => throw new InvalidOperationException() + }; - // The example displays the following output: - // Version 2.0 is earlier than Version 2.1. - // - } + Console.WriteLine($"Version {v1} is {relationship} Version {v2}."); + + // The example displays the following output: + // Version 2.0 is earlier than Version 2.1. + // + } } diff --git a/snippets/csharp/System/Version/Overview/comparisons2.cs b/snippets/csharp/System/Version/Overview/comparisons2.cs index e4f6dc58c92..3de96a7f718 100644 --- a/snippets/csharp/System/Version/Overview/comparisons2.cs +++ b/snippets/csharp/System/Version/Overview/comparisons2.cs @@ -1,24 +1,27 @@ // using System; -enum VersionTime {Earlier = -1, Same = 0, Later = 1 }; +enum VersionTime +{ + Earlier = -1, + Same = 0, + Later = 1 +} public class Example2 { - public static void Main() - { - Version v1 = new(1, 1); - Version v1a = new("1.1.0"); - ShowRelationship(v1, v1a); - - Version v1b = new(1, 1, 0, 0); - ShowRelationship(v1b, v1a); - } + public static void Main() + { + Version v1 = new(1, 1); + Version v1a = new("1.1.0"); + ShowRelationship(v1, v1a); + + Version v1b = new(1, 1, 0, 0); + ShowRelationship(v1b, v1a); + } - private static void ShowRelationship(Version v1, Version v2) - { - Console.WriteLine($"Relationship of {v1} to {v2}: {(VersionTime) v1.CompareTo(v2)}"); - } + private static void ShowRelationship(Version v1, Version v2) => + Console.WriteLine($"Relationship of {v1} to {v2}: {(VersionTime)v1.CompareTo(v2)}"); } // The example displays the following output: diff --git a/snippets/csharp/System/Version/Overview/currentapp.cs b/snippets/csharp/System/Version/Overview/currentapp.cs index 0a932351d50..82979bf7577 100644 --- a/snippets/csharp/System/Version/Overview/currentapp.cs +++ b/snippets/csharp/System/Version/Overview/currentapp.cs @@ -4,13 +4,13 @@ public class Example4 { - public static void Main() - { - // Get the version of the executing assembly (that is, this assembly). - Assembly assem = Assembly.GetEntryAssembly(); - AssemblyName assemName = assem.GetName(); - Version ver = assemName.Version; - Console.WriteLine("Application {0}, Version {1}", assemName.Name, ver.ToString()); - } + public static void Main() + { + // Get the version of the executing assembly (that is, this assembly). + Assembly assem = Assembly.GetEntryAssembly(); + AssemblyName assemName = assem.GetName(); + Version ver = assemName.Version; + Console.WriteLine($"Application {assemName.Name}, Version {ver}"); + } } // diff --git a/snippets/csharp/System/Version/Overview/currentassem.cs b/snippets/csharp/System/Version/Overview/currentassem.cs index e83f32b25e7..11559103e42 100644 --- a/snippets/csharp/System/Version/Overview/currentassem.cs +++ b/snippets/csharp/System/Version/Overview/currentassem.cs @@ -4,13 +4,13 @@ public class Example3 { - public static void Main() - { - // Get the version of the current assembly. - Assembly assem = typeof(Example3).Assembly; - AssemblyName assemName = assem.GetName(); - Version ver = assemName.Version; - Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString()); - } + public static void Main() + { + // Get the version of the current assembly. + Assembly assem = typeof(Example3).Assembly; + AssemblyName assemName = assem.GetName(); + Version ver = assemName.Version; + Console.WriteLine($"{assemName.Name}, Version {ver}"); + } } // diff --git a/snippets/csharp/System/Version/Overview/example1.cs b/snippets/csharp/System/Version/Overview/example1.cs index e595209c12f..5fc37e45c07 100644 --- a/snippets/csharp/System/Version/Overview/example1.cs +++ b/snippets/csharp/System/Version/Overview/example1.cs @@ -2,19 +2,18 @@ using System; using System.Reflection; -[assembly:AssemblyVersionAttribute("2.0.1")] +[assembly: AssemblyVersion("2.0.1")] public class Example1 { - public static void Main() - { - Assembly thisAssem = typeof(Example1).Assembly; - AssemblyName thisAssemName = thisAssem.GetName(); - - Version ver = thisAssemName.Version; - - Console.WriteLine("This is version {0} of {1}.", ver, thisAssemName.Name); - } + public static void Main() + { + Assembly thisAssem = typeof(Example1).Assembly; + AssemblyName thisAssemName = thisAssem.GetName(); + Version ver = thisAssemName.Version; + + Console.WriteLine($"This is version {ver} of {thisAssemName.Name}."); + } } // The example displays the following output: diff --git a/snippets/csharp/System/Version/Parse/parse1.cs b/snippets/csharp/System/Version/Parse/parse1.cs index 3faf054b2c8..8fe2308e930 100644 --- a/snippets/csharp/System/Version/Parse/parse1.cs +++ b/snippets/csharp/System/Version/Parse/parse1.cs @@ -3,56 +3,63 @@ public class Example { - public static void Main() - { - string input = "4.0"; - ParseVersion(input); - - input = "4.0."; - ParseVersion(input); - - input = "1.1.2"; - ParseVersion(input); - - input = "1.1.2.01702"; - ParseVersion(input); - - input = "1.1.2.0702.119"; - ParseVersion(input); - - input = "1.3.5.2150000000"; - ParseVersion(input); - } - - private static void ParseVersion(string input) - { - try { - Version ver = Version.Parse(input); - Console.WriteLine("Converted '{0} to {1}.", input, ver); - } - catch (ArgumentNullException) { - Console.WriteLine("Error: String to be parsed is null."); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("Error: Negative value in '{0}'.", input); - } - catch (ArgumentException) { - Console.WriteLine("Error: Bad number of components in '{0}'.", - input); - } - catch (FormatException) { - Console.WriteLine("Error: Non-integer value in '{0}'.", input); - } - catch (OverflowException) { - Console.WriteLine("Error: Number out of range in '{0}'.", input); - } - } + public static void Main() + { + string input = "4.0"; + ParseVersion(input); + + input = "4.0."; + ParseVersion(input); + + input = "1.1.2"; + ParseVersion(input); + + input = "1.1.2.01702"; + ParseVersion(input); + + input = "1.1.2.0702.119"; + ParseVersion(input); + + input = "1.3.5.2150000000"; + ParseVersion(input); + } + + private static void ParseVersion(string input) + { + try + { + Version ver = Version.Parse(input); + Console.WriteLine($"Converted '{input}' to {ver}."); + } + catch (ArgumentNullException) + { + Console.WriteLine("Error: String to be parsed is null."); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"Error: Negative value in '{input}'."); + } + catch (ArgumentException) + { + Console.WriteLine($"Error: Bad number of components in '{input}'."); + } + catch (FormatException) + { + Console.WriteLine($"Error: Non-integer value in '{input}'."); + } + catch (OverflowException) + { + Console.WriteLine($"Error: Number out of range in '{input}'."); + } + } } + // The example displays the following output: -// Converted '4.0 to 4.0. +// Converted '4.0' to 4.0. // Error: Non-integer value in '4.0.'. -// Converted '1.1.2 to 1.1.2. -// Converted '1.1.2.01702 to 1.1.2.1702. +// Converted '1.1.2' to 1.1.2. +// Converted '1.1.2.01702' to 1.1.2.1702. // Error: Bad number of components in '1.1.2.0702.119'. // Error: Number out of range in '1.3.5.2150000000'. -// \ No newline at end of file + +// diff --git a/snippets/csharp/System/Version/TryParse/tryparse1.cs b/snippets/csharp/System/Version/TryParse/tryparse1.cs index e814d444c22..988e365c56b 100644 --- a/snippets/csharp/System/Version/TryParse/tryparse1.cs +++ b/snippets/csharp/System/Version/TryParse/tryparse1.cs @@ -3,42 +3,43 @@ public class Example { - public static void Main() - { - string input = "4.0"; - ParseVersion(input); - - input = "4.0."; - ParseVersion(input); - - input = "1.1.2"; - ParseVersion(input); - - input = "1.1.2.01702"; - ParseVersion(input); - - input = "1.1.2.0702.119"; - ParseVersion(input); - - input = "1.3.5.2150000000"; - ParseVersion(input); - } - - private static void ParseVersion(string input) - { - Version ver = null; - if (Version.TryParse(input, out ver)) - Console.WriteLine("Converted '{0} to {1}.", input, ver); - else - Console.WriteLine("Unable to determine the version from '{0}'.", - input); - } + public static void Main() + { + string input = "4.0"; + ParseVersion(input); + + input = "4.0."; + ParseVersion(input); + + input = "1.1.2"; + ParseVersion(input); + + input = "1.1.2.01702"; + ParseVersion(input); + + input = "1.1.2.0702.119"; + ParseVersion(input); + + input = "1.3.5.2150000000"; + ParseVersion(input); + } + + private static void ParseVersion(string input) + { + Version ver = null; + if (Version.TryParse(input, out ver)) + Console.WriteLine($"Converted '{input}' to {ver}."); + else + Console.WriteLine($"Unable to determine the version from '{input}'."); + } } + // The example displays the following output: -// Converted '4.0 to 4.0. +// Converted '4.0' to 4.0. // Unable to determine the version from '4.0.'. -// Converted '1.1.2 to 1.1.2. -// Converted '1.1.2.01702 to 1.1.2.1702. +// Converted '1.1.2' to 1.1.2. +// Converted '1.1.2.01702' to 1.1.2.1702. // Unable to determine the version from '1.1.2.0702.119'. // Unable to determine the version from '1.3.5.2150000000'. -// \ No newline at end of file + +// diff --git a/snippets/csharp/System/WeakReference/Overview/program.cs b/snippets/csharp/System/WeakReference/Overview/program.cs index e4d13b0f6e1..c8c7c2dab7a 100644 --- a/snippets/csharp/System/WeakReference/Overview/program.cs +++ b/snippets/csharp/System/WeakReference/Overview/program.cs @@ -8,21 +8,22 @@ public static void Main() { // Create the cache. int cacheSize = 50; - Random r = new Random(); - Cache c = new Cache(cacheSize); + Random r = new(); + Cache c = new(cacheSize); string DataName = ""; GC.Collect(0); // Randomly access objects in the cache. - for (int i = 0; i < c.Count; i++) { + for (int i = 0; i < c.Count; i++) + { int index = r.Next(c.Count); // Access the object by getting a property value. DataName = c[index].Name; } // Show results. - double regenPercent = c.RegenerationCount/(double)c.Count; + double regenPercent = c.RegenerationCount / (double)c.Count; Console.WriteLine($"Cache size: {c.Count}, Regenerated: {regenPercent:P0}"); } } @@ -37,49 +38,47 @@ public class Cache public Cache(int count) { - _cache = new Dictionary(); + _cache = new(); // // Add objects with a short weak reference to the cache. - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { _cache.Add(i, new WeakReference(new Data(i), false)); } // } // Number of items in the cache. - public int Count - { - get { return _cache.Count; } - } + public int Count => _cache.Count; // Number of times an object needs to be regenerated. - public int RegenerationCount - { - get { return regenCount; } - } + public int RegenerationCount => regenCount; // Retrieve a data object from the cache. public Data this[int index] { - get { + get + { // Data d = _cache[index].Target as Data; - if (d == null) { + if (d == null) + { // If the object was reclaimed, generate a new one. - Console.WriteLine("Regenerate object at {0}: Yes", index); - d = new Data(index); + Console.WriteLine($"Regenerate object at {index}: Yes"); + d = new(index); _cache[index].Target = d; regenCount++; } - else { + else + { // Object was obtained with the weak reference. - Console.WriteLine("Regenerate object at {0}: No", index); + Console.WriteLine($"Regenerate object at {index}: No"); } return d; - // - } + // + } } } @@ -96,10 +95,7 @@ public Data(int size) } // Simple property. - public string Name - { - get { return _name; } - } + public string Name => _name; } // Example of the last lines of the output: // @@ -114,4 +110,4 @@ public string Name // Regenerate object at 43: Yes // Regenerate object at 38: No // Cache size: 50, Regenerated: 94% -// \ No newline at end of file +// From ddc57802950f8ab66405f6743eb4fa54dc2f48b2 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Fri, 14 Aug 2026 10:30:41 -0700 Subject: [PATCH 9/9] Modernize C# code snippets - System/P*, System/R* (#12969) --- .../ParamArrayAttribute/Overview/Example.cs | 114 +++++++++--------- .../csharp/System/PlatformID/Overview/pid.cs | 40 +++--- .../System/PredicateT/Overview/Project.csproj | 8 ++ .../System/PredicateT/Overview/predicate1.cs | 50 ++++---- .../PredicateT/Overview/predicateex1.cs | 24 ++-- .../PredicateT/Overview/predicateex2.cs | 33 +++-- snippets/csharp/System/Random/.ctor/ctor.cs | 44 +++---- snippets/csharp/System/Random/.ctor/ctor1.cs | 40 +++--- snippets/csharp/System/Random/.ctor/ctor4.cs | 38 +++--- snippets/csharp/System/Random/Next/sample.cs | 47 +++----- .../csharp/System/Random/NextBytes/source.cs | 6 +- .../System/Random/NextDouble/nextdouble1.cs | 55 ++++----- .../csharp/System/Random/Overview/Next2.cs | 84 ++++++------- .../csharp/System/Random/Overview/Random2.cs | 12 +- .../System/Random/Overview/booleans1.cs | 18 +-- .../System/Random/Overview/booleans2.cs | 13 +- .../System/Random/Overview/doublerange1.cs | 6 +- .../System/Random/Overview/doublerange3.cs | 4 +- .../csharp/System/Random/Overview/long1.cs | 6 +- .../csharp/System/Random/Overview/next.cs | 4 +- .../System/Random/Overview/threadsafeex1.cs | 10 +- .../System/Random/Overview/threadsafeex2.cs | 20 +-- .../csharp/System/Random/Overview/unique.cs | 4 +- .../System/Random/Overview/uniquearray1.cs | 9 +- .../getpinnablereference1.cs | 7 +- .../Overview/type_gettypehandle.cs | 28 ++--- 26 files changed, 337 insertions(+), 387 deletions(-) create mode 100644 snippets/csharp/System/PredicateT/Overview/Project.csproj diff --git a/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs b/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs index 3e245b91d86..f93cd9ac9f4 100644 --- a/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs +++ b/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs @@ -3,81 +3,75 @@ public class Temperature { - private decimal temp; + private decimal temp; - public Temperature(decimal temperature) - { - this.temp = temperature; - } + public Temperature(decimal temperature) => this.temp = temperature; - public override string ToString() - { - return ToString("C"); - } + public override string ToString() => ToString("C"); - public string ToString(string format) - { - if (String.IsNullOrEmpty(format)) - format = "G"; + public string ToString(string format) + { + if (string.IsNullOrEmpty(format)) + format = "G"; - switch (format.ToUpper()) - { - case "G": - case "C": - return temp.ToString("N") + " °C"; - case "F": - return (9 * temp / 5 + 32).ToString("N") + " °F"; - case "K": - return (temp + 273.15m).ToString("N") + " °K"; - default: - throw new FormatException(String.Format("The '{0}' format specifier is not supported", - format)); - } - } + switch (format.ToUpperInvariant()) + { + case "G": + case "C": + return temp.ToString("N") + " °C"; + case "F": + return (9 * temp / 5 + 32).ToString("N") + " °F"; + case "K": + return (temp + 273.15m).ToString("N") + " °K"; + default: + throw new FormatException($"The '{format}' format specifier is not supported"); + } + } - public void Display(params string []formats) - { - if (formats.Length == 0) - { - Console.WriteLine(this.ToString("G")); - } - else - { - foreach (string format in formats) - { - try { - Console.WriteLine(this.ToString(format)); + public void Display(params string[] formats) + { + if (formats.Length == 0) + { + Console.WriteLine(this.ToString("G")); + } + else + { + foreach (string format in formats) + { + try + { + Console.WriteLine(this.ToString(format)); + } + // If there is an exception, do nothing. + catch { } } - // If there is an exception, do nothing. - catch { } - } - } - } + } + } } // // public class Class1 { - public static void Main() - { - Temperature temp1 = new Temperature(100); - string[] formats = { "C", "G", "F", "K" }; + public static void Main() + { + Temperature temp1 = new(100); + string[] formats = [ "C", "G", "F", "K" ]; - // Call Display method with a string array. - Console.WriteLine("Calling Display with a string array:"); - temp1.Display(formats); - Console.WriteLine(); + // Call Display method with a string array. + Console.WriteLine("Calling Display with a string array:"); + temp1.Display(formats); + Console.WriteLine(); - // Call Display method with individual string arguments. - Console.WriteLine("Calling Display with individual arguments:"); - temp1.Display("C", "F", "K", "G"); - Console.WriteLine(); + // Call Display method with individual string arguments. + Console.WriteLine("Calling Display with individual arguments:"); + temp1.Display("C", "F", "K", "G"); + Console.WriteLine(); - // Call parameterless Display method. - Console.WriteLine("Calling Display with an implicit parameter array:"); - temp1.Display(); - } + // Call parameterless Display method. + Console.WriteLine("Calling Display with an implicit parameter array:"); + temp1.Display(); + } } // The example displays the following output: // Calling Display with a string array: diff --git a/snippets/csharp/System/PlatformID/Overview/pid.cs b/snippets/csharp/System/PlatformID/Overview/pid.cs index 0f3f208e9d6..f93b59ce4f9 100644 --- a/snippets/csharp/System/PlatformID/Overview/pid.cs +++ b/snippets/csharp/System/PlatformID/Overview/pid.cs @@ -6,28 +6,28 @@ class Sample { public static void Main() { - string msg1 = "This is a Windows operating system."; - string msg2 = "This is a Unix operating system."; - string msg3 = "ERROR: This platform identifier is invalid."; + string msg1 = "This is a Windows operating system."; + string msg2 = "This is a Unix operating system."; + string msg3 = "ERROR: This platform identifier is invalid."; -// Assume this example is run on a Windows operating system. + // Assume this example is run on a Windows operating system. - OperatingSystem os = Environment.OSVersion; - PlatformID pid = os.Platform; - switch (pid) + OperatingSystem os = Environment.OSVersion; + PlatformID pid = os.Platform; + switch (pid) { - case PlatformID.Win32NT: - case PlatformID.Win32S: - case PlatformID.Win32Windows: - case PlatformID.WinCE: - Console.WriteLine(msg1); - break; - case PlatformID.Unix: - Console.WriteLine(msg2); - break; - default: - Console.WriteLine(msg3); - break; + case PlatformID.Win32NT: + case PlatformID.Win32S: + case PlatformID.Win32Windows: + case PlatformID.WinCE: + Console.WriteLine(msg1); + break; + case PlatformID.Unix: + Console.WriteLine(msg2); + break; + default: + Console.WriteLine(msg3); + break; } } } @@ -36,4 +36,4 @@ public static void Main() This is a Windows operating system. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/PredicateT/Overview/Project.csproj b/snippets/csharp/System/PredicateT/Overview/Project.csproj new file mode 100644 index 00000000000..dfdef3fd2a7 --- /dev/null +++ b/snippets/csharp/System/PredicateT/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net10.0 + + + diff --git a/snippets/csharp/System/PredicateT/Overview/predicate1.cs b/snippets/csharp/System/PredicateT/Overview/predicate1.cs index a70880bda97..99512cdf2a4 100644 --- a/snippets/csharp/System/PredicateT/Overview/predicate1.cs +++ b/snippets/csharp/System/PredicateT/Overview/predicate1.cs @@ -1,44 +1,42 @@ -// +namespace PredicateExample3; + +// using System; using System.Collections.Generic; public class HockeyTeam { - private string _name; - private int _founded; + private string _name; + private int _founded; - public HockeyTeam(string name, int year) - { - _name = name; - _founded = year; - } + public HockeyTeam(string name, int year) + { + _name = name; + _founded = year; + } - public string Name { - get { return _name; } - } + public string Name => _name; - public int Founded { - get { return _founded; } - } + public int Founded => _founded; } public class Example { - public static void Main() - { - Random rnd = new Random(); - List teams = new List(); - teams.AddRange( new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926), + public static void Main() + { + Random rnd = new(); + List teams = new(); + teams.AddRange(new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926), new HockeyTeam("Chicago Blackhawks", 1926), new HockeyTeam("San Jose Sharks", 1991), new HockeyTeam("Montreal Canadiens", 1909), - new HockeyTeam("St. Louis Blues", 1967) } ); - int[] years = { 1920, 1930, 1980, 2000 }; - int foundedBeforeYear = years[rnd.Next(0, years.Length)]; - Console.WriteLine("Teams founded before {0}:", foundedBeforeYear); - foreach (var team in teams.FindAll( x => x.Founded <= foundedBeforeYear)) - Console.WriteLine("{0}: {1}", team.Name, team.Founded); - } + new HockeyTeam("St. Louis Blues", 1967) }); + int[] years = { 1920, 1930, 1980, 2000 }; + int foundedBeforeYear = years[rnd.Next(0, years.Length)]; + Console.WriteLine($"Teams founded before {foundedBeforeYear}:"); + foreach (var team in teams.FindAll(x => x.Founded <= foundedBeforeYear)) + Console.WriteLine($"{team.Name}: {team.Founded}"); + } } // The example displays output similar to the following: // Teams founded before 1930: diff --git a/snippets/csharp/System/PredicateT/Overview/predicateex1.cs b/snippets/csharp/System/PredicateT/Overview/predicateex1.cs index dfe5e2b61f9..fb66c274e66 100644 --- a/snippets/csharp/System/PredicateT/Overview/predicateex1.cs +++ b/snippets/csharp/System/PredicateT/Overview/predicateex1.cs @@ -1,23 +1,25 @@ -// +namespace PredicateExample2; + +// using System; using System.Drawing; public class Example { - public static void Main() - { - // Create an array of Point structures. - Point[] points = { new Point(100, 200), + public static void Main() + { + // Create an array of Point structures. + Point[] points = { new Point(100, 200), new Point(150, 250), new Point(250, 375), new Point(275, 395), new Point(295, 450) }; - // Find the first Point structure for which X times Y - // is greater than 100000. - Point first = Array.Find(points, x => x.X * x.Y > 100000 ); + // Find the first Point structure for which X times Y + // is greater than 100000. + Point first = Array.Find(points, x => x.X * x.Y > 100000); - // Display the first structure found. - Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); - } + // Display the first structure found. + Console.WriteLine($"Found: X = {first.X}, Y = {first.Y}"); + } } // The example displays the following output: // Found: X = 275, Y = 395 diff --git a/snippets/csharp/System/PredicateT/Overview/predicateex2.cs b/snippets/csharp/System/PredicateT/Overview/predicateex2.cs index bcba19c7089..9b89982d5e2 100644 --- a/snippets/csharp/System/PredicateT/Overview/predicateex2.cs +++ b/snippets/csharp/System/PredicateT/Overview/predicateex2.cs @@ -1,31 +1,30 @@ -// +namespace PredicateExample4; + +// using System; using System.Drawing; public class Example { - public static void Main() - { - // Create an array of Point structures. - Point[] points = { new Point(100, 200), + public static void Main() + { + // Create an array of Point structures. + Point[] points = { new Point(100, 200), new Point(150, 250), new Point(250, 375), new Point(275, 395), new Point(295, 450) }; - // Define the Predicate delegate. - Predicate predicate = FindPoints; + // Define the Predicate delegate. + Predicate predicate = FindPoints; - // Find the first Point structure for which X times Y - // is greater than 100000. - Point first = Array.Find(points, predicate); + // Find the first Point structure for which X times Y + // is greater than 100000. + Point first = Array.Find(points, predicate); - // Display the first structure found. - Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y); - } + // Display the first structure found. + Console.WriteLine($"Found: X = {first.X}, Y = {first.Y}"); + } - private static bool FindPoints(Point obj) - { - return obj.X * obj.Y > 100000; - } + private static bool FindPoints(Point obj) => obj.X * obj.Y > 100000; } // The example displays the following output: // Found: X = 275, Y = 395 diff --git a/snippets/csharp/System/Random/.ctor/ctor.cs b/snippets/csharp/System/Random/.ctor/ctor.cs index 7c9875c8f70..5239b2c5fe9 100644 --- a/snippets/csharp/System/Random/.ctor/ctor.cs +++ b/snippets/csharp/System/Random/.ctor/ctor.cs @@ -10,13 +10,13 @@ public class RandomObjectDemo static void RunIntNDoubleRandoms(Random randObj) { // Generate the first six random integers. - for(int j = 0; j < 6; j++) - Console.Write(" {0,10} ", randObj.Next()); + for (int j = 0; j < 6; j++) + Console.Write($" {randObj.Next(),10} "); Console.WriteLine(); // Generate the first six random doubles. - for(int j = 0; j < 6; j++) - Console.Write(" {0:F8} ", randObj.NextDouble()); + for (int j = 0; j < 6; j++) + Console.Write($" {randObj.NextDouble():F8} "); Console.WriteLine(); } @@ -26,7 +26,7 @@ static void FixedSeedRandoms(int seed) Console.WriteLine( "\nRandom numbers from a Random object with " + "seed = {0}:", seed); - Random fixRand = new Random(seed); + Random fixRand = new(seed); RunIntNDoubleRandoms(fixRand); } @@ -40,13 +40,13 @@ static void AutoSeedRandoms() Console.WriteLine( "\nRandom numbers from a Random object " + "with an auto-generated seed:"); - Random autoRand = new Random(); + Random autoRand = new(); RunIntNDoubleRandoms(autoRand); } static void Main() - { + { Console.WriteLine( "This example of the Random class constructors and " + "Random.NextDouble() \n" + @@ -108,19 +108,19 @@ 0.04937517 0.44618494 0.83879212 0.43139707 0.36163507 0.11024451 // same timer value that will produce unique random number sequences. public class FixTimerResolution { - public static void CreateEnginesWithSameTimer() - { -// - int randomInstancesToCreate = 4; - Random[] randomEngines = new Random[randomInstancesToCreate]; - for (int ctr = 0; ctr < randomInstancesToCreate; ctr++) - { - randomEngines[ctr] = new Random(unchecked((int) (DateTime.Now.Ticks >> ctr))); - } -// - for (int ctr = 0; ctr < randomInstancesToCreate; ctr++) - { - Console.WriteLine(randomEngines[ctr].Next()); - } - } + public static void CreateEnginesWithSameTimer() + { + // + int randomInstancesToCreate = 4; + Random[] randomEngines = new Random[randomInstancesToCreate]; + for (int ctr = 0; ctr < randomInstancesToCreate; ctr++) + { + randomEngines[ctr] = new(unchecked((int)(DateTime.Now.Ticks >> ctr))); + } + // + for (int ctr = 0; ctr < randomInstancesToCreate; ctr++) + { + Console.WriteLine(randomEngines[ctr].Next()); + } + } } diff --git a/snippets/csharp/System/Random/.ctor/ctor1.cs b/snippets/csharp/System/Random/.ctor/ctor1.cs index e9e61383e04..ede86d28b58 100644 --- a/snippets/csharp/System/Random/.ctor/ctor1.cs +++ b/snippets/csharp/System/Random/.ctor/ctor1.cs @@ -4,26 +4,26 @@ public class RandomNumbers { - public static void Main() - { - Random rand1 = new Random(); - Random rand2 = new Random(); - Thread.Sleep(2000); - Random rand3 = new Random(); - ShowRandomNumbers(rand1); - ShowRandomNumbers(rand2); - ShowRandomNumbers(rand3); - } + public static void Main() + { + Random rand1 = new(); + Random rand2 = new(); + Thread.Sleep(2000); + Random rand3 = new(); + ShowRandomNumbers(rand1); + ShowRandomNumbers(rand2); + ShowRandomNumbers(rand3); + } - private static void ShowRandomNumbers(Random rand) - { - Console.WriteLine(); - byte[] values = new byte[5]; - rand.NextBytes(values); - foreach (byte value in values) - Console.Write("{0, 5}", value); - Console.WriteLine(); - } + private static void ShowRandomNumbers(Random rand) + { + Console.WriteLine(); + byte[] values = new byte[5]; + rand.NextBytes(values); + foreach (byte value in values) + Console.Write($"{value,5}"); + Console.WriteLine(); + } } // The example displays an output similar to the following: // 28 35 133 224 58 @@ -31,4 +31,4 @@ private static void ShowRandomNumbers(Random rand) // 28 35 133 224 58 // // 32 222 43 251 49 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Random/.ctor/ctor4.cs b/snippets/csharp/System/Random/.ctor/ctor4.cs index 01b219da8e5..9358c8f9141 100644 --- a/snippets/csharp/System/Random/.ctor/ctor4.cs +++ b/snippets/csharp/System/Random/.ctor/ctor4.cs @@ -4,27 +4,27 @@ public class Example { - public static void Main() - { - Random rand1 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF); - Random rand2 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF); - Thread.Sleep(20); - Random rand3 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF); - ShowRandomNumbers(rand1); - ShowRandomNumbers(rand2); - ShowRandomNumbers(rand3); - } + public static void Main() + { + Random rand1 = new((int)DateTime.Now.Ticks & 0x0000FFFF); + Random rand2 = new((int)DateTime.Now.Ticks & 0x0000FFFF); + Thread.Sleep(20); + Random rand3 = new((int)DateTime.Now.Ticks & 0x0000FFFF); + ShowRandomNumbers(rand1); + ShowRandomNumbers(rand2); + ShowRandomNumbers(rand3); + } - private static void ShowRandomNumbers(Random rand) - { - Console.WriteLine(); - byte[] values = new byte[4]; - rand.NextBytes(values); - foreach (var value in values) - Console.Write("{0, 5}", value); + private static void ShowRandomNumbers(Random rand) + { + Console.WriteLine(); + byte[] values = new byte[4]; + rand.NextBytes(values); + foreach (byte value in values) + Console.Write($"{value,5}"); - Console.WriteLine(); - } + Console.WriteLine(); + } } // The example displays output similar to the following: // 145 214 177 134 173 diff --git a/snippets/csharp/System/Random/Next/sample.cs b/snippets/csharp/System/Random/Next/sample.cs index 75ce9349484..ef7ff03ff47 100644 --- a/snippets/csharp/System/Random/Next/sample.cs +++ b/snippets/csharp/System/Random/Next/sample.cs @@ -7,31 +7,25 @@ public class RandomProportional : Random { // The Sample method generates a distribution proportional to the value // of the random numbers, in the range [0.0, 1.0]. - protected override double Sample() - { - return Math.Sqrt(base.Sample()); - } + protected override double Sample() => Math.Sqrt(base.Sample()); - public override int Next() - { - return (int) (Sample() * int.MaxValue); - } + public override int Next() => (int)(Sample() * int.MaxValue); } public class RandomSampleDemo { static void Main() - { + { const int rows = 4, cols = 6; const int runCount = 1000000; const int distGroupCount = 10; const double intGroupSize = ((double)int.MaxValue + 1.0) / (double)distGroupCount; - RandomProportional randObj = new RandomProportional(); + RandomProportional randObj = new(); - int[ ] intCounts = new int[ distGroupCount ]; - int[ ] realCounts = new int[ distGroupCount ]; + int[] intCounts = new int[distGroupCount]; + int[] realCounts = new int[distGroupCount]; Console.WriteLine( "\nThe derived RandomProportional class overrides " + @@ -49,7 +43,7 @@ static void Main() for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) - Console.Write("{0,12:F8}", randObj.NextDouble()); + Console.Write($"{randObj.NextDouble(),12:F8}"); Console.WriteLine(); } @@ -61,7 +55,7 @@ static void Main() for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) - Console.Write("{0,12}", randObj.Next()); + Console.Write($"{randObj.Next(),12}"); Console.WriteLine(); } @@ -71,33 +65,22 @@ static void Main() "into {1} equal value ranges. This \n" + "is the count of values in each range:\n", runCount, distGroupCount); - Console.WriteLine( - "{0,21}{1,10}{2,20}{3,10}", "Integer Range", - "Count", "Double Range", "Count"); - Console.WriteLine( - "{0,21}{1,10}{2,20}{3,10}", "-------------", - "-----", "------------", "-----"); + Console.WriteLine($"{"Integer Range",21}{"Count",10}{"Double Range",20}{"Count",10}"); + Console.WriteLine($"{"-------------",21}{"-----",10}{"------------",20}{"-----",10}"); // Generate random integers and doubles, and then count // them by group. for (int i = 0; i < runCount; i++) { - intCounts[ (int)((double)randObj.Next() / - intGroupSize) ]++; - realCounts[ (int)(randObj.NextDouble() * - (double)distGroupCount) ]++; + intCounts[(int)((double)randObj.Next() / + intGroupSize)]++; + realCounts[(int)(randObj.NextDouble() * + (double)distGroupCount)]++; } // Display the count of each group. for (int i = 0; i < distGroupCount; i++) - Console.WriteLine( - "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}", - (int)((double)i * intGroupSize), - (int)((double)(i + 1) * intGroupSize - 1.0), - intCounts[ i ], - ((double)i) / (double)distGroupCount, - ((double)(i + 1)) / (double)distGroupCount, - realCounts[ i ]); + Console.WriteLine($"{(int)((double)i * intGroupSize),10}-{(int)((double)(i + 1) * intGroupSize - 1.0),10}{intCounts[i],10:N0}{((double)i) / (double)distGroupCount,12:N5}-{((double)(i + 1)) / (double)distGroupCount,7:N5}{realCounts[i],10:N0}"); } } diff --git a/snippets/csharp/System/Random/NextBytes/source.cs b/snippets/csharp/System/Random/NextBytes/source.cs index 5f05b24328f..d340bd97112 100644 --- a/snippets/csharp/System/Random/NextBytes/source.cs +++ b/snippets/csharp/System/Random/NextBytes/source.cs @@ -5,12 +5,12 @@ public class Example public static void Main() { // - Random rnd = new Random(); - Byte[] b = new Byte[10]; + Random rnd = new(); + byte[] b = new byte[10]; rnd.NextBytes(b); Console.WriteLine("The Random bytes are: "); for (int i = 0; i <= b.GetUpperBound(0); i++) - Console.WriteLine("{0}: {1}", i, b[i]); + Console.WriteLine($"{i}: {b[i]}"); // The example displays output similar to the following: // The Random bytes are: diff --git a/snippets/csharp/System/Random/NextDouble/nextdouble1.cs b/snippets/csharp/System/Random/NextDouble/nextdouble1.cs index c4b0b13e099..b6204b8c8bd 100644 --- a/snippets/csharp/System/Random/NextDouble/nextdouble1.cs +++ b/snippets/csharp/System/Random/NextDouble/nextdouble1.cs @@ -2,33 +2,34 @@ public class Example { - public static void Main() - { - // - int[] frequency = new int[10]; - double number; - Random rnd = new Random(); + public static void Main() + { + // + int[] frequency = new int[10]; + double number; + Random rnd = new(); - for (int ctr = 0; ctr <= 99; ctr++) { - number = rnd.NextDouble(); - frequency[(int) Math.Floor(number*10)] ++; - } - Console.WriteLine("Distribution of Random Numbers:"); - for (int ctr = frequency.GetLowerBound(0); ctr <= frequency.GetUpperBound(0); ctr++) - Console.WriteLine("0.{0}0-0.{0}9 {1}", ctr, frequency[ctr]); + for (int ctr = 0; ctr <= 99; ctr++) + { + number = rnd.NextDouble(); + frequency[(int)Math.Floor(number * 10)]++; + } + Console.WriteLine("Distribution of Random Numbers:"); + for (int ctr = frequency.GetLowerBound(0); ctr <= frequency.GetUpperBound(0); ctr++) + Console.WriteLine("0.{0}0-0.{0}9 {1}", ctr, frequency[ctr]); - // The following example displays output similar to the following: - // Distribution of Random Numbers: - // 0.00-0.09 16 - // 0.10-0.19 8 - // 0.20-0.29 8 - // 0.30-0.39 11 - // 0.40-0.49 9 - // 0.50-0.59 6 - // 0.60-0.69 13 - // 0.70-0.79 6 - // 0.80-0.89 9 - // 0.90-0.99 14 - // - } + // The following example displays output similar to the following: + // Distribution of Random Numbers: + // 0.00-0.09 16 + // 0.10-0.19 8 + // 0.20-0.29 8 + // 0.30-0.39 11 + // 0.40-0.49 9 + // 0.50-0.59 6 + // 0.60-0.69 13 + // 0.70-0.79 6 + // 0.80-0.89 9 + // 0.90-0.99 14 + // + } } diff --git a/snippets/csharp/System/Random/Overview/Next2.cs b/snippets/csharp/System/Random/Overview/Next2.cs index 123ae011b2c..6571e692ebd 100644 --- a/snippets/csharp/System/Random/Overview/Next2.cs +++ b/snippets/csharp/System/Random/Overview/Next2.cs @@ -2,50 +2,50 @@ public class Example9 { - public static void Main() - { - // - Random rnd = new(); + public static void Main() + { + // + Random rnd = new(); - Console.WriteLine("\n20 random integers from -100 to 100:"); - for (int ctr = 1; ctr <= 20; ctr++) - { - Console.Write("{0,6}", rnd.Next(-100, 101)); - if (ctr % 5 == 0) Console.WriteLine(); - } + Console.WriteLine("\n20 random integers from -100 to 100:"); + for (int ctr = 1; ctr <= 20; ctr++) + { + Console.Write($"{rnd.Next(-100, 101),6}"); + if (ctr % 5 == 0) Console.WriteLine(); + } - Console.WriteLine("\n20 random integers from 1000 to 10000:"); - for (int ctr = 1; ctr <= 20; ctr++) - { - Console.Write("{0,8}", rnd.Next(1000, 10001)); - if (ctr % 5 == 0) Console.WriteLine(); - } + Console.WriteLine("\n20 random integers from 1000 to 10000:"); + for (int ctr = 1; ctr <= 20; ctr++) + { + Console.Write($"{rnd.Next(1000, 10001),8}"); + if (ctr % 5 == 0) Console.WriteLine(); + } - Console.WriteLine("\n20 random integers from 1 to 10:"); - for (int ctr = 1; ctr <= 20; ctr++) - { - Console.Write("{0,6}", rnd.Next(1, 11)); - if (ctr % 5 == 0) Console.WriteLine(); - } + Console.WriteLine("\n20 random integers from 1 to 10:"); + for (int ctr = 1; ctr <= 20; ctr++) + { + Console.Write($"{rnd.Next(1, 11),6}"); + if (ctr % 5 == 0) Console.WriteLine(); + } - // The example displays output similar to the following: - // 20 random integers from -100 to 100: - // 65 -95 -10 90 -35 - // -83 -16 -15 -19 41 - // -67 -93 40 12 62 - // -80 -95 67 -81 -21 - // - // 20 random integers from 1000 to 10000: - // 4857 9897 4405 6606 1277 - // 9238 9113 5151 8710 1187 - // 2728 9746 1719 3837 3736 - // 8191 6819 4923 2416 3028 - // - // 20 random integers from 1 to 10: - // 9 8 5 9 9 - // 9 1 2 3 8 - // 1 4 8 10 5 - // 9 7 9 10 5 - // - } + // The example displays output similar to the following: + // 20 random integers from -100 to 100: + // 65 -95 -10 90 -35 + // -83 -16 -15 -19 41 + // -67 -93 40 12 62 + // -80 -95 67 -81 -21 + // + // 20 random integers from 1000 to 10000: + // 4857 9897 4405 6606 1277 + // 9238 9113 5151 8710 1187 + // 2728 9746 1719 3837 3736 + // 8191 6819 4923 2416 3028 + // + // 20 random integers from 1 to 10: + // 9 8 5 9 9 + // 9 1 2 3 8 + // 1 4 8 10 5 + // 9 7 9 10 5 + // + } } diff --git a/snippets/csharp/System/Random/Overview/Random2.cs b/snippets/csharp/System/Random/Overview/Random2.cs index c95f92491d6..66a60fdea13 100644 --- a/snippets/csharp/System/Random/Overview/Random2.cs +++ b/snippets/csharp/System/Random/Overview/Random2.cs @@ -13,37 +13,37 @@ public static void Main() rand.NextBytes(bytes); Console.WriteLine("Five random byte values:"); foreach (byte byteValue in bytes) - Console.Write("{0, 5}", byteValue); + Console.Write($"{byteValue,5}"); Console.WriteLine(); // Generate and display 5 random integers. Console.WriteLine("Five random integer values:"); for (int ctr = 0; ctr <= 4; ctr++) - Console.Write("{0,15:N0}", rand.Next()); + Console.Write($"{rand.Next(),15:N0}"); Console.WriteLine(); // Generate and display 5 random integers between 0 and 100. Console.WriteLine("Five random integers between 0 and 100:"); for (int ctr = 0; ctr <= 4; ctr++) - Console.Write("{0,8:N0}", rand.Next(101)); + Console.Write($"{rand.Next(101),8:N0}"); Console.WriteLine(); // Generate and display 5 random integers from 50 to 100. Console.WriteLine("Five random integers between 50 and 100:"); for (int ctr = 0; ctr <= 4; ctr++) - Console.Write("{0,8:N0}", rand.Next(50, 101)); + Console.Write($"{rand.Next(50, 101),8:N0}"); Console.WriteLine(); // Generate and display 5 random floating point values from 0 to 1. Console.WriteLine("Five Doubles."); for (int ctr = 0; ctr <= 4; ctr++) - Console.Write("{0,8:N3}", rand.NextDouble()); + Console.Write($"{rand.NextDouble(),8:N3}"); Console.WriteLine(); // Generate and display 5 random floating point values from 0 to 5. Console.WriteLine("Five Doubles between 0 and 5."); for (int ctr = 0; ctr <= 4; ctr++) - Console.Write("{0,8:N3}", rand.NextDouble() * 5); + Console.Write($"{rand.NextDouble() * 5,8:N3}"); // The example displays output like the following: // Five random byte values: diff --git a/snippets/csharp/System/Random/Overview/booleans1.cs b/snippets/csharp/System/Random/Overview/booleans1.cs index 8c2a2a9ed54..078734bfcad 100644 --- a/snippets/csharp/System/Random/Overview/booleans1.cs +++ b/snippets/csharp/System/Random/Overview/booleans1.cs @@ -18,12 +18,8 @@ public static void Main() else totalFalse++; } - Console.WriteLine("Number of true values: {0,7:N0} ({1:P3})", - totalTrue, - ((double)totalTrue) / (totalTrue + totalFalse)); - Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", - totalFalse, - ((double)totalFalse) / (totalTrue + totalFalse)); + Console.WriteLine($"Number of true values: {totalTrue,7:N0} ({((double)totalTrue) / (totalTrue + totalFalse):P3})"); + Console.WriteLine($"Number of false values: {totalFalse,7:N0} ({((double)totalFalse) / (totalTrue + totalFalse):P3})"); } } @@ -31,15 +27,9 @@ public class BooleanGenerator { Random rnd; - public BooleanGenerator() - { - rnd = new Random(); - } + public BooleanGenerator() => rnd = new(); - public bool NextBoolean() - { - return rnd.Next(0, 2) == 1; - } + public bool NextBoolean() => rnd.Next(0, 2) == 1; } // The example displays output like the following: // Number of true values: 500,004 (50.000 %) diff --git a/snippets/csharp/System/Random/Overview/booleans2.cs b/snippets/csharp/System/Random/Overview/booleans2.cs index 70483c07c19..f892675e01c 100644 --- a/snippets/csharp/System/Random/Overview/booleans2.cs +++ b/snippets/csharp/System/Random/Overview/booleans2.cs @@ -18,17 +18,10 @@ public static void Main() else totalFalse++; } - Console.WriteLine("Number of true values: {0,7:N0} ({1:P3})", - totalTrue, - ((double)totalTrue) / (totalTrue + totalFalse)); - Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})", - totalFalse, - ((double)totalFalse) / (totalTrue + totalFalse)); + Console.WriteLine($"Number of true values: {totalTrue,7:N0} ({((double)totalTrue) / (totalTrue + totalFalse):P3})"); + Console.WriteLine($"Number of false values: {totalFalse,7:N0} ({((double)totalFalse) / (totalTrue + totalFalse):P3})"); - bool NextBoolean() - { - return rnd.Next(0, 2) == 1; - } + bool NextBoolean() => rnd.Next(0, 2) == 1; // The example displays output like the following: // Number of true values: 499,777 (49.978 %) diff --git a/snippets/csharp/System/Random/Overview/doublerange1.cs b/snippets/csharp/System/Random/Overview/doublerange1.cs index a5098632c36..bf80c8915c4 100644 --- a/snippets/csharp/System/Random/Overview/doublerange1.cs +++ b/snippets/csharp/System/Random/Overview/doublerange1.cs @@ -19,11 +19,9 @@ public static void Main() count[(int)(number / ONE_TENTH)]++; } // Display breakdown by range. - Console.WriteLine("{0,28} {1,32} {2,7}\n", "Range", "Count", "Pct."); + Console.WriteLine($"{"Range",28} {"Count",32} {"Pct.",7}\n"); for (int ctr = 0; ctr <= 9; ctr++) - Console.WriteLine("{0,25:N0}-{1,25:N0} {2,8:N0} {3,7:P2}", ctr * ONE_TENTH, - ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue, - count[ctr], count[ctr] / 20000000.0); + Console.WriteLine($"{ctr * ONE_TENTH,25:N0}-{(ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue),25:N0} {count[ctr],8:N0} {count[ctr] / 20000000.0,7:P2}"); // The example displays output like the following: // Range Count Pct. diff --git a/snippets/csharp/System/Random/Overview/doublerange3.cs b/snippets/csharp/System/Random/Overview/doublerange3.cs index 92c4a7ebe33..53460f7617e 100644 --- a/snippets/csharp/System/Random/Overview/doublerange3.cs +++ b/snippets/csharp/System/Random/Overview/doublerange3.cs @@ -18,9 +18,7 @@ public static void Main() for (int ctr = 0; ctr <= 9; ctr++) { double lowerRange = 10 + ctr * .1; - Console.WriteLine("{0:N1} to {1:N1}: {2,8:N0} ({3,7:P2})", - lowerRange, lowerRange + .1, range[ctr], - range[ctr] / 1000000.0); + Console.WriteLine($"{lowerRange:N1} to {lowerRange + .1:N1}: {range[ctr],8:N0} ({range[ctr] / 1000000.0,7:P2})"); } // The example displays output like the following: diff --git a/snippets/csharp/System/Random/Overview/long1.cs b/snippets/csharp/System/Random/Overview/long1.cs index 10f76c4b328..5ae2f401f6f 100644 --- a/snippets/csharp/System/Random/Overview/long1.cs +++ b/snippets/csharp/System/Random/Overview/long1.cs @@ -19,11 +19,9 @@ public static void Main() count[(int)(number / ONE_TENTH)]++; } // Display breakdown by range. - Console.WriteLine("{0,28} {1,32} {2,7}\n", "Range", "Count", "Pct."); + Console.WriteLine($"{"Range",28} {"Count",32} {"Pct.",7}\n"); for (int ctr = 0; ctr <= 9; ctr++) - Console.WriteLine("{0,25:N0}-{1,25:N0} {2,8:N0} {3,7:P2}", ctr * ONE_TENTH, - ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue, - count[ctr], count[ctr] / 20000000.0); + Console.WriteLine($"{ctr * ONE_TENTH,25:N0}-{(ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue),25:N0} {count[ctr],8:N0} {count[ctr] / 20000000.0,7:P2}"); // The example displays output like the following: // Range Count Pct. diff --git a/snippets/csharp/System/Random/Overview/next.cs b/snippets/csharp/System/Random/Overview/next.cs index 39ac1861c06..fbf4eb1efe3 100644 --- a/snippets/csharp/System/Random/Overview/next.cs +++ b/snippets/csharp/System/Random/Overview/next.cs @@ -4,7 +4,7 @@ public class RandomNextDemo { static void Main() - { + { // Console.WriteLine( """ @@ -20,7 +20,7 @@ bounds. Note the effect\nthat the various combinations of bounds have on the sequences. """ ); - + NoBoundsRandoms(234); UpperBoundRandoms(234, int.MaxValue); diff --git a/snippets/csharp/System/Random/Overview/threadsafeex1.cs b/snippets/csharp/System/Random/Overview/threadsafeex1.cs index ea88b8c3e9d..9e86f956c27 100644 --- a/snippets/csharp/System/Random/Overview/threadsafeex1.cs +++ b/snippets/csharp/System/Random/Overview/threadsafeex1.cs @@ -16,11 +16,11 @@ public class Example18 public Example18() { - s_rand = new Random(); - s_randLock = new object(); - s_numericLock = new object(); - s_countdown = new CountdownEvent(1); - s_source = new CancellationTokenSource(); + s_rand = new(); + s_randLock = new(); + s_numericLock = new(); + s_countdown = new(1); + s_source = new(); } public static void Main() diff --git a/snippets/csharp/System/Random/Overview/threadsafeex2.cs b/snippets/csharp/System/Random/Overview/threadsafeex2.cs index 9f7ef357321..85bd6a4b84a 100644 --- a/snippets/csharp/System/Random/Overview/threadsafeex2.cs +++ b/snippets/csharp/System/Random/Overview/threadsafeex2.cs @@ -14,10 +14,10 @@ public class Example19 public Example19() { - s_rand = new Random(); - s_randLock = new object(); - s_numericLock = new object(); - s_source = new CancellationTokenSource(); + s_rand = new(); + s_randLock = new(); + s_numericLock = new(); + s_source = new(); } public static async Task Main() @@ -65,10 +65,10 @@ private async Task Execute() } // Show result. - Console.WriteLine("Task {0} finished execution.", taskNo); - Console.WriteLine("Random numbers generated: {0:N0}", taskCtr); - Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal); - Console.WriteLine("Random number mean: {0:N4}\n", taskTotal / taskCtr); + Console.WriteLine($"Task {taskNo} finished execution."); + Console.WriteLine($"Random numbers generated: {taskCtr:N0}"); + Console.WriteLine($"Sum of random numbers: {taskTotal:N2}"); + Console.WriteLine($"Random number mean: {taskTotal / taskCtr:N4}\n"); // Update overall totals. lock (s_numericLock) @@ -91,9 +91,9 @@ private async Task Execute() foreach (Exception inner in e.InnerExceptions) { if (inner is TaskCanceledException canc) - Console.WriteLine("Task #{0} cancelled.", canc.Task.Id); + Console.WriteLine($"Task #{canc.Task.Id} cancelled."); else - Console.WriteLine("Exception: {0}", inner.GetType().Name); + Console.WriteLine($"Exception: {inner.GetType().Name}"); } } finally diff --git a/snippets/csharp/System/Random/Overview/unique.cs b/snippets/csharp/System/Random/Overview/unique.cs index dcc2da0789f..7403d1d422b 100644 --- a/snippets/csharp/System/Random/Overview/unique.cs +++ b/snippets/csharp/System/Random/Overview/unique.cs @@ -13,11 +13,11 @@ public static void Main() Console.WriteLine("\nThe first random number generator:"); for (int ctr = 1; ctr <= 10; ctr++) - Console.WriteLine(" {0}", rnd1.Next()); + Console.WriteLine($" {rnd1.Next()}"); Console.WriteLine("\nThe second random number generator:"); for (int ctr = 1; ctr <= 10; ctr++) - Console.WriteLine(" {0}", rnd2.Next()); + Console.WriteLine($" {rnd2.Next()}"); } } // The example displays output like the following: diff --git a/snippets/csharp/System/Random/Overview/uniquearray1.cs b/snippets/csharp/System/Random/Overview/uniquearray1.cs index 3d570b52193..8e05e57dec6 100644 --- a/snippets/csharp/System/Random/Overview/uniquearray1.cs +++ b/snippets/csharp/System/Random/Overview/uniquearray1.cs @@ -7,10 +7,7 @@ public class Card public Suit Suit; public FaceValue FaceValue; - public override string ToString() - { - return string.Format("{0:F} of {1:F}", FaceValue, Suit); - } + public override string ToString() => $"{FaceValue:F} of {Suit:F}"; } public enum Suit { Hearts, Diamonds, Spades, Clubs }; @@ -36,7 +33,7 @@ public class Dealer public Dealer() { - _rnd = new Random(); + _rnd = new(); // Initialize the deck. int deckCtr = 0; foreach (object suit in Enum.GetValues(typeof(Suit))) @@ -97,7 +94,7 @@ private static void ShowCards(Card[] cards) { foreach (Card card in cards) if (card != null) - Console.WriteLine("{0} of {1}", card.FaceValue, card.Suit); + Console.WriteLine($"{card.FaceValue} of {card.Suit}"); } } // The example displays output like the following: diff --git a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs index 0a696d41bb1..f1f685688b8 100644 --- a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs +++ b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs @@ -1,4 +1,4 @@ -using System; +using System; // Note: you must compile this sample using the unsafe flag. // From the command line, type the following: csc sample.cs /unsafe @@ -34,10 +34,7 @@ public static unsafe void Main() } } - private static int[] CreateInt32Array() - { - return new int[] { 100, 200, 300, 400, 500 }; - } + private static int[] CreateInt32Array() =>[ 100, 200, 300, 400, 500 ]; } // The example displays the following output: diff --git a/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs b/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs index 3a4def83465..ce060d61ac7 100644 --- a/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs +++ b/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs @@ -1,41 +1,35 @@ // using System; -using System.Reflection; + public class MyClass1 { - private int x=0; - public int MyMethod() - { - return x; - } + private int x = 0; + public int MyMethod() => x; } public class MyClass2 { public static void Main() { - MyClass1 myClass1 = new MyClass1(); + MyClass1 myClass1 = new(); // Get the RuntimeTypeHandle from an object. RuntimeTypeHandle myRTHFromObject = Type.GetTypeHandle(myClass1); // Get the RuntimeTypeHandle from a type. RuntimeTypeHandle myRTHFromType = typeof(MyClass1).TypeHandle; - Console.WriteLine("\nmyRTHFromObject.Value: {0}", myRTHFromObject.Value); - Console.WriteLine("myRTHFromObject.GetType(): {0}", myRTHFromObject.GetType()); + Console.WriteLine($"\nmyRTHFromObject.Value: {myRTHFromObject.Value}"); + Console.WriteLine($"myRTHFromObject.GetType(): {myRTHFromObject.GetType()}"); Console.WriteLine("Get the type back from the handle..."); - Console.WriteLine("Type.GetTypeFromHandle(myRTHFromObject): {0}", - Type.GetTypeFromHandle(myRTHFromObject)); + Console.WriteLine($"Type.GetTypeFromHandle(myRTHFromObject): {Type.GetTypeFromHandle(myRTHFromObject)}"); - Console.WriteLine("\nmyRTHFromObject.Equals(myRTHFromType): {0}", - myRTHFromObject.Equals(myRTHFromType)); + Console.WriteLine($"\nmyRTHFromObject.Equals(myRTHFromType): {myRTHFromObject.Equals(myRTHFromType)}"); - Console.WriteLine("\nmyRTHFromType.Value: {0}", myRTHFromType.Value); - Console.WriteLine("myRTHFromType.GetType(): {0}", myRTHFromType.GetType()); + Console.WriteLine($"\nmyRTHFromType.Value: {myRTHFromType.Value}"); + Console.WriteLine($"myRTHFromType.GetType(): {myRTHFromType.GetType()}"); Console.WriteLine("Get the type back from the handle..."); - Console.WriteLine("Type.GetTypeFromHandle(myRTHFromType): {0}", - Type.GetTypeFromHandle(myRTHFromType)); + Console.WriteLine($"Type.GetTypeFromHandle(myRTHFromType): {Type.GetTypeFromHandle(myRTHFromType)}"); } }