diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs index 48fdf3dfce218..0c00c32649e5a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Class1 { @@ -44,19 +44,13 @@ private static void ConvertUsingDateTime() // Convert UTC to DateTime value sourceTime = new DateTimeOffset(baseTime, TimeSpan.Zero); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); // Convert local time to DateTime value sourceTime = new DateTimeOffset(baseTime, TimeZoneInfo.Local.GetUtcOffset(baseTime)); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); // Convert Central Standard Time to a DateTime value try @@ -64,10 +58,7 @@ private static void ConvertUsingDateTime() TimeSpan offset = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(baseTime); sourceTime = new DateTimeOffset(baseTime, offset); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); } catch (TimeZoneNotFoundException) { @@ -85,10 +76,7 @@ private static void ConvertUtcTime() // DateTimeOffset utcTime1 = new DateTimeOffset(2008, 6, 19, 7, 0, 0, TimeSpan.Zero); DateTime utcTime2 = utcTime1.UtcDateTime; - Console.WriteLine("{0} converted to {1} {2}", - utcTime1, - utcTime2, - utcTime2.Kind); + Console.WriteLine($"{utcTime1} converted to {utcTime2} {utcTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +00:00 converted to 6/19/2008 7:00:00 AM Utc // @@ -104,10 +92,7 @@ private static void ConvertLocalTime() if (utcTime1.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(utcTime1.DateTime))) utcTime2 = DateTime.SpecifyKind(utcTime2, DateTimeKind.Local); - Console.WriteLine("{0} converted to {1} {2}", - utcTime1, - utcTime2, - utcTime2.Kind); + Console.WriteLine($"{utcTime1} converted to {utcTime2} {utcTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local // @@ -134,28 +119,19 @@ private static void CallConversionFunction() // Convert UTC time DateTimeOffset utcTime = new DateTimeOffset(timeComponent, TimeSpan.Zero); returnedDate = ConvertFromDateTimeOffset(utcTime); - Console.WriteLine("{0} converted to {1} {2}", - utcTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{utcTime} converted to {returnedDate} {returnedDate.Kind}"); // Convert local time DateTimeOffset localTime = new DateTimeOffset(timeComponent, TimeZoneInfo.Local.GetUtcOffset(timeComponent)); returnedDate = ConvertFromDateTimeOffset(localTime); - Console.WriteLine("{0} converted to {1} {2}", - localTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{localTime} converted to {returnedDate} {returnedDate.Kind}"); // Convert Central Standard Time DateTimeOffset cstTime = new DateTimeOffset(timeComponent, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(timeComponent)); returnedDate = ConvertFromDateTimeOffset(cstTime); - Console.WriteLine("{0} converted to {1} {2}", - cstTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{cstTime} converted to {returnedDate} {returnedDate.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +00:00 converted to 6/19/2008 7:00:00 AM Utc // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local @@ -169,10 +145,7 @@ private static void ConvertUtcToDateTimeOffset() DateTime utcTime1 = new DateTime(2008, 6, 19, 7, 0, 0); utcTime1 = DateTime.SpecifyKind(utcTime1, DateTimeKind.Utc); DateTimeOffset utcTime2 = utcTime1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - utcTime1, - utcTime1.Kind, - utcTime2); + Console.WriteLine($"Converted {utcTime1} {utcTime1.Kind} to a DateTimeOffset value of {utcTime2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Utc to a DateTimeOffset value of 6/19/2008 7:00:00 AM +00:00 // @@ -184,10 +157,7 @@ private static void ConvertLocalToDateTimeOffset() DateTime localTime1 = new DateTime(2008, 6, 19, 7, 0, 0); localTime1 = DateTime.SpecifyKind(localTime1, DateTimeKind.Local); DateTimeOffset localTime2 = localTime1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - localTime1, - localTime1.Kind, - localTime2); + Console.WriteLine($"Converted {localTime1} {localTime1.Kind} to a DateTimeOffset value of {localTime2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Local to a DateTimeOffset value of 6/19/2008 7:00:00 AM -07:00 // @@ -198,10 +168,7 @@ private static void ConvertUnspecifiedToDateTimeOffset1() // DateTime time1 = new DateTime(2008, 6, 19, 7, 0, 0); // Kind is DateTimeKind.Unspecified DateTimeOffset time2 = time1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - time1, - time1.Kind, - time2); + Console.WriteLine($"Converted {time1} {time1.Kind} to a DateTimeOffset value of {time2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Unspecified to a DateTimeOffset value of 6/19/2008 7:00:00 AM -07:00 // @@ -215,10 +182,7 @@ private static void ConvertUnspecifiedToDateTimeOffset2() { DateTimeOffset time2 = new DateTimeOffset(time1, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(time1)); - Console.WriteLine("Converted {0} {1} to a DateTime value of {2}", - time1, - time1.Kind, - time2); + Console.WriteLine($"Converted {time1} {time1.Kind} to a DateTime value of {time2}"); } // Handle exception if time zone is not defined in registry catch (TimeZoneNotFoundException) @@ -238,10 +202,7 @@ private static void ConvertUsingLocalTimeProperty1() TimeZoneInfo.Local.GetUtcOffset(sourceDate)); DateTime localTime2 = localTime1.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - localTime1, - localTime2, - localTime2.Kind); + Console.WriteLine($"{localTime1} converted to {localTime2} {localTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local // @@ -257,19 +218,13 @@ private static void ConvertUsingLocalTimeProperty2() originalDate = new DateTimeOffset(2008, 6, 18, 7, 0, 0, new TimeSpan(-5, 0, 0)); localDate = originalDate.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalDate, - localDate, - localDate.Kind); + Console.WriteLine($"{originalDate} converted to {localDate} {localDate.Kind}"); // Convert time originating in a different time zone // so local time zone's adjustment rules are applied originalDate = new DateTimeOffset(2007, 11, 4, 4, 0, 0, new TimeSpan(-5, 0, 0)); localDate = originalDate.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalDate, - localDate, - localDate.Kind); + Console.WriteLine($"{originalDate} converted to {localDate} {localDate.Kind}"); // The example displays the following output to the console, // when you run it on a machine that is set to Pacific Time (US & Canada): // 6/18/2008 7:00:00 AM -05:00 converted to 6/18/2008 5:00:00 AM Local @@ -282,10 +237,7 @@ private static void PerformUtcAndTypeConversion() // DateTimeOffset originalTime = new DateTimeOffset(2008, 6, 19, 7, 0, 0, new TimeSpan(5, 0, 0)); DateTime utcTime = originalTime.UtcDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalTime, - utcTime, - utcTime.Kind); + Console.WriteLine($"{originalTime} converted to {utcTime} {utcTime.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +05:00 converted to 6/19/2008 2:00:00 AM Utc // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs index 79239e00df00f..e0114984f8ed5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs @@ -4,40 +4,40 @@ public class TimeOffsets { - public static void Main() - { - DateTime thisDate = new DateTime(2007, 3, 10, 0, 0, 0); - DateTime dstDate = new DateTime(2007, 6, 10, 0, 0, 0); - DateTimeOffset thisTime; + public static void Main() + { + DateTime thisDate = new DateTime(2007, 3, 10, 0, 0, 0); + DateTime dstDate = new DateTime(2007, 6, 10, 0, 0, 0); + DateTimeOffset thisTime; - thisTime = new DateTimeOffset(dstDate, new TimeSpan(-7, 0, 0)); - ShowPossibleTimeZones(thisTime); + thisTime = new DateTimeOffset(dstDate, new TimeSpan(-7, 0, 0)); + ShowPossibleTimeZones(thisTime); - thisTime = new DateTimeOffset(thisDate, new TimeSpan(-6, 0, 0)); - ShowPossibleTimeZones(thisTime); + thisTime = new DateTimeOffset(thisDate, new TimeSpan(-6, 0, 0)); + ShowPossibleTimeZones(thisTime); - thisTime = new DateTimeOffset(thisDate, new TimeSpan(+1, 0, 0)); - ShowPossibleTimeZones(thisTime); - } + thisTime = new DateTimeOffset(thisDate, new TimeSpan(+1, 0, 0)); + ShowPossibleTimeZones(thisTime); + } - private static void ShowPossibleTimeZones(DateTimeOffset offsetTime) - { - TimeSpan offset = offsetTime.Offset; - ReadOnlyCollection timeZones; + private static void ShowPossibleTimeZones(DateTimeOffset offsetTime) + { + TimeSpan offset = offsetTime.Offset; + ReadOnlyCollection timeZones; - Console.WriteLine("{0} could belong to the following time zones:", - offsetTime.ToString()); - // Get all time zones defined on local system - timeZones = TimeZoneInfo.GetSystemTimeZones(); - // Iterate time zones - foreach (TimeZoneInfo timeZone in timeZones) - { - // Compare offset with offset for that date in that time zone - if (timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)) - Console.WriteLine(" {0}", timeZone.DisplayName); - } - Console.WriteLine(); - } + Console.WriteLine("{0} could belong to the following time zones:", + offsetTime.ToString()); + // Get all time zones defined on local system + timeZones = TimeZoneInfo.GetSystemTimeZones(); + // Iterate time zones + foreach (TimeZoneInfo timeZone in timeZones) + { + // Compare offset with offset for that date in that time zone + if (timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)) + Console.WriteLine($" {timeZone.DisplayName}"); + } + Console.WriteLine(); + } } // This example displays the following output to the console: // 6/10/2007 12:00:00 AM -07:00 could belong to the following time zones: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs index 4feaa27cce964..0264f0cf1f6fd 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs @@ -1,30 +1,30 @@ // using System; -public enum TimeComparison +public enum TimeComparison2 { - EarlierThan = -1, - TheSameAs = 0, - LaterThan = 1 + EarlierThan = -1, + TheSameAs = 0, + LaterThan = 1 } public class DateManipulation { - public static void Main() - { - DateTime localTime = DateTime.Now; - DateTime utcTime = DateTime.UtcNow; + public static void Main() + { + DateTime localTime = DateTime.Now; + DateTime utcTime = DateTime.UtcNow; - Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", - localTime.Kind, - utcTime.Kind, - (localTime - utcTime).Hours, - (localTime - utcTime).Minutes); - Console.WriteLine("The {0} time is {1} the {2} time.", - localTime.Kind, - Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime)), - utcTime.Kind); - } + Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", + localTime.Kind, + utcTime.Kind, + (localTime - utcTime).Hours, + (localTime - utcTime).Minutes); + Console.WriteLine("The {0} time is {1} the {2} time.", + localTime.Kind, + Enum.GetName(typeof(TimeComparison2), localTime.CompareTo(utcTime)), + utcTime.Kind); + } } // If run in the U.S. Pacific Standard Time zone, the example displays // the following output to the console: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs index e26881f249e06..b64102cc183f9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs @@ -3,24 +3,24 @@ public enum TimeComparison { - EarlierThan = -1, - TheSameAs = 0, - LaterThan = 1 + EarlierThan = -1, + TheSameAs = 0, + LaterThan = 1 } public class DateTimeOffsetManipulation { - public static void Main() - { - DateTimeOffset localTime = DateTimeOffset.Now; - DateTimeOffset utcTime = DateTimeOffset.UtcNow; + public static void Main() + { + DateTimeOffset localTime = DateTimeOffset.Now; + DateTimeOffset utcTime = DateTimeOffset.UtcNow; - Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours", - (localTime - utcTime).Hours, - (localTime - utcTime).Minutes); - Console.WriteLine("The local time is {0} UTC.", - Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime))); - } + Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours", + (localTime - utcTime).Hours, + (localTime - utcTime).Minutes); + Console.WriteLine("The local time is {0} UTC.", + Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime))); + } } // Regardless of the local time zone, the example displays // the following output to the console: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs index f160104c70b2c..ffd074a57c276 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs @@ -3,30 +3,30 @@ public class IntervalArithmetic { - public static void Main() - { - DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); - const string tzName = "Central Standard Time"; - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + public static void Main() + { + DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); + const string tzName = "Central Standard Time"; + TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - // Instantiate DateTimeOffset value to have correct CST offset - try - { - DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, - TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime)); + // Instantiate DateTimeOffset value to have correct CST offset + try + { + DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, + TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime)); - // Add two and a half hours - DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours); - // Display result - Console.WriteLine("{0} + {1} hours = {2}", centralTime1, - twoAndAHalfHours.ToString(), - centralTime2); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("Unable to retrieve Central Standard Time zone information."); - } - } + // Add two and a half hours + DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours); + // Display result + Console.WriteLine("{0} + {1} hours = {2}", centralTime1, + twoAndAHalfHours.ToString(), + centralTime2); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve Central Standard Time zone information."); + } + } } // The example displays the following output to the console: // 3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 4:00:00 AM -06:00 diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs index 5ef61fcb6c681..1bbb333dd3bcd 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs @@ -3,35 +3,35 @@ public class TimeZoneAwareArithmetic { - public static void Main() - { - const string tzName = "Central Standard Time"; + public static void Main() + { + const string tzName = "Central Standard Time"; - DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); + TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - // Instantiate DateTimeOffset value to have correct CST offset - try - { - DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, - cst.GetUtcOffset(generalTime)); + // Instantiate DateTimeOffset value to have correct CST offset + try + { + DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, + cst.GetUtcOffset(generalTime)); - // Add two and a half hours - DateTimeOffset utcTime = centralTime1.ToUniversalTime(); - utcTime += twoAndAHalfHours; + // Add two and a half hours + DateTimeOffset utcTime = centralTime1.ToUniversalTime(); + utcTime += twoAndAHalfHours; - DateTimeOffset centralTime2 = TimeZoneInfo.ConvertTime(utcTime, cst); - // Display result - Console.WriteLine("{0} + {1} hours = {2}", centralTime1, - twoAndAHalfHours.ToString(), - centralTime2); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("Unable to retrieve Central Standard Time zone information."); - } - } + DateTimeOffset centralTime2 = TimeZoneInfo.ConvertTime(utcTime, cst); + // Display result + Console.WriteLine("{0} + {1} hours = {2}", centralTime1, + twoAndAHalfHours.ToString(), + centralTime2); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve Central Standard Time zone information."); + } + } } // The example displays the following output to the console: // 3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 5:00:00 AM -05:00 diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs index d61113912eb71..1bfaa417cca9e 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs @@ -1,57 +1,56 @@ // using System; -public struct TimeZoneTime +public struct TimeZoneTime2 { - public TimeZoneInfo TimeZone; - public DateTimeOffset Time; + public TimeZoneInfo TimeZone; + public DateTimeOffset Time; - public TimeZoneTime(TimeZoneInfo tz, DateTimeOffset time) - { - if (tz == null) - throw new ArgumentNullException("The time zone cannot be a null reference."); + public TimeZoneTime2(TimeZoneInfo tz, DateTimeOffset time) + { + ArgumentNullException.ThrowIfNull(tz); - this.TimeZone = tz; - this.Time = time; - } + TimeZone = tz; + Time = time; + } - public TimeZoneTime AddTime(TimeSpan interval) - { - // Convert time to UTC - DateTimeOffset utcTime = TimeZoneInfo.ConvertTime(this.Time, TimeZoneInfo.Utc); - // Add time interval to time - utcTime = utcTime.Add(interval); - // Convert time back to time in time zone - return new TimeZoneTime(this.TimeZone, TimeZoneInfo.ConvertTime(utcTime, this.TimeZone)); - } + public TimeZoneTime2 AddTime(TimeSpan interval) + { + // Convert time to UTC + DateTimeOffset utcTime = TimeZoneInfo.ConvertTime(Time, TimeZoneInfo.Utc); + // Add time interval to time + utcTime = utcTime.Add(interval); + // Convert time back to time in time zone + return new TimeZoneTime2(TimeZone, TimeZoneInfo.ConvertTime(utcTime, TimeZone)); + } } -public class TimeArithmetic +public class TimeArithmetic2 { - public const string tzName = "Central Standard Time"; + public const string tzName = "Central Standard Time"; - public static void Main() - { - try - { - TimeZoneTime cstTime1, cstTime2; + public static void Main() + { + try + { + TimeZoneTime2 cstTime1, cstTime2; - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - DateTime time1 = new DateTime(2008, 3, 9, 1, 30, 0); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); + DateTime time1 = new(2008, 3, 9, 1, 30, 0); + TimeSpan twoAndAHalfHours = new(2, 30, 0); - cstTime1 = new TimeZoneTime(cst, - new DateTimeOffset(time1, cst.GetUtcOffset(time1))); - cstTime2 = cstTime1.AddTime(twoAndAHalfHours); - Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, - twoAndAHalfHours.ToString(), - cstTime2.Time); - } - catch - { - Console.WriteLine("Unable to find {0}.", tzName); - } - } + cstTime1 = new TimeZoneTime2(cst, + new DateTimeOffset(time1, cst.GetUtcOffset(time1))); + cstTime2 = cstTime1.AddTime(twoAndAHalfHours); + Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, + twoAndAHalfHours.ToString(), + cstTime2.Time); + } + catch + { + Console.WriteLine($"Unable to find {tzName}."); + } + } } // @@ -59,7 +58,7 @@ public static void Main() // Define a structure for DateTime values for internal use only internal struct TimeWithTimeZone { - TimeZoneInfo TimeZone; - DateTime Time; + TimeZoneInfo TimeZone; + DateTime Time; } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs index fed84fa38aadd..b2ae41aac95b4 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs @@ -3,54 +3,53 @@ public struct TimeZoneTime { - public TimeZoneInfo TimeZone; - public DateTime Time; - - public TimeZoneTime(TimeZoneInfo tz, DateTime time) - { - if (tz == null) - throw new ArgumentNullException("The time zone cannot be a null reference."); - - this.TimeZone = tz; - this.Time = time; - } - - public TimeZoneTime AddTime(TimeSpan interval) - { - // Convert time to UTC - DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(this.Time, this.TimeZone); - // Add time interval to time - utcTime = utcTime.Add(interval); - // Convert time back to time in time zone - return new TimeZoneTime(this.TimeZone, TimeZoneInfo.ConvertTime(utcTime, - TimeZoneInfo.Utc, this.TimeZone)); - } + public TimeZoneInfo TimeZone; + public DateTime Time; + + public TimeZoneTime(TimeZoneInfo tz, DateTime time) + { + ArgumentNullException.ThrowIfNull(tz); + + TimeZone = tz; + Time = time; + } + + public TimeZoneTime AddTime(TimeSpan interval) + { + // Convert time to UTC + DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(Time, TimeZone); + // Add time interval to time + utcTime = utcTime.Add(interval); + // Convert time back to time in time zone + return new TimeZoneTime(TimeZone, TimeZoneInfo.ConvertTime(utcTime, + TimeZoneInfo.Utc, TimeZone)); + } } public class TimeArithmetic { - public const string tzName = "Central Standard Time"; - - public static void Main() - { - try - { - TimeZoneTime cstTime1, cstTime2; - - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - DateTime time1 = new DateTime(2008, 3, 9, 1, 30, 0); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - - cstTime1 = new TimeZoneTime(cst, time1); - cstTime2 = cstTime1.AddTime(twoAndAHalfHours); - Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, - twoAndAHalfHours.ToString(), - cstTime2.Time); - } - catch - { - Console.WriteLine("Unable to find {0}.", tzName); - } - } + public const string TzName = "Central Standard Time"; + + public static void Main() + { + try + { + TimeZoneTime cstTime1, cstTime2; + + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(TzName); + DateTime time1 = new(2008, 3, 9, 1, 30, 0); + TimeSpan twoAndAHalfHours = new(2, 30, 0); + + cstTime1 = new TimeZoneTime(cst, time1); + cstTime2 = cstTime1.AddTime(twoAndAHalfHours); + Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, + twoAndAHalfHours.ToString(), + cstTime2.Time); + } + catch + { + Console.WriteLine($"Unable to find {TzName}."); + } + } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs index 376bd86b6b9db..28bdbc622399a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs @@ -4,415 +4,424 @@ public class Class1 { public static void Main() { - ShowSchedule(); - Console.WriteLine("----------"); - ShowStartOfWorkWeek(); - Console.WriteLine("----------"); - ShowShiftStartTimes(); - Console.WriteLine("----------"); - ShowQuarters(); - Console.WriteLine("----------"); - DisplayTimes(); - Console.WriteLine("----------"); - ShowLegalLicenseAge(); - Console.WriteLine("----------"); - CompareForEquality1(); - Console.WriteLine("----------"); - CompareForEquality2(); - Console.WriteLine("----------"); - CompareForEquality3(); - Console.WriteLine("----------"); - CompareExactly(); - Console.WriteLine("----------"); - Subtract1(); - Console.WriteLine("----------"); - Subtract2(); - Console.WriteLine("----------"); - ConvertToLocal(); - Console.WriteLine("----------"); - ConvertToUniversal(); - Console.WriteLine("----------"); + ShowSchedule(); + Console.WriteLine("----------"); + ShowStartOfWorkWeek(); + Console.WriteLine("----------"); + ShowShiftStartTimes(); + Console.WriteLine("----------"); + ShowQuarters(); + Console.WriteLine("----------"); + DisplayTimes(); + Console.WriteLine("----------"); + ShowLegalLicenseAge(); + Console.WriteLine("----------"); + CompareForEquality1(); + Console.WriteLine("----------"); + CompareForEquality2(); + Console.WriteLine("----------"); + CompareForEquality3(); + Console.WriteLine("----------"); + CompareExactly(); + Console.WriteLine("----------"); + Subtract1(); + Console.WriteLine("----------"); + Subtract2(); + Console.WriteLine("----------"); + ConvertToLocal(); + Console.WriteLine("----------"); + ConvertToUniversal(); + Console.WriteLine("----------"); } - private static void ShowSchedule() - { - // - DateTimeOffset takeOff = new DateTimeOffset(2007, 6, 1, 7, 55, 0, - new TimeSpan(-5, 0, 0)); - DateTimeOffset currentTime = takeOff; - TimeSpan[] flightTimes = new TimeSpan[] - {new TimeSpan(2, 25, 0), new TimeSpan(1, 48, 0)}; - Console.WriteLine("Takeoff is scheduled for {0:d} at {0:T}.", - takeOff); - for (int ctr = flightTimes.GetLowerBound(0); - ctr <= flightTimes.GetUpperBound(0); ctr++) - { - currentTime = currentTime.Add(flightTimes[ctr]); - Console.WriteLine("Destination #{0} at {1}.", ctr + 1, currentTime); - } - // - } - - private static void ShowStartOfWorkWeek() - { - // - DateTimeOffset workDay = new DateTimeOffset(2008, 3, 1, 9, 0, 0, - DateTimeOffset.Now.Offset); - int month = workDay.Month; - // Start with the first Monday of the month - if (workDay.DayOfWeek != DayOfWeek.Monday) - { - if (workDay.DayOfWeek == DayOfWeek.Sunday) - workDay = workDay.AddDays(1); - else - workDay = workDay.AddDays(8 - (int)workDay.DayOfWeek); - } - Console.WriteLine("Beginning of Work Week In {0:MMMM} {0:yyyy}:", workDay); - // Add one week to the current date - do - { - Console.WriteLine(" {0:dddd}, {0:MMMM}{0: d}", workDay); - workDay = workDay.AddDays(7); - } while (workDay.Month == month); - // The example produces the following output: - // Beginning of Work Week In March 2008: - // Monday, March 3 - // Monday, March 10 - // Monday, March 17 - // Monday, March 24 - // Monday, March 31 - // - } - - private static void ShowShiftStartTimes() - { - // - const int SHIFT_LENGTH = 8; - - DateTimeOffset startTime = new DateTimeOffset(2007, 8, 6, 0, 0, 0, + private static void ShowSchedule() + { + // + DateTimeOffset takeOff = new DateTimeOffset(2007, 6, 1, 7, 55, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset currentTime = takeOff; + TimeSpan[] flightTimes = new TimeSpan[] + {new TimeSpan(2, 25, 0), new TimeSpan(1, 48, 0)}; + Console.WriteLine($"Takeoff is scheduled for {takeOff:d} at {takeOff:T}."); + for (int ctr = flightTimes.GetLowerBound(0); + ctr <= flightTimes.GetUpperBound(0); ctr++) + { + currentTime = currentTime.Add(flightTimes[ctr]); + Console.WriteLine($"Destination #{ctr + 1} at {currentTime}."); + } + // + } + + private static void ShowStartOfWorkWeek() + { + // + DateTimeOffset workDay = new DateTimeOffset(2008, 3, 1, 9, 0, 0, DateTimeOffset.Now.Offset); - DateTimeOffset startOfShift = startTime.AddHours(SHIFT_LENGTH); - - Console.WriteLine("Shifts for the week of {0:D}", startOfShift); - do - { - // Exclude third shift - if (startOfShift.Hour > 6) - Console.WriteLine(" {0:d} at {0:T}", startOfShift); - - startOfShift = startOfShift.AddHours(SHIFT_LENGTH); - } while (startOfShift.DayOfWeek != DayOfWeek.Saturday & - startOfShift.DayOfWeek != DayOfWeek.Sunday); - // The example produces the following output: - // - // Shifts for the week of Monday, August 06, 2007 - // 8/6/2007 at 8:00:00 AM - // 8/6/2007 at 4:00:00 PM - // 8/7/2007 at 8:00:00 AM - // 8/7/2007 at 4:00:00 PM - // 8/8/2007 at 8:00:00 AM - // 8/8/2007 at 4:00:00 PM - // 8/9/2007 at 8:00:00 AM - // 8/9/2007 at 4:00:00 PM - // 8/10/2007 at 8:00:00 AM - // 8/10/2007 at 4:00:00 PM - // - } - - private static void ShowQuarters() - { - // - DateTimeOffset quarterDate = new DateTimeOffset(2007, 1, 1, 0, 0, 0, - DateTimeOffset.Now.Offset); - for (int ctr = 1; ctr <= 4; ctr++) - { - Console.WriteLine("Quarter {0}: {1:MMMM d}", ctr, quarterDate); - quarterDate = quarterDate.AddMonths(3); - } - // This example produces the following output: - // Quarter 1: January 1 - // Quarter 2: April 1 - // Quarter 3: July 1 - // Quarter 4: October 1 - // - } - - private static void DisplayTimes() - { - // - double[] lapTimes = {1.308, 1.283, 1.325, 1.3625, 1.317, 1.267}; - DateTimeOffset currentTime = new DateTimeOffset(1, 1, 1, 1, 30, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("Start: {0:T}", currentTime); - for (int ctr = lapTimes.GetLowerBound(0); ctr <= lapTimes.GetUpperBound(0); ctr++) - { - currentTime = currentTime.AddMinutes(lapTimes[ctr]); - Console.WriteLine("Lap {0}: {1:T}", ctr + 1, currentTime); - } - // The example produces the following output: - // Start: 1:30:00 PM - // Lap 1: 1:31:18 PM - // Lap 2: 1:32:35 PM - // Lap 3: 1:33:54 PM - // Lap 4: 1:35:16 PM - // Lap 5: 1:36:35 PM - // Lap 6: 1:37:51 PM - // - } - - private static void ShowLegalLicenseAge() - { - // - const int minimumAge = 16; - DateTimeOffset dateToday = DateTimeOffset.Now; - DateTimeOffset latestBirthday = dateToday.AddYears(-1 * minimumAge); - Console.WriteLine("To possess a driver's license, you must have been born on or before {0:d}.", - latestBirthday); - // - } - - // - private static void CompareForEquality1() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); - - DateTimeOffset secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - // The example displays the following output to the console: - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True - // - } - - // - private static void CompareForEquality2() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); - - object secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = null; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTime(2007, 9, 1, 6, 45, 00); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - // The example displays the following output to the console: - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True - // 9/1/2007 6:45:00 AM -07:00 = : False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM: False - // - } - - private static void CompareForEquality3() - { - // - DateTimeOffset firstTime = new DateTimeOffset(2007, 11, 15, 11, 35, 00, - DateTimeOffset.Now.Offset); - DateTimeOffset secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - - // The value of firstTime remains unchanged - secondTime = new DateTimeOffset(firstTime.DateTime, - TimeSpan.FromHours(firstTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - - // value of firstTime remains unchanged - secondTime = new DateTimeOffset(firstTime.DateTime + TimeSpan.FromHours(1), - TimeSpan.FromHours(firstTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - // The example produces the following output: - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -07:00: True - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -06:00: False - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 12:35:00 PM -06:00: True - // - } - - private static void CompareExactly() - { - // - DateTimeOffset instanceTime = new DateTimeOffset(2007, 10, 31, 0, 0, 0, - DateTimeOffset.Now.Offset); - - DateTimeOffset otherTime = instanceTime; - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - - otherTime = new DateTimeOffset(instanceTime.DateTime, - TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - - otherTime = new DateTimeOffset(instanceTime.DateTime + TimeSpan.FromHours(1), - TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - // The example produces the following output: - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -07:00: True - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -06:00: False - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 1:00:00 AM -06:00: False - // - } - - private static void Subtract1() - { - // - DateTimeOffset firstDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset secondDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, - new TimeSpan(-5, 0, 0)); - DateTimeOffset thirdDate = new DateTimeOffset(2018, 9, 28, 9, 0, 0, - new TimeSpan(-7, 0, 0)); - TimeSpan difference; - - difference = firstDate.Subtract(secondDate); - Console.WriteLine($"({firstDate}) - ({secondDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); - - difference = firstDate.Subtract(thirdDate); - Console.WriteLine($"({firstDate}) - ({thirdDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); - - // The example produces the following output: - // (10/25/2018 6:00:00 PM -07:00) - (10/25/2018 6:00:00 PM -05:00): 0 days, 2:00 - // (10/25/2018 6:00:00 PM -07:00) - (9/28/2018 9:00:00 AM -07:00): 27 days, 9:00 - // - } - - private static void Subtract2() - { - // - DateTimeOffset offsetDate = new DateTimeOffset(2007, 12, 3, 11, 30, 0, - new TimeSpan(-8, 0, 0)); - TimeSpan duration = new TimeSpan(7, 18, 0, 0); - Console.WriteLine(offsetDate.Subtract(duration).ToString()); // Displays 11/25/2007 5:30:00 PM -08:00 - // - } - - private static void ConvertToLocal() - { - // - // Local time changes on 3/11/2007 at 2:00 AM - DateTimeOffset originalTime, localTime; - - originalTime = new DateTimeOffset(2007, 3, 11, 3, 0, 0, - new TimeSpan(-6, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - originalTime = new DateTimeOffset(2007, 3, 11, 4, 0, 0, - new TimeSpan(-6, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - // Define a summer UTC time - originalTime = new DateTimeOffset(2007, 6, 15, 8, 0, 0, - TimeSpan.Zero); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - // Define a winter time - originalTime = new DateTimeOffset(2007, 11, 30, 14, 0, 0, - new TimeSpan(3, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - // The example produces the following output: - // Converted 3/11/2007 3:00:00 AM -06:00 to 3/11/2007 1:00:00 AM -08:00. - // Converted 3/11/2007 4:00:00 AM -06:00 to 3/11/2007 3:00:00 AM -07:00. - // Converted 6/15/2007 8:00:00 AM +00:00 to 6/15/2007 1:00:00 AM -07:00. - // Converted 11/30/2007 2:00:00 PM +03:00 to 11/30/2007 3:00:00 AM -08:00. - // - } - - private static void ConvertToUniversal() - { - // - DateTimeOffset localTime, otherTime, universalTime; - - // Define local time in local time zone - localTime = new DateTimeOffset(new DateTime(2007, 6, 15, 12, 0, 0)); - Console.WriteLine("Local time: {0}", localTime); - Console.WriteLine(); - - // Convert local time to offset 0 and assign to otherTime - otherTime = localTime.ToOffset(TimeSpan.Zero); - Console.WriteLine("Other time: {0}", otherTime); - Console.WriteLine("{0} = {1}: {2}", - localTime, otherTime, - localTime.Equals(otherTime)); - Console.WriteLine("{0} exactly equals {1}: {2}", - localTime, otherTime, - localTime.EqualsExact(otherTime)); - Console.WriteLine(); - - // Convert other time to UTC - universalTime = localTime.ToUniversalTime(); - Console.WriteLine("Universal time: {0}", universalTime); - Console.WriteLine("{0} = {1}: {2}", - otherTime, universalTime, - universalTime.Equals(otherTime)); - Console.WriteLine("{0} exactly equals {1}: {2}", - otherTime, universalTime, - universalTime.EqualsExact(otherTime)); - Console.WriteLine(); - // The example produces the following output to the console: - // Local time: 6/15/2007 12:00:00 PM -07:00 - // - // Other time: 6/15/2007 7:00:00 PM +00:00 - // 6/15/2007 12:00:00 PM -07:00 = 6/15/2007 7:00:00 PM +00:00: True - // 6/15/2007 12:00:00 PM -07:00 exactly equals 6/15/2007 7:00:00 PM +00:00: False - // - // Universal time: 6/15/2007 7:00:00 PM +00:00 - // 6/15/2007 7:00:00 PM +00:00 = 6/15/2007 7:00:00 PM +00:00: True - // 6/15/2007 7:00:00 PM +00:00 exactly equals 6/15/2007 7:00:00 PM +00:00: True - // - } + int month = workDay.Month; + // Start with the first Monday of the month + if (workDay.DayOfWeek != DayOfWeek.Monday) + { + if (workDay.DayOfWeek == DayOfWeek.Sunday) + workDay = workDay.AddDays(1); + else + workDay = workDay.AddDays(8 - (int)workDay.DayOfWeek); + } + Console.WriteLine($"Beginning of Work Week In {workDay:MMMM} {workDay:yyyy}:"); + // Add one week to the current date + do + { + Console.WriteLine(" {0:dddd}, {0:MMMM}{0: d}", workDay); + workDay = workDay.AddDays(7); + } while (workDay.Month == month); + + // The example produces the following output: + // Beginning of Work Week In March 2008: + // Monday, March 3 + // Monday, March 10 + // Monday, March 17 + // Monday, March 24 + // Monday, March 31 + // + } + + private static void ShowShiftStartTimes() + { + // + const int SHIFT_LENGTH = 8; + + DateTimeOffset startTime = new DateTimeOffset(2007, 8, 6, 0, 0, 0, + DateTimeOffset.Now.Offset); + DateTimeOffset startOfShift = startTime.AddHours(SHIFT_LENGTH); + + Console.WriteLine($"Shifts for the week of {startOfShift:D}"); + do + { + // Exclude third shift + if (startOfShift.Hour > 6) + Console.WriteLine($" {startOfShift:d} at {startOfShift:T}"); + + startOfShift = startOfShift.AddHours(SHIFT_LENGTH); + } while (startOfShift.DayOfWeek != DayOfWeek.Saturday & + startOfShift.DayOfWeek != DayOfWeek.Sunday); + + // The example produces the following output: + // + // Shifts for the week of Monday, August 06, 2007 + // 8/6/2007 at 8:00:00 AM + // 8/6/2007 at 4:00:00 PM + // 8/7/2007 at 8:00:00 AM + // 8/7/2007 at 4:00:00 PM + // 8/8/2007 at 8:00:00 AM + // 8/8/2007 at 4:00:00 PM + // 8/9/2007 at 8:00:00 AM + // 8/9/2007 at 4:00:00 PM + // 8/10/2007 at 8:00:00 AM + // 8/10/2007 at 4:00:00 PM + // + } + + private static void ShowQuarters() + { + // + DateTimeOffset quarterDate = new DateTimeOffset(2007, 1, 1, 0, 0, 0, + DateTimeOffset.Now.Offset); + for (int ctr = 1; ctr <= 4; ctr++) + { + Console.WriteLine($"Quarter {ctr}: {quarterDate:MMMM d}"); + quarterDate = quarterDate.AddMonths(3); + } + + // This example produces the following output: + // Quarter 1: January 1 + // Quarter 2: April 1 + // Quarter 3: July 1 + // Quarter 4: October 1 + // + } + + private static void DisplayTimes() + { + // + double[] lapTimes = { 1.308, 1.283, 1.325, 1.3625, 1.317, 1.267 }; + DateTimeOffset currentTime = new DateTimeOffset(1, 1, 1, 1, 30, 0, + DateTimeOffset.Now.Offset); + Console.WriteLine($"Start: {currentTime:T}"); + for (int ctr = lapTimes.GetLowerBound(0); ctr <= lapTimes.GetUpperBound(0); ctr++) + { + currentTime = currentTime.AddMinutes(lapTimes[ctr]); + Console.WriteLine($"Lap {ctr + 1}: {currentTime:T}"); + } + + // The example produces the following output: + // Start: 1:30:00 PM + // Lap 1: 1:31:18 PM + // Lap 2: 1:32:35 PM + // Lap 3: 1:33:54 PM + // Lap 4: 1:35:16 PM + // Lap 5: 1:36:35 PM + // Lap 6: 1:37:51 PM + // + } + + private static void ShowLegalLicenseAge() + { + // + const int minimumAge = 16; + DateTimeOffset dateToday = DateTimeOffset.Now; + DateTimeOffset latestBirthday = dateToday.AddYears(-1 * minimumAge); + Console.WriteLine("To possess a driver's license, you must have been born on or before {0:d}.", + latestBirthday); + // + } + + // + private static void CompareForEquality1() + { + DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + DateTimeOffset secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + // The example displays the following output to the console: + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True + // + } + + // + private static void CompareForEquality2() + { + DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + object secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = null; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTime(2007, 9, 1, 6, 45, 00); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + // The example displays the following output to the console: + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True + // 9/1/2007 6:45:00 AM -07:00 = : False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM: False + // + } + + private static void CompareForEquality3() + { + // + DateTimeOffset firstTime = new DateTimeOffset(2007, 11, 15, 11, 35, 00, + DateTimeOffset.Now.Offset); + DateTimeOffset secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // The value of firstTime remains unchanged + secondTime = new DateTimeOffset(firstTime.DateTime, + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // value of firstTime remains unchanged + secondTime = new DateTimeOffset(firstTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // The example produces the following output: + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -07:00: True + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -06:00: False + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 12:35:00 PM -06:00: True + // + } + + private static void CompareExactly() + { + // + DateTimeOffset instanceTime = new DateTimeOffset(2007, 10, 31, 0, 0, 0, + DateTimeOffset.Now.Offset); + + DateTimeOffset otherTime = instanceTime; + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + otherTime = new DateTimeOffset(instanceTime.DateTime, + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + otherTime = new DateTimeOffset(instanceTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + // The example produces the following output: + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -07:00: True + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -06:00: False + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 1:00:00 AM -06:00: False + // + } + + private static void Subtract1() + { + // + DateTimeOffset firstDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset secondDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset thirdDate = new DateTimeOffset(2018, 9, 28, 9, 0, 0, + new TimeSpan(-7, 0, 0)); + TimeSpan difference; + + difference = firstDate.Subtract(secondDate); + Console.WriteLine($"({firstDate}) - ({secondDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + + difference = firstDate.Subtract(thirdDate); + Console.WriteLine($"({firstDate}) - ({thirdDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + + // The example produces the following output: + // (10/25/2018 6:00:00 PM -07:00) - (10/25/2018 6:00:00 PM -05:00): 0 days, 2:00 + // (10/25/2018 6:00:00 PM -07:00) - (9/28/2018 9:00:00 AM -07:00): 27 days, 9:00 + // + } + + private static void Subtract2() + { + // + DateTimeOffset offsetDate = new DateTimeOffset(2007, 12, 3, 11, 30, 0, + new TimeSpan(-8, 0, 0)); + TimeSpan duration = new TimeSpan(7, 18, 0, 0); + Console.WriteLine(offsetDate.Subtract(duration).ToString()); // Displays 11/25/2007 5:30:00 PM -08:00 + // + } + + private static void ConvertToLocal() + { + // + // Local time changes on 3/11/2007 at 2:00 AM + DateTimeOffset originalTime, localTime; + + originalTime = new DateTimeOffset(2007, 3, 11, 3, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + originalTime = new DateTimeOffset(2007, 3, 11, 4, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // Define a summer UTC time + originalTime = new DateTimeOffset(2007, 6, 15, 8, 0, 0, + TimeSpan.Zero); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // Define a winter time + originalTime = new DateTimeOffset(2007, 11, 30, 14, 0, 0, + new TimeSpan(3, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // The example produces the following output: + // Converted 3/11/2007 3:00:00 AM -06:00 to 3/11/2007 1:00:00 AM -08:00. + // Converted 3/11/2007 4:00:00 AM -06:00 to 3/11/2007 3:00:00 AM -07:00. + // Converted 6/15/2007 8:00:00 AM +00:00 to 6/15/2007 1:00:00 AM -07:00. + // Converted 11/30/2007 2:00:00 PM +03:00 to 11/30/2007 3:00:00 AM -08:00. + // + } + + private static void ConvertToUniversal() + { + // + DateTimeOffset localTime, otherTime, universalTime; + + // Define local time in local time zone + localTime = new DateTimeOffset(new DateTime(2007, 6, 15, 12, 0, 0)); + Console.WriteLine($"Local time: {localTime}"); + Console.WriteLine(); + + // Convert local time to offset 0 and assign to otherTime + otherTime = localTime.ToOffset(TimeSpan.Zero); + Console.WriteLine($"Other time: {otherTime}"); + Console.WriteLine("{0} = {1}: {2}", + localTime, otherTime, + localTime.Equals(otherTime)); + Console.WriteLine("{0} exactly equals {1}: {2}", + localTime, otherTime, + localTime.EqualsExact(otherTime)); + Console.WriteLine(); + + // Convert other time to UTC + universalTime = localTime.ToUniversalTime(); + Console.WriteLine($"Universal time: {universalTime}"); + Console.WriteLine("{0} = {1}: {2}", + otherTime, universalTime, + universalTime.Equals(otherTime)); + Console.WriteLine("{0} exactly equals {1}: {2}", + otherTime, universalTime, + universalTime.EqualsExact(otherTime)); + Console.WriteLine(); + + // The example produces the following output to the console: + // Local time: 6/15/2007 12:00:00 PM -07:00 + // + // Other time: 6/15/2007 7:00:00 PM +00:00 + // 6/15/2007 12:00:00 PM -07:00 = 6/15/2007 7:00:00 PM +00:00: True + // 6/15/2007 12:00:00 PM -07:00 exactly equals 6/15/2007 7:00:00 PM +00:00: False + // + // Universal time: 6/15/2007 7:00:00 PM +00:00 + // 6/15/2007 7:00:00 PM +00:00 = 6/15/2007 7:00:00 PM +00:00: True + // 6/15/2007 7:00:00 PM +00:00 exactly equals 6/15/2007 7:00:00 PM +00:00: True + // + } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs index 34701606ec3a4..0d7aff0f97051 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.IO.Pipes; @@ -12,8 +12,7 @@ static void Main(string[] args) using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[0])) { - Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.", - pipeClient.TransmissionMode); + Console.WriteLine($"[CLIENT] Current TransmissionMode: {pipeClient.TransmissionMode}."); using (StreamReader sr = new StreamReader(pipeClient)) { diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs index ef2dbadd6dcb9..b8680b410a51c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.IO.Pipes; @@ -16,8 +16,7 @@ static void Main() new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { - Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", - pipeServer.TransmissionMode); + Console.WriteLine($"[SERVER] Current TransmissionMode: {pipeServer.TransmissionMode}."); // Pass the client process a handle to the server. pipeClient.StartInfo.Arguments = @@ -45,7 +44,7 @@ static void Main() // or disconnected. catch (IOException e) { - Console.WriteLine("[SERVER] Error: {0}", e.Message); + Console.WriteLine($"[SERVER] Error: {e.Message}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs index ade03f310b09a..d5782f676950c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Security.Permissions; @@ -26,8 +26,7 @@ public static void DemonstrateWindowsBuiltInRoleEnum() } catch (Exception) { - Console.WriteLine("{0}: Could not obtain role for this RID.", - roleName); + Console.WriteLine($"{roleName}: Could not obtain role for this RID."); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs index abf8cbfdf3e03..0e301ad78a29a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs @@ -39,8 +39,7 @@ public static void Main() // Create the thread object, passing in the // serverObject.InstanceMethod method using a // ThreadStart delegate. - Thread InstanceCaller = new Thread( - new ThreadStart(serverObject.InstanceMethod)); + Thread InstanceCaller = new(new ThreadStart(serverObject.InstanceMethod)); // Start the thread. InstanceCaller.Start(); @@ -51,8 +50,7 @@ public static void Main() // Create the thread object, passing in the // serverObject.StaticMethod method using a // ThreadStart delegate. - Thread StaticCaller = new Thread( - new ThreadStart(ServerClass.StaticMethod)); + Thread StaticCaller = new(new ThreadStart(ServerClass.StaticMethod)); // Start the thread. StaticCaller.Start(); diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs index 2743be307c19b..f753b1faa8958 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs @@ -8,37 +8,35 @@ public class ThreadWithState { // State information used in the task. - private string boilerplate; - private int numberValue; + private string _boilerplate; + private int _numberValue; // The constructor obtains the state information. public ThreadWithState(string text, int number) { - boilerplate = text; - numberValue = number; + _boilerplate = text; + _numberValue = number; } // The thread procedure performs the task, such as formatting // and printing a document. public void ThreadProc() { - Console.WriteLine(boilerplate, numberValue); + Console.WriteLine(_boilerplate, _numberValue); } } // Entry point for the example. -// public class Example { public static void Main() { // Supply the state information required by the task. - ThreadWithState tws = new ThreadWithState( - "This report displays the number {0}.", 42); + ThreadWithState tws = new("This report displays the number {0}.", 42); // Create a thread to execute the task, and then // start the thread. - Thread t = new Thread(new ThreadStart(tws.ThreadProc)); + Thread t = new(new ThreadStart(tws.ThreadProc)); t.Start(); Console.WriteLine("Main thread does some work, then waits."); t.Join(); @@ -46,6 +44,7 @@ public static void Main() "Independent task has completed; main thread ends."); } } + // The example displays the following output: // Main thread does some work, then waits. // This report displays the number 42. diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs index 8890726ee4e8b..48a2682310050 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs @@ -2,28 +2,27 @@ using System; using System.Threading; -// The ThreadWithState class contains the information needed for +// The ThreadWithState2 class contains the information needed for // a task, the method that executes the task, and a delegate // to call when the task is complete. -// -public class ThreadWithState +public class ThreadWithState2 { // State information used in the task. - private string boilerplate; - private int numberValue; + private string _boilerplate; + private int _numberValue; // Delegate used to execute the callback method when the // task is complete. - private ExampleCallback callback; + private ExampleCallback _callback; // The constructor obtains the state information and the // callback delegate. - public ThreadWithState(string text, int number, + public ThreadWithState2(string text, int number, ExampleCallback callbackDelegate) { - boilerplate = text; - numberValue = number; - callback = callbackDelegate; + _boilerplate = text; + _numberValue = number; + _callback = callbackDelegate; } // The thread procedure performs the task, such as @@ -31,30 +30,27 @@ public ThreadWithState(string text, int number, // the callback delegate with the number of lines printed. public void ThreadProc() { - Console.WriteLine(boilerplate, numberValue); - if (callback != null) - callback(1); + Console.WriteLine(_boilerplate, _numberValue); + _callback?.Invoke(1); } } // Delegate that defines the signature for the callback method. -// public delegate void ExampleCallback(int lineCount); // Entry point for the example. -// -public class Example +public class Example2 { public static void Main() { // Supply the state information required by the task. - ThreadWithState tws = new ThreadWithState( + ThreadWithState2 tws = new( "This report displays the number {0}.", 42, new ExampleCallback(ResultCallback) ); - Thread t = new Thread(new ThreadStart(tws.ThreadProc)); + Thread t = new(new ThreadStart(tws.ThreadProc)); t.Start(); Console.WriteLine("Main thread does some work, then waits."); t.Join(); @@ -64,13 +60,12 @@ public static void Main() // The callback method must match the signature of the // callback delegate. - // public static void ResultCallback(int lineCount) { - Console.WriteLine( - "Independent task printed {0} lines.", lineCount); + Console.WriteLine($"Independent task printed {lineCount} lines."); } } + // The example displays the following output: // Main thread does some work, then waits. // This report displays the number 42. diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs index 2c0055eff14b4..fc41bb07708cf 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -14,8 +14,7 @@ static void Main() // Create a timer that invokes CheckStatus after one second, // and every 1/4 second thereafter. - Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", - DateTime.Now); + Console.WriteLine($"{DateTime.Now:h:mm:ss.fff} Creating timer.\n"); var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 250); diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs index 4ead01dc5d6f4..5eb50d6cfa316 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; // using System.Collections.Generic; @@ -125,7 +125,7 @@ private void DefineNonDSTTime() ! (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); + Console.WriteLine($"{palmer.StandardName} supports DST: {palmer.SupportsDaylightSavingTime}"); // } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs index 18288f974c827..fbdb60e766b36 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Runtime.ExceptionServices; @@ -32,8 +32,7 @@ static void Main() } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } // } @@ -41,8 +40,7 @@ static void Main() // static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e) { - Console.WriteLine("FirstChanceException event raised in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, e.Exception.Message); + Console.WriteLine($"FirstChanceException event raised in {AppDomain.CurrentDomain.FriendlyName}: {e.Exception.Message}"); } // } @@ -60,8 +58,7 @@ public void Thrower(bool catchException) } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } } else diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs index 1677bd6176f15..e70e7a2281484 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.Runtime.ExceptionServices; @@ -10,8 +10,7 @@ static void Main() AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e) => { - Console.WriteLine("FirstChanceException event raised in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, e.Exception.Message); + Console.WriteLine($"FirstChanceException event raised in {AppDomain.CurrentDomain.FriendlyName}: {e.Exception.Message}"); }; // @@ -22,8 +21,7 @@ static void Main() } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs index e9c442e12e40a..0668b39bcf7a3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ComponentModel; using System.Diagnostics; @@ -23,7 +23,7 @@ public static void Main() foreach (var inputValue in inputs) { - Console.WriteLine("Processing {0}", inputValue); + Console.WriteLine($"Processing {inputValue}"); bool timedOut = false; do { @@ -56,14 +56,12 @@ public static void Main() TimeSpan timeout = e.MatchTimeout.Add(TimeSpan.FromSeconds(1)); if (timeout.TotalSeconds > MaxTimeoutInSeconds) { - Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.", - MaxTimeoutInSeconds); + Console.WriteLine($"Maximum timeout interval of {MaxTimeoutInSeconds} seconds exceeded."); timedOut = false; } else { - Console.WriteLine("Changing the timeout interval to {0}", - timeout); + Console.WriteLine($"Changing the timeout interval to {timeout}"); rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout); timedOut = true; } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs index 899de21fb2706..b3c479f2fba7d 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -67,7 +67,7 @@ static void CancelDemo() // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{e}"); } // Catching the cancellation exception catch (OperationCanceledException e) diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs index 3f50ecf984363..6b8a826da51d5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -39,13 +39,13 @@ static void Main() (localSum) => Interlocked.Add(ref sum, localSum) // thread local aggregator ); - Console.WriteLine("\nSum={0}", sum); + Console.WriteLine($"\nSum={sum}"); } // No exception is expected in this example, but if one is still thrown from a task, // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{e}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs index 92bf29a51beb6..1f565e4c0f9a9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -46,7 +46,7 @@ static void Main() // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("An iteration has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"An iteration has thrown an exception. THIS WAS NOT EXPECTED.\n{e}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs index 6195ad0e3eaf5..14c974f0be909 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -34,7 +34,7 @@ static void Main() ); // Print the actual and expected results. - Console.WriteLine("Actual result: {0}. Expected 1000000.", result); + Console.WriteLine($"Actual result: {result}. Expected 1000000."); } // Simulates a lengthy operation. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs b/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs index bc30836e90568..06c1b877d95de 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -13,7 +13,7 @@ public CancelableObject(string id) public void Cancel() { - Console.WriteLine("Object {0} Cancel callback", id); + Console.WriteLine($"Object {id} Cancel callback"); // Perform object cancellation here. } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj new file mode 100644 index 0000000000000..f3462ab8ee804 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj @@ -0,0 +1,12 @@ + + + + Library + net9.0 + + + + + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs index c9b51bfa998ee..0687c66aacff2 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs @@ -1,6 +1,4 @@ - - -// +// namespace ProducerConsumer { using System; @@ -8,9 +6,9 @@ namespace ProducerConsumer using System.Diagnostics; using System.Linq; using System.Threading; + class Program { - // Limit the collection size to 2000 items // at any given time. const int upperLimit = 2000; @@ -24,7 +22,6 @@ class Program static void Main(string[] args) { - // Start the stopwatch. sw.Start(); @@ -40,16 +37,14 @@ static void Main(string[] args) Console.ReadKey(); } - static void RunProducer(Object stateInfo) + static void RunProducer(object stateInfo) { - for (int i = 0; i < 100; i++) { - long ticks = sw.ElapsedTicks; // Uncomment this line to see interleaved additions and subtractions. - Console.WriteLine("adding tick value {0}. item# {1}", ticks, additions); + Console.WriteLine($"adding tick value {ticks}. item# {additions}"); collection.Add(ticks); @@ -65,14 +60,14 @@ static void RunProducer(Object stateInfo) // Important!!! Tell consumers that no more items will be added. collection.CompleteAdding(); - Console.WriteLine("Done adding: {0} items", additions); + Console.WriteLine($"Done adding: {additions} items"); } static void RunConsumer(Object stateInfo) { // GetConsumingEnumerable returns the enumerator for the // underlying collection. - foreach (var item in collection.GetConsumingEnumerable()) + foreach (long item in collection.GetConsumingEnumerable()) { Console.WriteLine("Consuming tick value {0} : item# {1} ", item.ToString("D18"), subtractions++); @@ -106,8 +101,7 @@ static void RunConsumer2(Object stateInfo) } } - Console.WriteLine("Total added: {0} Total consumed: {1} Current count: {2} ", - additions, subtractions, collection.Count); + Console.WriteLine($"Total added: {additions} Total consumed: {subtractions} Current count: {collection.Count} "); } // } @@ -129,12 +123,11 @@ class Data class Blocking { - private static BlockingCollection blockingCollection = new BlockingCollection(10); // Some data to add. - static string[] cities = new string[10] { "London", "Mumbai", "Beijing", "Baghdad", "Paris", "Berlin", "Moscow", "Sydney", "Buenos Aires", "Tokyo" }; - static double[] population = new double[10] { 7.65, 18.041, 12.037, 4.795, 9.642, 3.339, 9.3, 3.664, 12.435, 38.027 }; + static string[] s_cities = ["London", "Mumbai", "Beijing", "Baghdad", "Paris", "Berlin", "Moscow", "Sydney", "Buenos Aires", "Tokyo"]; + static double[] s_population = [7.65, 18.041, 12.037, 4.795, 9.642, 3.339, 9.3, 3.664, 12.435, 38.027]; static void Main() { @@ -142,9 +135,9 @@ static void Main() Thread.Sleep(100); //Give the other thread time to spin up. // Produce data - for (int i = 0; i < cities.Length; i++) + for (int i = 0; i < s_cities.Length; i++) { - blockingCollection.Add(new Data() { City = cities[i], Population = (int)(population[i] * 1000000) }); + blockingCollection.Add(new Data() { City = s_cities[i], Population = (int)(s_population[i] * 1000000) }); Thread.SpinWait(5000000); // Simulate some extra work. } blockingCollection.CompleteAdding(); @@ -159,7 +152,7 @@ private static void ConsumeData(object collection) BlockingCollection coll = (BlockingCollection)collection; foreach (Data d in coll.GetConsumingEnumerable()) { - Console.WriteLine("The population of {0} is approximately {1}", d.City, d.Population); + Console.WriteLine($"The population of {d.City} is approximately {d.Population}"); } Console.WriteLine("Done"); } @@ -170,13 +163,11 @@ private static void ConsumeData(object collection) namespace Demos { using System; - using System.Data.SqlClient; - using System.Diagnostics; - using System.Collections.Concurrent; - using System.Text; using System.Linq; + using System.Text; using System.Threading; using System.Threading.Tasks; + using Microsoft.Data.SqlClient; // @@ -184,14 +175,14 @@ class MyBarrier { const int Partitions = 3; - static byte[][] data = new byte[Partitions][]; - static double[] results = new double[Partitions]; + static byte[][] s_data = new byte[Partitions][]; + static double[] s_results = new double[Partitions]; static void Main() { // Create a new barrier, specifying a participant count and a // delegate to invoke when the first phase is complete. - Barrier b = new Barrier(Partitions); + Barrier b = new(Partitions); Task[] tasks = new Task[Partitions]; for (int i = 0; i < Partitions; i++) @@ -202,7 +193,6 @@ static void Main() tasks[i] = Task.Run(() => { - // Fill each buffer, then wait. GenerateDataForMyPartition(index); b.SignalAndWait(); @@ -220,18 +210,18 @@ static void Main() // Toy implementation to generate some data. static void GenerateDataForMyPartition(int taskNumber) { - data[taskNumber] = new byte[100]; + s_data[taskNumber] = new byte[100]; var rand = new Random(); - rand.NextBytes(data[taskNumber]); + rand.NextBytes(s_data[taskNumber]); - Console.WriteLine("Generate for {0}", taskNumber); + Console.WriteLine($"Generate for {taskNumber}"); int total = 0; - foreach (var b in data[taskNumber]) + foreach (byte b in s_data[taskNumber]) { total += b; } - results[taskNumber] = (double)((double)total / data[taskNumber].Length); - Console.WriteLine("results[{0}] = {1}", taskNumber, results[taskNumber]); + s_results[taskNumber] = (double)((double)total / s_data[taskNumber].Length); + Console.WriteLine($"results[{taskNumber}] = {s_results[taskNumber]}"); } // In this example, we simply take the average and compare it to other partitions. @@ -239,19 +229,19 @@ static void GenerateDataForMyPartition(int taskNumber) // operation. static void ComputeForMyPartition(int index) { - double myAverage = results[index]; + double myAverage = s_results[index]; var sb = new StringBuilder(); sb.AppendFormat("results for buffer[{0}]:\n", index); - for (int i = 0; i < results.Length; i++) + for (int i = 0; i < s_results.Length; i++) { if (i == index) continue; // Don't compare to myself. - var them = results[i]; + double them = s_results[i]; var diff = Math.Abs(them - myAverage); - if(myAverage > them) + if (myAverage > them) sb.AppendFormat(" greater than buffer[{0}] by {1}\n", i, diff); else if (myAverage == them) - sb.AppendFormat(" equal to buffer[{0}]\n", i, diff); + sb.AppendFormat(" equal to buffer[{0}]\n", i, diff); else if (myAverage < them) sb.AppendFormat(" less than buffer[{0}] by {1}\n", i, diff); } @@ -261,22 +251,6 @@ static void ComputeForMyPartition(int index) } // - //might use this for another barrier example - class HoldingPatter - { - static byte[][] data = new byte[10][]; // - static void AdjustValues(int index, double factor) - { - - for (int i = 0; i < data[index].Length; i++) - { - var val = data[index][i]; - var newVal = val * factor; - data[index][i] = newVal > 1 ? (byte)newVal : (byte)255; - } - } - } - class MyBarrierOld { const int P = 4; @@ -284,7 +258,7 @@ class MyBarrierOld static void Main() { byte[][] data = new byte[P][]; - Barrier b = new Barrier(P); + Barrier b = new(P); Task[] tasks = new Task[P]; for (int i = 0; i < P; i++) @@ -304,7 +278,7 @@ static void Main() static void GenerateDataForMyPartition(int index, byte[][] buffer) { var rand = new Random(); - var myBytes = new Byte[50]; + byte[] myBytes = new byte[50]; rand.NextBytes(myBytes); buffer[index] = myBytes; } @@ -313,249 +287,24 @@ static void CompareMyPartitionToTotal(int index, byte[][] buffer) { // To gain efficiency, the average value of all buffers // could be calculated once instead of once per task. - var average = (from buf in buffer + double average = (from buf in buffer from b in buf select b).Average(n => n); - var myAverage = buffer[index].Average(n => n); + double myAverage = buffer[index].Average(n => n); if (myAverage > average) { - Console.WriteLine("Buffer [{0}] is above average!", index); + Console.WriteLine($"Buffer [{index}] is above average!"); } } } - //class Lazy : Lazy where T: MyClass, new() - //{ - // public Lazy(Action action) - // { - // return new MyClass(() => "test"); - // } - // public Lazy() - //{} - //} - class DataInitializedFromDb - { - public DataInitializedFromDb (SqlDataReader reader){} - public int Rows = 0; - } - //class ThreadLocal - //{ - // public ThreadLocal(T input) {} - // public T Value {get; set;} - //} - /* - class LazyDemo - { - static void Main() - { - Lazy mc = new Lazy(); - - LazyInit.EnsureInitialized(ref mc); - - - MyClass mc2 = null; - - LazyInit.EnsureInitialized(ref mc2); - - Console.WriteLine("I've created the LI"); - - Console.WriteLine("Process Data? Y/N"); - char c = Console.ReadKey().KeyChar; - if (c == 'y' || c == 'Y') - // mc.Value.DoSomething(); - mc.Value.DoSomething(); - - else - Console.WriteLine("Program complete."); - - Console.WriteLine("Enter Name to find? Exapmle: Fred "); - string s = Console.ReadLine(); - - if (s.Length > 0) - { - Console.WriteLine("mc.Value.data.Value"); - mc = new Lazy(() => new MyClass(s)); - Console.WriteLine(mc.Value.data.Value.Name); - - } - Console.WriteLine("Press any key"); - Console.ReadKey(); - } - - static void Test() - { - // snip pet 9 was here. deleted per JoshP - - } - - private static void ProcessData(DataInitializedFromDb data){} - private static void Test2() - { - string cmdText = ""; - // was snippet 10 removed per joshp - - Lazy _data = - new Lazy(delegate - { - using(SqlConnection conn = new SqlConnection(...)) - using(SqlCommand comm = new SqlCommand(cmdText, conn)) - { - SqlDataReader reader = comm.ExecuteReader(); - DataInitializedFromDb data = - new DataInitializedFromDb(reader); - return data; - } - }, LazyExecutionMode.AllowMultipleThreadSafeExecutions); - - // use the data - if (_data.Value.Rows > 10) - { - ProcessData(_data.Value); - } - ///snippet 10 - } - - private static int Compute(int i){return i;} - private static void Test3() - { - // - //Initializing a value with a big computation, computed in parallel - Lazy _data = new Lazy(delegate - { - return ParallelEnumerable.Range(0, 1000). - Select(i => Compute(i)).Aggregate((x,y) => x + y); - }, LazyExecutionMode.EnsureSingleThreadSafeExecution); - // ... - // use the data - if (_data.Value > 100) - { - Console.WriteLine("Good data"); - } - // - } - - - - - // - // Direct initialization to avoid overhead - static List m_exceptions; - - static void AddException(Exception e) - { - LazyInitializer.EnsureInitialized(ref m_exceptions).Add(e); - } - // - - private static void Test5() - { - // - //Initializing a value per thread, per instance - ThreadLocal _scratchArrays = - new ThreadLocal(InitializeArrays); - // . . . - static int[][] InitializeArrays () {return new int[][]} - // . . . - // use the thread-local data - int i = 8; - int [] tempArr = _scratchArrays.Value[i]; - // - - } - - static void Test6() - { - - // - Action[] actions = new Action[5]; - // ...initialize actions - - // Lazily-initializing a local with minimal overhead - var exceptions = new LazyVariable>(); - foreach(var action in actions) - { - try - { - action(); - } - catch(Exception exc) - { - exceptions.Value.Add(exc); - } - } - if (exceptions.IsValueCreated) - throw new AggregateException(exceptions.Value); - - // - } - - } - - class Data - { - public Data(string s) { Name = s; } - public string Name {get; set;} - public int Number {get; set;} - //... assume - } - class MyClass - { - - public LazyVariable data; - public MyClass() - { - Console.WriteLine("Default constructor called."); - } - public MyClass(string str) - { - Console.Write("Constructor with string argument called: "); - data = new LazyVariable( () => new Data(str)); - Console.WriteLine(data.Value.Name); - } - - public void DoSomething() - { - Console.WriteLine("Do something"); - } - - } - */ - - // NOT USED!!!!! - // - class MRES { - static ManualResetEventSlim _signalled = new ManualResetEventSlim(); - static byte[] data = new byte[4]; - - static void Main() - { - SpinUntilCondition(); - } - - private static void SpinUntilCondition() - { - // Do something on another thread. - ThreadPool.QueueUserWorkItem(new WaitCallback(PostData), null); - - // The data will be ready very soon. - _signalled.Wait(); - - //Consume data - Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", data[0], data[1], data[2], data[3]); - } - - static void PostData(object state) - { - Random rand = new Random(); - rand.NextBytes(data); - _signalled.Set(); - } - } - // + public DataInitializedFromDb(SqlDataReader reader) { } + public int Rows = 0; } +} class Test5 { diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs index 7343de417801e..fe01e3ad6e2bb 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs @@ -1,4 +1,4 @@ -// +// //#define TRACE using System; using System.Collections.Generic; @@ -40,7 +40,7 @@ class Program if (String.CompareOrdinal(solution, sb.ToString()) == 0) { success = true; - Console.WriteLine("\r\nThe solution was found in {0} attempts", barrier.CurrentPhaseNumber); + Console.WriteLine($"\r\nThe solution was found in {barrier.CurrentPhaseNumber} attempts"); } }); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs index 8e135caaa79d5..1e4014ad06304 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; @@ -40,7 +40,7 @@ static void Main() Console.WriteLine("Adding was completed!"); break; } - Console.WriteLine("Take:{0} ", i); + Console.WriteLine($"Take:{i} "); // Simulate a slow consumer. This will cause // collection to fill up fast and thus Adds wil block. @@ -56,7 +56,7 @@ static void Main() for (int i = 0; i < itemsToAdd; i++) { numbers.Add(i); - Console.WriteLine("Add:{0} Count={1}", i, numbers.Count); + Console.WriteLine($"Add:{i} Count={numbers.Count}"); } // See documentation for this method. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs index 522740f13d251..42f576e6a6c5d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; @@ -61,7 +61,7 @@ static void NonBlockingConsumer(BlockingCollection bc, CancellationToken ct } else { - Console.WriteLine(" Take:{0}", nextItem); + Console.WriteLine($" Take:{nextItem}"); } } @@ -103,7 +103,7 @@ static void NonBlockingProducer(BlockingCollection bc, CancellationToken ct if (success) { - Console.WriteLine(" Add:{0}", itemToAdd); + Console.WriteLine($" Add:{itemToAdd}"); itemToAdd++; } else @@ -123,7 +123,7 @@ static void NonBlockingProducer(BlockingCollection bc, CancellationToken ct static void UpdateProgress(int i) { double percent = ((double)i / inputs) * 100; - Console.WriteLine("Percent complete: {0}", percent); + Console.WriteLine($"Percent complete: {percent}"); } } // \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs index d76d12d757b49..0f3f413b8f64f 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Linq; @@ -26,7 +26,7 @@ public static void Main() { int k = BlockingCollection.TryAddToAny(sourceArrays, j); if(k >=0) - Console.WriteLine("added {0} to source data", j); + Console.WriteLine($"added {j} to source data"); }); foreach (var arr in sourceArrays) @@ -127,7 +127,7 @@ public PipelineFilter( public void Run() { - Console.WriteLine("{0} is running", this.Name); + Console.WriteLine($"{this.Name} is running"); while (!m_input.All(bc => bc.IsCompleted) && !m_token.IsCancellationRequested) { TInput receivedItem; @@ -139,7 +139,7 @@ public void Run() { TOutput outputItem = m_processor(receivedItem); BlockingCollection.AddToAny(m_output, outputItem); - Console.WriteLine("{0} sent {1} to next", this.Name, outputItem); + Console.WriteLine($"{this.Name} sent {outputItem} to next"); } else // we're an endpoint { diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs index 914d66b0405b4..9421c9eae5b62 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs @@ -5,9 +5,6 @@ namespace ProdConsumerCS using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text; using System.Threading; using System.Threading.Tasks; @@ -24,7 +21,7 @@ public class SimplePriorityQueue : IProducerConsumerCollectio public SimplePriorityQueue(int priCount) { - this.priorityCount = priCount; + priorityCount = priCount; _queues = new ConcurrentQueue>[priorityCount]; for (int i = 0; i < priorityCount; i++) _queues[i] = new ConcurrentQueue>(); @@ -83,8 +80,8 @@ void ICollection.CopyTo(Array array, int index) // data as we have without running off the end. public void CopyTo(KeyValuePair[] destination, int destStartingIndex) { - if (destination == null) throw new ArgumentNullException(); - if (destStartingIndex < 0) throw new ArgumentOutOfRangeException(); + ArgumentNullException.ThrowIfNull(destination); + ArgumentOutOfRangeException.ThrowIfNegative(destStartingIndex); int remaining = destination.Length; KeyValuePair[] temp = this.ToArray(); @@ -210,29 +207,33 @@ static void Main() if (success) { // Do something useful with the data. - Console.WriteLine("removed Pri = {0} data = {1} collCount= {2}", item.Key, item.Value, bc.Count); + Console.WriteLine($"removed Pri = {item.Key} data = {item.Value} collCount= {bc.Count}"); } else { - Console.WriteLine("No items to retrieve. count = {0}", bc.Count); + Console.WriteLine($"No items to retrieve. count = {bc.Count}"); } } Console.WriteLine("Exited consumer loop"); }, cts.Token); - try { + try + { Task.WaitAll(tasks, cts.Token); } - catch (OperationCanceledException e) { + catch (OperationCanceledException e) + { if (e.CancellationToken == cts.Token) Console.WriteLine("Operation was canceled by user. Press any key to exit"); } - catch (AggregateException ae) { + catch (AggregateException ae) + { foreach (var v in ae.InnerExceptions) Console.WriteLine(v.Message); } - finally { + finally + { cts.Dispose(); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs index 753ed136f3d9c..d77a6497ea9bd 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -28,7 +28,7 @@ static void ProcessData(object obj) { Data d = (Data)obj; Thread.SpinWait(50000000); - Console.WriteLine("Processed {0}", d.Num); + Console.WriteLine($"Processed {d.Num}"); } static IEnumerable GetData() @@ -101,7 +101,7 @@ static void ProcessData(object obj) DataWithToken dataWithToken = (DataWithToken)obj; if (dataWithToken.Token.IsCancellationRequested) { - Console.WriteLine("Canceled before starting {0}", dataWithToken.Data.Num); + Console.WriteLine($"Canceled before starting {dataWithToken.Data.Num}"); return; } @@ -109,13 +109,13 @@ static void ProcessData(object obj) { if (dataWithToken.Token.IsCancellationRequested) { - Console.WriteLine("Cancelling while executing {0}", dataWithToken.Data.Num); + Console.WriteLine($"Cancelling while executing {dataWithToken.Data.Num}"); return; } // Increase this value to slow down the program. Thread.SpinWait(100000); } - Console.WriteLine("Processed {0}", dataWithToken.Data.Num); + Console.WriteLine($"Processed {dataWithToken.Data.Num}"); } static void Main(string[] args) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs index ab24b4b1b6103..0f5f96e55e4e2 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Collections.Concurrent; @@ -50,8 +50,7 @@ public static void DoWork() } catch (LockRecursionException ex) { - Console.WriteLine("Thread {0} attempted to reenter the lock", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} attempted to reenter the lock"); throw; } finally @@ -141,7 +140,7 @@ private static void UseSpinLock() } ); sw.Stop(); - Console.WriteLine("elapsed ms with spinlock: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed ms with spinlock: {sw.ElapsedMilliseconds}"); } static void UpdateWithLock(Data d, int i) @@ -171,7 +170,7 @@ private static void UseLock() } ); sw.Stop(); - Console.WriteLine("elapsed ms with lock: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed ms with lock: {sw.ElapsedMilliseconds}"); } } // @@ -188,7 +187,7 @@ static void ParallelForWithLock() //} // ); //sw.Stop(); - // Console.WriteLine("elapsed ms with lock: {0}", sw.ElapsedMilliseconds); + // Console.WriteLine($"elapsed ms with lock: {sw.ElapsedMilliseconds}"); } static void ParallelForwithSpinLock() diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs index 133dccebc83a9..bb024484a23e4 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs @@ -1,4 +1,4 @@ -#define LOGGING +#define LOGGING using System; using System.Collections.Generic; @@ -28,9 +28,9 @@ public void PrintLog() for (int i = 0; i < spinCountLog.Length; i++) { - Console.WriteLine("Wait succeeded with spin count of {0} on {1} attempts", i, spinCountLog[i]); + Console.WriteLine($"Wait succeeded with spin count of {i} on {spinCountLog[i]} attempts"); } - Console.WriteLine("Wait used the kernel event on {0} attempts.", totalKernelWaits); + Console.WriteLine($"Wait used the kernel event on {totalKernelWaits} attempts."); Console.WriteLine("Logging complete"); } #endif @@ -252,14 +252,14 @@ private static void SpinThenWait(int count) if (SpinForResult(count) == true) { ReadFiles(files); - Console.WriteLine("Spinning paid off. returned after {0} ticks", watch.ElapsedTicks); + Console.WriteLine($"Spinning paid off. returned after {watch.ElapsedTicks} ticks"); } else { mre.WaitOne(); ReadFiles(files); - Console.WriteLine("Spinning timed out. Now waiting on event: returned after {0} ticks", watch.ElapsedTicks); + Console.WriteLine($"Spinning timed out. Now waiting on event: returned after {watch.ElapsedTicks} ticks"); } } @@ -335,7 +335,7 @@ private static void UseManualResetEvent() // Now do something with result array here... } long ticks = watch.ElapsedTicks; - Console.WriteLine("Waiting on {0} complete. Elapsed ticks = {1}", loopCount, ticks); + Console.WriteLine($"Waiting on {loopCount} complete. Elapsed ticks = {ticks}"); } private static void UseSpinWait() @@ -351,7 +351,7 @@ private static void UseSpinWait() } long ticks = watch.ElapsedTicks; - Console.WriteLine("Spinning on {0} complete. Elapsed ticks = {1}", loopCount, ticks); + Console.WriteLine($"Spinning on {loopCount} complete. Elapsed ticks = {ticks}"); } static void GenerateDataForResetEvent(object state) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs index bd78a13b85e3d..25c864e4292db 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs @@ -1,4 +1,4 @@ -// +// #define LOGGING using System; @@ -24,10 +24,9 @@ public void DisplayLog() { for (int i = 0; i < spinCountLog.Length; i++) { - Console.WriteLine("Wait succeeded with spin count of {0} on {1:N0} attempts", - i, spinCountLog[i]); + Console.WriteLine($"Wait succeeded with spin count of {i} on {spinCountLog[i]:N0} attempts"); } - Console.WriteLine("Wait used the kernel event on {0:N0} attempts.", totalKernelWaits); + Console.WriteLine($"Wait used the kernel event on {totalKernelWaits:N0} attempts."); Console.WriteLine("Logging complete"); } #endif diff --git a/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs b/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs index 3a2f5eed0946a..a68a9b06d18cd 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; @@ -275,7 +275,7 @@ class Calculator { public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state) { - Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling BeginCalculate on thread {Thread.CurrentThread.ManagedThreadId}"); Task f = Task.Factory.StartNew(_ => Compute(decimalPlaces), state); if (ac != null) f.ContinueWith((res) => ac(f)); return f; @@ -283,7 +283,7 @@ public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object s public string Compute(int numPlaces) { - Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling compute on thread {Thread.CurrentThread.ManagedThreadId}"); // Simulating some heavy work. Thread.SpinWait(500000000); @@ -295,7 +295,7 @@ public string Compute(int numPlaces) public string EndCalculate(IAsyncResult ar) { - Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling EndCalculate on thread {Thread.CurrentThread.ManagedThreadId}"); return ((Task)ar).Result; } } @@ -321,8 +321,7 @@ public static void PrintResult(IAsyncResult result) { Calculator c = (Calculator)result.AsyncState; string piString = c.EndCalculate(result); - Console.WriteLine("Calling PrintResult on thread {0}; result = {1}", - Thread.CurrentThread.ManagedThreadId, piString); + Console.WriteLine($"Calling PrintResult on thread {Thread.CurrentThread.ManagedThreadId}; result = {piString}"); } } #endregion @@ -586,7 +585,7 @@ void ProcessFilesAsync() } catch { - Console.WriteLine("Argument exception on {0}", file); + Console.WriteLine($"Argument exception on {file}"); continue; } t.ContinueWith((antecedent) => ProcessFileData(antecedent.Result)); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs index b0332feb436e8..54b122ba68074 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Linq; @@ -25,7 +25,7 @@ from num in source.AsParallel() sw.Stop(); long elapsed = sw.ElapsedMilliseconds; // or sw.ElapsedTicks - Console.WriteLine("Total query time: {0} ms", elapsed); + Console.WriteLine($"Total query time: {elapsed} ms"); Console.WriteLine("Press any key to exit."); Console.ReadKey(); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs index 5df56f47b4c40..09dc3d926297a 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs @@ -1,4 +1,4 @@ -namespace PLINQ_Samples +namespace PLINQ_Samples { using System; using System.Collections.Generic; @@ -431,8 +431,7 @@ static void Main(string[] args) Console.WriteLine(line); } - Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.", - sw.ElapsedMilliseconds); + Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds} ms. Press any key to exit."); Console.ReadKey(); } @@ -488,8 +487,8 @@ static void Main(string[] args) // perform standard deviation calc on the aggregated result. (finalSum) => Math.Sqrt((finalSum / (source.Length - 1))) ); - Console.WriteLine("Mean value is = {0}", mean); - Console.WriteLine("Standard deviation is {0}", standardDev); + Console.WriteLine($"Mean value is = {mean}"); + Console.WriteLine($"Standard deviation is {standardDev}"); Console.ReadLine(); } } @@ -743,7 +742,7 @@ static void SimpleOrdering() .AsOrdered() .ElementAt(48); - Console.WriteLine("Element #48 is: {0}", cust.CustomerID); + Console.WriteLine($"Element #48 is: {cust.CustomerID}"); } // @@ -776,7 +775,7 @@ static void OrderedThenUnordered() .OrderBy(i => i.Product); // Apply new ordering to final result sequence. foreach (var v in q2) - Console.WriteLine("{0} {1} {2}", v.ID, v.Customer, v.Product); + Console.WriteLine($"{v.ID} {v.Customer} {v.Product}"); } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs index 6115e2cb224f9..2243898e8311d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs @@ -26,7 +26,7 @@ static void Main() string path = @"C:\Users\Public\Pictures\Sample Pictures\"; string[] files = System.IO.Directory.GetFiles(path); - var result = (from file in files.AsParallel() + string[] result = (from file in files.AsParallel() let info = new System.IO.FileInfo(file) where info.Extension == ".jpg" select file).ToArray(); @@ -34,7 +34,7 @@ static void Main() return result; }); - foreach (var name in task3.Result) + foreach (string name in task3.Result) Console.WriteLine(name); } class Test @@ -43,4 +43,4 @@ class Test public double Number { get; set; } } } -// \ No newline at end of file +// diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs index bd990ba954ed0..cedbcd1b940b8 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs @@ -1,23 +1,15 @@ - - -namespace TPL +namespace TPL { using System; - using System.Collections; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading; using System.Threading.Tasks; class Program { static void Main(string[] args) { - // WaitOnTasks(); - // HandleExceptions(); - // RethrowAllExceptions(); + // WaitOnTasks(); + // HandleExceptions(); + // RethrowAllExceptions(); Console.ReadKey(); } @@ -28,69 +20,6 @@ class Test public double Number { get; set; } } - static void DoSomeWork(int val) - { - // Pretend to do something. - Thread.SpinWait(val); // ticks, not milliseconds - } - - static double TrySolution1() - { - // Pretend to do something. - Thread.SpinWait(1000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - static double TrySolution2() - { - // Pretend to do something. - Thread.SpinWait(10000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - static double TrySolution3() - { - // Pretend to do something. - Thread.SpinWait(1000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - - static string[] GetAllFiles(string str) - { - // Should throw an AccessDenied exception on Vista. - return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories); - } -// static void HandleExceptions() -// { -// // Assume this is a user-entered string. -// string path = @"C:\"; -// -// // Use this line to throw UnauthorizedAccessException, which we handle. -// Task task1 = Task.Factory.StartNew(() => GetAllFiles(path)); -// -// // Use this line to throw an exception that is not handled. -// // Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } ); -// try -// { -// task1.Wait(); -// } -// catch (AggregateException ae) -// { -// -// ae.Handle((x) => -// { -// if (x is UnauthorizedAccessException) // This we know how to handle. -// { -// Console.WriteLine("You do not have permission to access all folders in this path."); -// Console.WriteLine("See your network administrator or try another path."); -// return true; -// } -// return false; // Let anything else stop the application. -// }); -// -// } -// -// Console.WriteLine("task1 has completed."); -// } - // static string[] GetValidExtensions(string path) { @@ -99,35 +28,12 @@ static string[] GetValidExtensions(string path) return new string[10]; } - static void RethrowAllExceptions() - { - // Assume this is a user-entered string. - string path = @"C:\"; - - Task[] tasks = new Task[3]; - tasks[0] = Task.Factory.StartNew(() => GetAllFiles(path)); - tasks[1] = Task.Factory.StartNew(() => GetValidExtensions(path)); - tasks[2] = Task.Factory.StartNew(() => new string[10]); - - //int index = Task.WaitAny(tasks2); - //double d = tasks2[index].Result; - try - { - Task.WaitAll(tasks); - } - catch (AggregateException ae) - { - throw ae.Flatten(); - } - - Console.WriteLine("task1 has completed."); - } // } - // 14 was deleted, probably because it duplicated cancellation snippet + // 14 was deleted, probably because it duplicated cancellation snippet - // 15 was moved to tpl_cancellation and so number is available in tpl + // 15 was moved to tpl_cancellation and so number is available in tpl // public class TreeWalk @@ -139,7 +45,7 @@ static void Main() // ...populate tree (left as an exercise) // Define the Action to perform on each node. - Action myAction = x => Console.WriteLine("{0} : {1}", x.Name, x.Number); + Action myAction = x => Console.WriteLine($"{x.Name} : {x.Number}"); // Traverse the tree with parallel tasks. DoTree(tree, myAction); @@ -169,7 +75,7 @@ public static void DoTree(Tree tree, Action action) { Task.WaitAll(left, right); } - catch (AggregateException ) + catch (AggregateException) { //handle exceptions here } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs index 63649a6a1490c..6a8da96d38e5b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Threading; @@ -27,9 +27,9 @@ public static async Task Main() // and also to the task so it can cancel before execution starts. var cancellableTask = Task.Run(() => { DoSomeWork(token); - Console.WriteLine("Cancellable: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Cancellable: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Main: Cancellable Task {0} created", cancellableTask.Id); + Console.WriteLine($"Main: Cancellable Task {cancellableTask.Id} created"); tasks.Add(cancellableTask); var parentTask = Task.Run(() => @@ -44,17 +44,17 @@ public static async Task Main() // to each user delegate and to Task.Run. var childTask = Task.Run(() => { DoSomeWork(token); - Console.WriteLine("Child: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Child: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Parent: Task {0} created", childTask.Id); + Console.WriteLine($"Parent: Task {childTask.Id} created"); tasks.Add(childTask); DoSomeWork(token, maxIterations: 1); } - Console.WriteLine("Parent: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Parent: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Main: Parent Task {0} created", parentTask.Id); + Console.WriteLine($"Main: Parent Task {parentTask.Id} created"); tasks.Add(parentTask); // Request cancellation from the UI thread. @@ -85,7 +85,7 @@ public static async Task Main() // Display status of all tasks. foreach (var task in tasks) { - Console.WriteLine("Main: Task {0} status is now {1}", task.Id, task.Status); + Console.WriteLine($"Main: Task {task.Id} status is now {task.Status}"); } } @@ -94,7 +94,7 @@ static void DoSomeWork(CancellationToken ct, int maxIterations = 10) // Was cancellation already requested? if (ct.IsCancellationRequested) { - Console.WriteLine("Task {0} was cancelled before it got started.", Task.CurrentId); + Console.WriteLine($"Task {Task.CurrentId} was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } @@ -112,7 +112,7 @@ static void DoSomeWork(CancellationToken ct, int maxIterations = 10) if (ct.IsCancellationRequested) { - Console.WriteLine("Task {0} work cancelled", Task.CurrentId); + Console.WriteLine($"Task {Task.CurrentId} work cancelled"); ct.ThrowIfCancellationRequested(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs index 8928ce0786066..877845c31a8d6 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs @@ -1,4 +1,4 @@ - + // @@ -75,7 +75,7 @@ static void Main(string[] args) // Prove that the tasks are now all in a canceled state. for (int i = 0; i < tasks.Length; i++) - Console.WriteLine("task[{0}] status is now {1}", i, tasks[i].Status); + Console.WriteLine($"task[{i}] status is now {tasks[i].Status}"); #endregion } @@ -105,10 +105,10 @@ static void DoSomeWork(int taskNum, CancellationToken ct) // Do a bit of work. Not too much. var sw = new SpinWait(); for (int j = 0; j < 3000; j++) sw.SpinOnce(); - Console.WriteLine("...{0} ", taskNum); + Console.WriteLine($"...{taskNum} "); if (ct.IsCancellationRequested) { - Console.WriteLine("bye from {0}.", taskNum); + Console.WriteLine($"bye from {taskNum}."); Console.WriteLine("\nPress Enter to quit."); ct.ThrowIfCancellationRequested(); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs index c77cf0b452340..3bcbca0dbffa3 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs @@ -19,6 +19,7 @@ public static void Main() Console.WriteLine("Parent has completed."); } } + // The example displays the following output: // Parent task executing. // Attached child starting. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs index f6dbfe5058255..024b8448acf79 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs @@ -3,7 +3,7 @@ using System.Threading; using System.Threading.Tasks; -public class Example +public class Example2 { public static void Main() { @@ -19,6 +19,7 @@ public static void Main() Console.WriteLine("Parent has completed."); } } + // The example displays output like the following: // Parent task executing. // Parent has completed. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs index 54a0c791e6d7e..9f50af8281b77 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs @@ -3,173 +3,33 @@ using System.Threading; using System.Threading.Tasks; -class Example +class Example3 { - static void Main() - { - var outer = Task.Factory.StartNew(() => { + static void Main() + { + var outer = Task.Factory.StartNew(() => + { Console.WriteLine("Outer task executing."); - var nested = Task.Factory.StartNew(() => { - Console.WriteLine("Nested task starting."); - Thread.SpinWait(5000000); - Console.WriteLine("Nested task completing."); - return 42; + var nested = Task.Factory.StartNew(() => + { + Console.WriteLine("Nested task starting."); + Thread.SpinWait(5000000); + Console.WriteLine("Nested task completing."); + return 42; }); // Parent will wait for this detached child. return nested.Result; - }); + }); - Console.WriteLine("Outer has returned {0}.", outer.Result); - } + Console.WriteLine($"Outer has returned {outer.Result}."); + } } + // The example displays the following output: // Outer task executing. // Nested task starting. // Nested task completing. // Outer has returned 42. // - -public class Extra -{ - // //not used yet - static void AttachedChildCancels() - { - var tokenSource = new CancellationTokenSource(); - - Task.Factory.StartNew(() => - { - Console.WriteLine("Press c to cancel"); - if (Console.ReadKey().KeyChar == 'c') - tokenSource.Cancel(); - }); - - var parent = Task.Factory.StartNew(() => - { - Console.WriteLine("Parent task starting."); - var ct = tokenSource.Token; - // tokenSource.Cancel(); - var child = Task.Factory.StartNew(() => - { - Console.WriteLine("Attached child starting."); - // ct.ThrowIfCancellationRequested(); - // Thread.SpinWait(500000000); - for (int i = 0; i < 10000; i++) - { - Thread.SpinWait(50000); - if (ct.IsCancellationRequested) - { - Console.WriteLine("Request noticed in attached child"); - ct.ThrowIfCancellationRequested(); - } - } - Console.WriteLine("Attached child completing."); - return 42; - }, ct); - - Console.WriteLine("child.Result = {0}", child.Result); - return child.Result; - }, tokenSource.Token); - - //try - //{ - // Console.WriteLine("About to wait"); - // parent.Wait(); - - //} - //catch (AggregateException ae) - //{ - // Console.WriteLine("Exception caught"); - // foreach (var v in ae.Flatten().InnerExceptions) - // Console.WriteLine(v.GetType().Name); - //} - tokenSource.Dispose(); - - Console.WriteLine("Parent has returned."); - } - - /* Sample output: - Parent task executing. - Detached child starting. - Detached child completing. - Parent has completed. - */ - // - - static void ChildTaskException() - { - var parent = new Task(() => - { - Console.WriteLine("Parent task executing."); - - //var child1 = Task.Factory.StartNew(() => - // { - // Thread.SpinWait(5000000); - // Console.WriteLine("Attached child running."); - // throw new InvalidOperationException("attached child faulted."); - // }); - - var child2 = Task.Factory.StartNew(() => - { - Thread.SpinWait(70000000); - Console.WriteLine("Detached child running."); - throw new InvalidOperationException("detached child faulted."); - }); - - try - { - child2.Wait(); - } - catch (AggregateException ae) - { - throw ae.InnerException; - } - }); - - parent.Start(); - - try - { - parent.Wait(); - } - catch (AggregateException ae) - { - // Flatten the exception to avoid having to iterate - // nested AggregateExceptions. - foreach (var v in ae.Flatten().InnerExceptions) - { - Console.WriteLine(v.Message); - } - } - } - - static void ChildReturns() - { - - var parent = new Task(() => - { - Console.WriteLine("Parent task executing."); - - var child1 = Task.Factory.StartNew(() => - { - Thread.SpinWait(5000000); - Console.WriteLine("Attached child running."); - return 5; - }); - - //var child2 = Task.Factory.StartNew(() => - //{ - // Thread.SpinWait(70000000); - // Console.WriteLine("Detached child running."); - // throw new InvalidOperationException("detached child faulted."); - //}); - - return child1.Result; - }); - - parent.Start(); - - Console.WriteLine(parent.Result); - } - } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs index 7f9989c841f09..31435c41763ee 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs @@ -3,24 +3,27 @@ using System.Threading; using System.Threading.Tasks; -public class Example +public class Example4 { - public static void Main() - { - var parent = Task.Factory.StartNew(() => { - Console.WriteLine("Outer task executing."); + public static void Main() + { + Task parent = Task.Factory.StartNew(() => + { + Console.WriteLine("Outer task executing."); - var child = Task.Factory.StartNew(() => { - Console.WriteLine("Nested task starting."); - Thread.SpinWait(500000); - Console.WriteLine("Nested task completing."); - }); - }); + Task child = Task.Factory.StartNew(() => + { + Console.WriteLine("Nested task starting."); + Thread.SpinWait(500000); + Console.WriteLine("Nested task completing."); + }); + }); - parent.Wait(); - Console.WriteLine("Outer has completed."); - } + parent.Wait(); + Console.WriteLine("Outer has completed."); + } } + // The example produces output like the following: // Outer task executing. // Nested task starting. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs index 2c19bdf70826e..6d35934f49ecb 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -51,19 +51,17 @@ static void RunWidget(Contoso.Widget widget, // Wait for the parent task to finish. Console.WriteLine("Waiting for parent task to finish..."); runWidget.Wait(); - Console.WriteLine("Parent task has finished. Elapsed time is {0} ms.", - stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Parent task has finished. Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); // Perform more work... Console.WriteLine("Performing more work on the main thread..."); Thread.Sleep(2000); - Console.WriteLine("Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); // Wait for the child task to finish. Console.WriteLine("Waiting for child task to finish..."); runWidget.Result.Wait(); - Console.WriteLine("Child task has finished. Elapsed time is {0} ms.", - stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Child task has finished. Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); } static void Main(string[] args) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs index 60e7b31876ffe..d8460f665e74d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs @@ -1,4 +1,4 @@ -namespace ThreadLocalFor +namespace ThreadLocalFor { // using System; @@ -22,7 +22,7 @@ static void Main() }, subtotal => Interlocked.Add(ref total, subtotal)); - Console.WriteLine("The total is {0:N0}", total); + Console.WriteLine($"The total is {total:N0}"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } @@ -68,7 +68,7 @@ static void ComputeHeron(double x, int precision) int places = (from c in precision.ToString().ToCharArray() where c == '0' select c).Count(); - Console.WriteLine("The square root of {0} to {1} places is {2}", x, places, r); + Console.WriteLine($"The square root of {x} to {places} places is {r}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs index 18d1ba928cbf4..681f14aa0680b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; using System.Threading; @@ -25,7 +25,7 @@ static void Main() // finalResult is the final value of subtotal for a particular partition. (finalResult) => Interlocked.Add(ref total, finalResult)); - Console.WriteLine("The total from Parallel.ForEach is {0:N0}", total); + Console.WriteLine($"The total from Parallel.ForEach is {total:N0}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs index 80be43ab95264..34d417381fe75 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs @@ -1,4 +1,4 @@ -// +// namespace CancelParallelLoops { using System; @@ -35,7 +35,7 @@ static void Main() Parallel.ForEach(nums, options, (num) => { double d = Math.Sqrt(num); - Console.WriteLine("{0} on {1}", d, Environment.CurrentManagedThreadId); + Console.WriteLine($"{d} on {Environment.CurrentManagedThreadId}"); }); } catch (OperationCanceledException e) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs index 2348e948ad6c4..89451c8c42528 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Diagnostics; @@ -150,7 +150,7 @@ public static void TraverseTreeParallelForEach(string root, Action actio } // For diagnostic purposes. - Console.WriteLine("Processed {0} files in {1} milliseconds", fileCount, sw.ElapsedMilliseconds); + Console.WriteLine($"Processed {fileCount} files in {sw.ElapsedMilliseconds} milliseconds"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs index d2534a40bba23..400d703d742c0 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -130,7 +130,7 @@ private static void OfferToPrint(int rowCount, int colCount, double[,] matrix) Console.WriteLine(); for (int x = 0; x < rowCount; x++) { - Console.WriteLine("ROW {0}: ", x); + Console.WriteLine($"ROW {x}: "); for (int y = 0; y < colCount; y++) { Console.Write("{0:#.##} ", matrix[x, y]); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs index 91e5a3a41d3c0..e9bbd6e37ceee 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -72,7 +72,7 @@ static void ParallelLoopsWithPartitioner() } ); - Console.WriteLine("elapsed for Parallel.For: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for Parallel.For: {sw.ElapsedMilliseconds}"); sw = Stopwatch.StartNew(); @@ -84,7 +84,7 @@ static void ParallelLoopsWithPartitioner() { double d = (double)x * Math.PI; }); - Console.WriteLine("elapsed for PLINQ with load-balancing: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for PLINQ with load-balancing: {sw.ElapsedMilliseconds}"); // Console.WriteLine("Clearing memory cache"); @@ -101,7 +101,7 @@ static void ParallelLoopsWithPartitioner() double d = (double)x * Math.PI; }); - Console.WriteLine("elapsed for PLINQ without load-balancing: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for PLINQ without load-balancing: {sw.ElapsedMilliseconds}"); } static void TestLoadBalancingCreateMethods() @@ -303,7 +303,7 @@ private int[] CalculatePartitions(int partitionCount, int sourceLength) IEnumerator GetItemsForPartition(int start, int end) { // For demonstration purposes. Each thread receives its own enumerator. - Console.WriteLine("called on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"called on thread {Thread.CurrentThread.ManagedThreadId}"); for (int i = start; i < end; i++) yield return source[i]; } @@ -322,7 +322,7 @@ public static void Main2() select ProcessData(n); foreach (var v in query) { } - Console.WriteLine("Processing time with custom partitioner {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"Processing time with custom partitioner {sw.ElapsedMilliseconds}"); var source2 = Enumerable.Range(0, 10000).ToArray(); @@ -332,7 +332,7 @@ public static void Main2() select ProcessData(n); foreach (var v in query2) { } - Console.WriteLine("Processing time with default partitioner {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"Processing time with default partitioner {sw.ElapsedMilliseconds}"); } // Consistent processing time for measurement purposes. @@ -390,12 +390,12 @@ public static int[] CalculatePartitionsWithoutUsingSlope(int partitions, int sou int[] boundaries = new int[partitions]; boundaries[0] = 0; - // Console.WriteLine("totalWork = {0}", sourceLength); + // Console.WriteLine($"totalWork = {sourceLength}"); double partitionSize = (sourceLength / partitions); double location = 0; for (int i = 0; i < boundaries.Length; i++) { - Console.WriteLine("length = {0}", location); + Console.WriteLine($"length = {location}"); boundaries[i] = (int)(Math.Floor(Math.Sqrt(location) * 100)); location = partitionSize * (i + 1); } @@ -417,7 +417,7 @@ public static int[] CalculatePartitions(double height, double len, int partition for (int i = 1; i < boundaries.Length; i++) { double area = partitionSize * (ulong)(i); - Console.WriteLine("area = {0}", area); + Console.WriteLine($"area = {area}"); boundaries[i] = (int)Math.Floor(Math.Sqrt((2 * area) / slope)); } Console.WriteLine("len={0} height={1} area={2} hyp={3:###.##}", height, len, height * len, Math.Sqrt(height * height + len * len)); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj new file mode 100644 index 0000000000000..ccf02451ac864 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net9.0-windows + true + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs index 91bcda06535f9..becc561aa932e 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs @@ -1,18 +1,16 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; using System.IO; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; +using System.Windows.Forms; namespace pitfalls_cs { class Program { - Button button1 = new Button(); - Button button2 = new Button(); + Button button1 = new(); + Button button2 = new(); int N = 100; static void Main(string[] args) { @@ -24,14 +22,12 @@ static void Main(string[] args) { if (j == Environment.ProcessorCount) { - Console.WriteLine("Set on {0} with value of {1}", - Thread.CurrentThread.ManagedThreadId, j); + Console.WriteLine($"Set on {Thread.CurrentThread.ManagedThreadId} with value of {j}"); mre.Set(); } else { - Console.WriteLine("Waiting on {0} with value of {1}", - Thread.CurrentThread.ManagedThreadId, j); + Console.WriteLine($"Waiting on {Thread.CurrentThread.ManagedThreadId} with value of {j}"); mre.Wait(); } }); //deadlocks @@ -51,7 +47,7 @@ private void button1_Click(object sender, EventArgs e) static void DisplayProgress(int i) { } // - private void button1_Click(object sender, EventArgs e) + private void button2_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => Parallel.For(0, N, i => @@ -65,13 +61,13 @@ private void button1_Click(object sender, EventArgs e) private void Urg() { - string path = @"C\"; - // - FileStream fs = File.OpenWrite(path); - byte[] bytes = new Byte[10000000]; - // ... - Parallel.For(0, bytes.Length, (i) => fs.WriteByte(bytes[i])); - // + string path = @"C\"; + // + FileStream fs = File.OpenWrite(path); + byte[] bytes = new Byte[10000000]; + // ... + Parallel.For(0, bytes.Length, (i) => fs.WriteByte(bytes[i])); + // } } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs index d7b27e06d0613..4815488ea4d63 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -13,8 +13,7 @@ public static void Main() int taskNo = ctr; Task.Factory.StartNew((x) => { Thread.SpinWait(5000000); - Console.WriteLine("Attached child #{0} completed.", - x); + Console.WriteLine($"Attached child #{x} completed."); }, taskNo, TaskCreationOptions.AttachedToParent); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs index 854062a499fe3..7e81840c931c6 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -25,8 +25,7 @@ public static void Main() return; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Task #{0} created at {1} on thread #{2}.", - data.Name, data.CreationTime, data.ThreadNum); + Console.WriteLine($"Task #{data.Name} created at {data.CreationTime} on thread #{data.ThreadNum}."); }, new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks} ); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs index cdae539ae7a9f..9c018a08fe00b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -23,8 +23,7 @@ public static void Main() taskArray[i] = Task.Factory.StartNew( (Object obj) => { var data = new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks}; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Task #{0} created at {1} on thread #{2}.", - data.Name, data.CreationTime, data.ThreadNum); + Console.WriteLine($"Task #{data.Name} created at {data.CreationTime} on thread #{data.ThreadNum}."); }, i ); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs index 8ed8375d9088e..9a37ef448a052 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -15,8 +15,7 @@ public static void Main() taskA.Start(); // Output a message from the calling thread. - Console.WriteLine("Hello from thread '{0}'.", - Thread.CurrentThread.Name); + Console.WriteLine($"Hello from thread '{Thread.CurrentThread.Name}'."); taskA.Wait(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs index 9d38dac76a8b5..25bbcc93353db 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading.Tasks; @@ -19,7 +19,7 @@ public static void Main() i == taskArray.Length - 1 ? "= " : "+ "); sum += results[i]; } - Console.WriteLine("{0:N1}", sum); + Console.WriteLine($"{sum:N1}"); } private static Double DoComputation(Double start) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs index 25d37ef83f9f9..fdfdfc059c82b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -15,8 +15,7 @@ public static void Main() Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA.")); // Output a message from the calling thread. - Console.WriteLine("Hello from thread '{0}'.", - Thread.CurrentThread.Name); + Console.WriteLine($"Hello from thread '{Thread.CurrentThread.Name}'."); taskA.Wait(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs index 0c937f32d8efb..c04eb5c9b5040 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -73,8 +73,7 @@ static void TaskDemo2() { MyCustomData mydata = (MyCustomData) obj; mydata.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Hello from Task #{0} created at {1} running on thread #{2}.", - mydata.Name, mydata.CreationTime, mydata.ThreadNum); + Console.WriteLine($"Hello from Task #{mydata.Name} created at {mydata.CreationTime} running on thread #{mydata.ThreadNum}."); }, new MyCustomData () {Name = i, CreationTime = DateTime.Now.Ticks} ); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs index 1a4a060ca98d4..6c36a1930e0d5 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -137,7 +137,7 @@ static byte Compute(byte[] data) foreach (byte item in data) { final ^= item; - Console.WriteLine("{0:x}", final); + Console.WriteLine($"{final:x}"); } Console.WriteLine("Done computing"); return final; diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs index f47cca0cd241e..05b670124c9ed 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.Collections.Generic; @@ -158,7 +158,7 @@ static int GetEmployeeID(string lastName, string firstName, // Posts random Employee data to the provided target block. static void PostRandomEmployees(ITargetBlock target, int count) { - Console.WriteLine("Adding {0} entries to Employee table...", count); + Console.WriteLine($"Adding {count} entries to Employee table..."); for (int i = 0; i < count; i++) { @@ -237,13 +237,11 @@ static void GetRandomEmployees(string connectionString, int batchSize, Console.WriteLine("Received a batch..."); foreach (Employee e in data.Item1) { - Console.WriteLine("Last={0} First={1} ID={2}", - e.LastName, e.FirstName, e.EmployeeID); + Console.WriteLine($"Last={e.LastName} First={e.FirstName} ID={e.EmployeeID}"); } // Print the error count for this batch. - Console.WriteLine("There were {0} errors in this batch...", - data.Item2.Count); + Console.WriteLine($"There were {data.Item2.Count} errors in this batch..."); // Update total error count. totalErrors += data.Item2.Count; @@ -287,7 +285,7 @@ static void GetRandomEmployees(string connectionString, int batchSize, printEmployees.Completion.Wait(); // Print the total error count. - Console.WriteLine("Finished. There were {0} total errors.", totalErrors); + Console.WriteLine($"Finished. There were {totalErrors} total errors."); } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs index 308e4e90155b0..524788fe098b7 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -50,7 +50,7 @@ static void Main(string[] args) int messageCount = processorCount; // Print the number of processors on this computer. - Console.WriteLine("Processor count = {0}.", processorCount); + Console.WriteLine($"Processor count = {processorCount}."); TimeSpan elapsed; diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs index bb4b1ccc8136a..2a0509b7cd6ce 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -226,15 +226,13 @@ static void ShowJoinBlock() switch (data.Item3) { case '+': - Console.WriteLine("{0} + {1} = {2}", - data.Item1, data.Item2, data.Item1 + data.Item2); + Console.WriteLine($"{data.Item1} + {data.Item2} = {data.Item1 + data.Item2}"); break; case '-': - Console.WriteLine("{0} - {1} = {2}", - data.Item1, data.Item2, data.Item1 - data.Item2); + Console.WriteLine($"{data.Item1} - {data.Item2} = {data.Item1 - data.Item2}"); break; default: - Console.WriteLine("Unknown operator '{0}'.", data.Item3); + Console.WriteLine($"Unknown operator '{data.Item3}'."); break; } } @@ -316,7 +314,7 @@ static void ShowCompletion() // is less than zero. var throwIfNegative = new ActionBlock(n => { - Console.WriteLine("n = {0}", n); + Console.WriteLine($"n = {n}"); if (n < 0) { throw new ArgumentOutOfRangeException(); @@ -364,7 +362,7 @@ static void ShowCompletionStatus() // is less than zero. var throwIfNegative = new ActionBlock(n => { - Console.WriteLine("n = {0}", n); + Console.WriteLine($"n = {n}"); if (n < 0) { throw new ArgumentOutOfRangeException(); @@ -375,8 +373,7 @@ static void ShowCompletionStatus() // task status to the console when the block finishes. throwIfNegative.Completion.ContinueWith(task => { - Console.WriteLine("The status of the completion task is '{0}'.", - task.Status); + Console.WriteLine($"The status of the completion task is '{task.Status}'."); }); // Post values to the block. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs index c02781b84a536..51732377b94f2 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -20,7 +20,7 @@ static void Main() // Downloads the requested resource as a string. var downloadString = new TransformBlock(async uri => { - Console.WriteLine("Downloading '{0}'...", uri); + Console.WriteLine($"Downloading '{uri}'..."); return await new HttpClient(new HttpClientHandler{ AutomaticDecompression = System.Net.DecompressionMethods.GZip }).GetStringAsync(uri); }); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs index 91eff05160235..38ec1f00e4f7e 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks.Dataflow; @@ -61,7 +61,7 @@ static void Main(string[] args) cts.Cancel(); // Print the result to the console. - Console.WriteLine("The solution is {0}.", result); + Console.WriteLine($"The solution is {result}."); cts.Dispose(); } diff --git a/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs b/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs index 07b0e1d2cb2ad..9a6e500793d66 100644 --- a/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs +++ b/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; using System.Transactions; @@ -19,9 +19,9 @@ static void Main() catch (Exception ex) { Console.WriteLine(""); - Console.WriteLine("In calling code: {0}", ex.Message); + Console.WriteLine($"In calling code: {ex.Message}"); } - Console.WriteLine("return value in caller {0}", r); + Console.WriteLine($"return value in caller {r}"); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs index 764ba2d5950a5..3a2a4b7f1d91c 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs @@ -1,4 +1,4 @@ -namespace FromClause; +namespace FromClause; // class LowNums @@ -64,7 +64,7 @@ where score > 90 // (Last) and an int (score). foreach (var student in scoreQuery) { - Console.WriteLine("{0} Score: {1}", student.Last, student.score); + Console.WriteLine($"{student.Last} Score: {student.score}"); } } } @@ -108,14 +108,14 @@ from upper in upperCase // Rest the mouse pointer on joinQuery1 to verify its type. foreach (var pair in joinQuery1) { - Console.WriteLine("{0} is matched to {1}", pair.upper, pair.lower); + Console.WriteLine($"{pair.upper} is matched to {pair.lower}"); } Console.WriteLine("Filtered non-equijoin:"); // Rest the mouse pointer over joinQuery2 to verify its type. foreach (var pair in joinQuery2) { - Console.WriteLine("{0} is matched to {1}", pair.lower, pair.upper); + Console.WriteLine($"{pair.lower} is matched to {pair.upper}"); } // Keep the console window open in debug mode. diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs index 8bdbb2aeb34e6..0846cd1f286d6 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs @@ -1,4 +1,4 @@ -namespace Group; +namespace Group; using CommonTypes; // For the group clause topic, we only use bits and pieces of this class. The same @@ -168,7 +168,7 @@ orderby g.Key foreach (var studentGroup in studentQuery) { int temp = studentGroup.Key * 10; - Console.WriteLine("Students with an average between {0} and {1}", temp, temp + 10); + Console.WriteLine($"Students with an average between {temp} and {temp + 10}"); foreach (var student in studentGroup) { Console.WriteLine(" {0}, {1}:{2}", student.Last, student.First, student.Scores.Average()); @@ -204,7 +204,7 @@ from w in words // Execute the query. foreach (var wordGroup in wordGroups) { - Console.WriteLine("Words that start with the letter '{0}':", wordGroup.Key); + Console.WriteLine($"Words that start with the letter '{wordGroup.Key}':"); foreach (var word in wordGroup) { Console.WriteLine(word); @@ -244,10 +244,10 @@ group w by w[0] into grps // Execute the query. foreach (var wordGroup in wordGroups2) { - Console.WriteLine("Groups that start with a vowel: {0}", wordGroup.Key); + Console.WriteLine($"Groups that start with a vowel: {wordGroup.Key}"); foreach (var word in wordGroup) { - Console.WriteLine(" {0}", word); + Console.WriteLine($" {word}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs index 356a054c20241..33e6f01a84521 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs @@ -1,4 +1,4 @@ -namespace IntoClause; +namespace IntoClause; // class IntoSample1 @@ -20,7 +20,7 @@ where fruitGroup.Count() >= 2 // not the items in each group foreach (var item in wordGroups1) { - Console.WriteLine(" {0} has {1} elements.", item.FirstLetter, item.Words); + Console.WriteLine($" {item.FirstLetter} has {item.Words} elements."); } } } @@ -47,7 +47,7 @@ from w in words2 // and the items in each group. foreach (var item in wordGroups2) { - Console.WriteLine("Words that start with the letter '{0}':", item.Key); + Console.WriteLine($"Words that start with the letter '{item.Key}':"); foreach (var w in item) { Console.WriteLine(w); diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs index 63c546dffbcec..a37f0fb431278 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs @@ -1,4 +1,4 @@ -namespace Joins; +namespace Joins; // @@ -151,10 +151,10 @@ orderby prod.CategoryID foreach (var item in groupJoinQuery3) { totalItems++; - Console.WriteLine(" {0}:{1}", item.ProductName, item.Category); + Console.WriteLine($" {item.ProductName}:{item.Category}"); } - Console.WriteLine("GroupJoin3: {0} items in 1 group", totalItems); + Console.WriteLine($"GroupJoin3: {totalItems} items in 1 group"); Console.WriteLine(System.Environment.NewLine); } @@ -206,7 +206,7 @@ from item in prodGroup.DefaultIfEmpty() totalItems++; Console.WriteLine("{0,-10}{1}", item.Name, item.CategoryID); } - Console.WriteLine("LeftOuterJoin2: {0} items in 1 group", totalItems); + Console.WriteLine($"LeftOuterJoin2: {totalItems} items in 1 group"); } } /*Output: diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs index e991474252bb6..494c70f199d6e 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs @@ -1,4 +1,4 @@ -namespace LetClause; +namespace LetClause; // class LetSample1 @@ -27,7 +27,7 @@ from word in words // Execute the query. foreach (var v in earlyBirdQuery) { - Console.WriteLine("\"{0}\" starts with a vowel", v); + Console.WriteLine($"\"{v}\" starts with a vowel"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs index 4d815f48a71e0..fa5e5295d3ccc 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs @@ -1,4 +1,4 @@ -namespace SelectClause; +namespace SelectClause; // class SelectSample1 @@ -132,7 +132,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery4: select range_variable[index]"); foreach (int i in studentQuery4) { - Console.WriteLine("First score = {0}", i); + Console.WriteLine($"First score = {i}"); } // Produce a filtered sequence of doubles @@ -145,7 +145,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery5: select expression"); foreach (double d in studentQuery5) { - Console.WriteLine("Adjusted first score = {0}", d); + Console.WriteLine($"Adjusted first score = {d}"); } // Produce a filtered sequence of doubles that are @@ -158,7 +158,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery6: select expression2"); foreach (double d in studentQuery6) { - Console.WriteLine("Average = {0}", d); + Console.WriteLine($"Average = {d}"); } // Produce a filtered sequence of anonymous types diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs index 05a93922dd561..9196f9a47fa56 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; // @@ -190,7 +190,7 @@ static void Main() } catch (System.InvalidCastException e) { - System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message); + System.Console.WriteLine($"{e.Message} Error: Incorrect unboxing."); } } } @@ -210,7 +210,7 @@ static void Main(string[] args) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); - Console.WriteLine("int: {0}", i); + Console.WriteLine($"int: {i}"); // Output: int: 25 // } @@ -326,7 +326,7 @@ static void Main() byte[] floatVals = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatVals, 0); - Console.WriteLine("float convert = {0}", f); + Console.WriteLine($"float convert = {f}"); // Output: 200.0056 // diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs index a8647352ae8da..6eb2d86f920b8 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -179,7 +179,7 @@ where student.Id > 111 // Variable str could be declared by using var instead of string. foreach (string str in queryId) { - Console.WriteLine("Last name: {0}", str); + Console.WriteLine($"Last name: {str}"); } // } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs index b773ca3093b81..22c5c8e775b7f 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -123,7 +123,7 @@ where student.Id > 115 Console.WriteLine("Execute first query:"); foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } // This query filters on the results of the first query. @@ -142,7 +142,7 @@ where student.Id < 117 foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } // Reuse query variable for a completely new query. Note that @@ -155,7 +155,7 @@ orderby student.LastName Console.WriteLine(System.Environment.NewLine + "Reuse query variable for a new query:"); foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } } /* Output: @@ -518,7 +518,7 @@ from file in files { foreach (var item in exceptionDemoQuery) { - Console.WriteLine("Processing {0}", item); + Console.WriteLine($"Processing {item}"); } } @@ -662,7 +662,7 @@ orderby newGroup.Key foreach (var nameGroup in queryLastNames) { - Console.WriteLine("Key: {0}", nameGroup.Key); + Console.WriteLine($"Key: {nameGroup.Key}"); foreach (var student in nameGroup) { Console.WriteLine("\t{0}, {1}", student.LastName, student.FirstName); @@ -710,10 +710,10 @@ orderby studentGroup.Key.FirstLetter foreach (var scoreGroup in queryHighScoreGroups) { string s = scoreGroup.Key.Score == true ? "more than" : "less than"; - Console.WriteLine("Name starts with {0} who scored {1} 85", scoreGroup.Key.FirstLetter, s); + Console.WriteLine($"Name starts with {scoreGroup.Key.FirstLetter} who scored {s} 85"); foreach (var item in scoreGroup) { - Console.WriteLine("\t{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"\t{item.FirstName} {item.LastName}"); } } } @@ -756,9 +756,9 @@ by student.ExamScores.Average() > 75 into studentGroup foreach (var studentGroup in queryGroupByAverages) { - Console.WriteLine("Key: {0}", studentGroup.Key); + Console.WriteLine($"Key: {studentGroup.Key}"); foreach (var student in studentGroup) - Console.WriteLine("\t{0} {1}", student.FirstName, student.LastName); + Console.WriteLine($"\t{student.FirstName} {student.LastName}"); } } /* Output: @@ -835,7 +835,7 @@ from student in students foreach (var studentGroup in queryFirstLetters) { - Console.WriteLine("Key: {0}", studentGroup.Key); + Console.WriteLine($"Key: {studentGroup.Key}"); // Nested foreach is required to access group items. foreach (var student in studentGroup) { @@ -896,11 +896,11 @@ select student2.ExamScores.Average()).Max() }; int count = queryGroupMax.Count(); - Console.WriteLine("Number of groups = {0}", count); + Console.WriteLine($"Number of groups = {count}"); foreach (var item in queryGroupMax) { - Console.WriteLine(" {0} Highest Score={1}", item.Level, item.HighestScore); + Console.WriteLine($" {item.Level} Highest Score={item.HighestScore}"); } } // @@ -935,13 +935,13 @@ from newGroup2 in // cursor over the iteration variables to see their actual type. foreach (var outerGroup in queryNestedGroups) { - Console.WriteLine("DataClass.Student Level = {0}", outerGroup.Key); + Console.WriteLine($"DataClass.Student Level = {outerGroup.Key}"); foreach (var innerGroup in outerGroup) { - Console.WriteLine("\tNames that begin with: {0}", innerGroup.Key); + Console.WriteLine($"\tNames that begin with: {innerGroup.Key}"); foreach (var innerGroupElement in innerGroup) { - Console.WriteLine("\t\t{0} {1}", innerGroupElement.LastName, innerGroupElement.FirstName); + Console.WriteLine($"\t\t{innerGroupElement.LastName} {innerGroupElement.FirstName}"); } } } @@ -1030,7 +1030,7 @@ where ids.Contains(i) foreach (var name in queryNames) { - Console.WriteLine("{0}: {1}", name.LastName, name.Id); + Console.WriteLine($"{name.LastName}: {name.Id}"); } } } @@ -1087,7 +1087,7 @@ static void QueryByYear(string level) Console.WriteLine("The following students are at level {0}", year.ToString()); foreach (Student name in studentQuery) { - Console.WriteLine("{0}: {1}", name.LastName, name.Id); + Console.WriteLine($"{name.LastName}: {name.Id}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs index 0a93af9ca52cd..9d11243209589 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs @@ -1,4 +1,4 @@ -namespace CsCsrefProgrammingProperties +namespace CsCsrefProgrammingProperties { using System.Linq; using System.Collections.Generic; @@ -93,8 +93,8 @@ static void Main() Cube c = new Cube(side); // Display the results: - System.Console.WriteLine("Area of the square = {0:F2}", s.Area); - System.Console.WriteLine("Area of the cube = {0:F2}", c.Area); + System.Console.WriteLine($"Area of the square = {s.Area:F2}"); + System.Console.WriteLine($"Area of the cube = {c.Area:F2}"); System.Console.WriteLine(); // Input the area: @@ -106,8 +106,8 @@ static void Main() c.Area = area; // Display the results: - System.Console.WriteLine("Side of the square = {0:F2}", s.side); - System.Console.WriteLine("Side of the cube = {0:F2}", c.side); + System.Console.WriteLine($"Side of the square = {s.side:F2}"); + System.Console.WriteLine($"Side of the cube = {c.side:F2}"); } } /* Example Output: @@ -201,7 +201,7 @@ where s.Contains('x') System.Console.WriteLine(s); //ROC allows [] access - Console.WriteLine("names_3[0] = {0}", ro.Names_3[0]); + Console.WriteLine($"names_3[0] = {ro.Names_3[0]}"); //throws runtime exceptions on unimplemented interface methods IList myList = (IList)ro.Names_3; diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs index 923b8397ceef6..718b73ab43a12 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs @@ -1,4 +1,4 @@ -namespace CsCsrefProgrammingStatements +namespace CsCsrefProgrammingStatements { //--------------------------------------------------------------------------- public class SimpleStatements @@ -29,8 +29,7 @@ public static void Main() // Expression statement (method invocation). A single-line // statement can span multiple text lines because line breaks // are treated as white space, which is ignored by the compiler. - System.Console.WriteLine("Radius of circle #{0} is {1}. Circumference = {2:N2}", - counter, radius, circumference); + System.Console.WriteLine($"Radius of circle #{counter} is {radius}. Circumference = {circumference:N2}"); // Expression statement (postfix increment). counter++; @@ -285,14 +284,14 @@ public static void Main() int i = 5; Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB)); - Console.WriteLine("pointA == pointB = {0}", pointA == pointB); + Console.WriteLine($"pointA == pointB = {pointA == pointB}"); Console.WriteLine("null comparison = {0}", pointA.Equals(pointC)); Console.WriteLine("Compare to some other type = {0}", pointA.Equals(i)); TwoDPoint pointD = null; TwoDPoint pointE = null; - Console.WriteLine("Two null TwoDPoints are equal: {0}", pointD == pointE); + Console.WriteLine($"Two null TwoDPoints are equal: {pointD == pointE}"); pointE = new TwoDPoint(3, 4); Console.WriteLine("(pointE == pointA) = {0}", pointE == pointA); @@ -343,7 +342,7 @@ public static void Main() int uniqueObjects = list.Count(); - Console.WriteLine("there are {0} unique objects", uniqueObjects); + Console.WriteLine($"there are {uniqueObjects} unique objects"); var uniqueHashCodes = (from item in list select item.GetHashCode()) @@ -354,7 +353,7 @@ select item.GetHashCode()) // This only shows the number of unique values, not the evenness // of their distribution. For that there is a LINQ query example in the docs // how to group by a range. - Console.WriteLine("there are {0} unique hash codes", hashCodeCount); + Console.WriteLine($"there are {hashCodeCount} unique hash codes"); Console.WriteLine("Distribution:"); @@ -447,7 +446,7 @@ public static void Main() // True: Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB)); // True: - Console.WriteLine("pointA == pointB = {0}", pointA == pointB); + Console.WriteLine($"pointA == pointB = {pointA == pointB}"); // True: Console.WriteLine("object.Equals(pointA, pointB) = {0}", object.Equals(pointA, pointB)); // False: @@ -459,7 +458,7 @@ public static void Main() // False: Console.WriteLine("pointA.Equals(i) = {0}", pointA.Equals(i)); // CS0019: - // Console.WriteLine("pointA == i = {0}", pointA == i); + // Console.WriteLine($"pointA == i = {pointA == i}"); // Compare unboxed to boxed. System.Collections.ArrayList list = new System.Collections.ArrayList(); @@ -473,7 +472,7 @@ public static void Main() // False: Console.WriteLine("pointA == (pointC = null) = {0}", pointA == pointC); // True: - Console.WriteLine("pointC == pointD = {0}", pointC == pointD); + Console.WriteLine($"pointC == pointD = {pointC == pointD}"); TwoDPoint temp = new TwoDPoint(3, 4); pointC = temp; diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs index da42593a42bea..24ffbf2ac57fc 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -13,8 +13,8 @@ public class Person public virtual void GetInfo() { - Console.WriteLine("Name: {0}", name); - Console.WriteLine("SSN: {0}", ssn); + Console.WriteLine($"Name: {name}"); + Console.WriteLine($"SSN: {ssn}"); } } class Employee : Person @@ -24,7 +24,7 @@ public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); - Console.WriteLine("Employee ID: {0}", id); + Console.WriteLine($"Employee ID: {id}"); } } @@ -131,7 +131,7 @@ public Employee(string name, string alias) // Printing method: public void printEmployee() { - Console.WriteLine("Name: {0}\nAlias: {1}", name, alias); + Console.WriteLine($"Name: {name}\nAlias: {alias}"); // Passing the object to the CalcTax method by using this: Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this)); } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj index f0609045a05b6..4ac4d4420a54d 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net8.0 diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs index 1f77b65709a4b..79b68a101306e 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs @@ -7,7 +7,7 @@ class Program { class MyClass { - public void MyMethod() { } + public static void MyMethod() { } } static void Main() @@ -30,7 +30,7 @@ static void Main() mc = new MyClass(); // You can call its method. - mc.MyMethod(); + MyClass.MyMethod(); // Set mc to null again. The object it referenced // is no longer accessible and can now be garbage-collected. @@ -38,17 +38,17 @@ static void Main() // A null string is not the same as an empty string. string s = null; - string t = String.Empty; // Logically the same as "" + string t = string.Empty; // Logically the same as "" // Equals applied to any null object returns false. - Console.WriteLine("t.Equals(s) is {0}", t.Equals(s)); + Console.WriteLine($"t.Equals(s) is {t.Equals(s)}"); // Equality operator also returns false when one // operand is null. - Console.WriteLine("Empty string {0} null string", s == t ? "equals": "does not equal"); + Console.WriteLine($"Empty string {(s == t ? "equals" : "does not equal")} null string"); // Returns true. - Console.WriteLine("null == null is {0}", null == null); + Console.WriteLine($"null == null is {null == null}"); // A value type cannot be null // int i = null; // Compiler error!