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 +//