diff --git a/snippets/csharp/System/DBNull/Overview/DBNullExamples.cs b/snippets/csharp/System/DBNull/Overview/DBNullExamples.cs index 2cc2e2db91f..2b4bd3b74ae 100644 --- a/snippets/csharp/System/DBNull/Overview/DBNullExamples.cs +++ b/snippets/csharp/System/DBNull/Overview/DBNullExamples.cs @@ -6,68 +6,68 @@ public class DBNullExample { public static void Main() { - DBNullExample ex = new DBNullExample(); - OleDbConnection conn = new OleDbConnection(); - OleDbCommand cmd = new OleDbCommand(); - OleDbDataAdapter adapter = new OleDbDataAdapter(); - DataSet ds = new DataSet(); - string dbFilename = @"c:\Data\contacts.mdb"; + DBNullExample ex = new(); + OleDbConnection conn = new OleDbConnection(); + OleDbCommand cmd = new OleDbCommand(); + OleDbDataAdapter adapter = new OleDbDataAdapter(); + DataSet ds = new(); + string dbFilename = @"c:\Data\contacts.mdb"; - // Open database connection - conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + - dbFilename + ";"; - conn.Open(); - // Define command : retrieve all records in contact table - cmd.CommandText = "SELECT * FROM Contact"; - cmd.Connection = conn; - adapter.SelectCommand = cmd; - // Fill dataset - ds.Clear(); - adapter.Fill(ds, "Contact"); - // Close connection - conn.Close(); - // Output labels to console - ex.OutputLabels(ds.Tables["Contact"]); - } + // Open database connection + conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + + dbFilename + ";"; + conn.Open(); + // Define command : retrieve all records in contact table + cmd.CommandText = "SELECT * FROM Contact"; + cmd.Connection = conn; + adapter.SelectCommand = cmd; + // Fill dataset + ds.Clear(); + adapter.Fill(ds, "Contact"); + // Close connection + conn.Close(); + // Output labels to console + ex.OutputLabels(ds.Tables["Contact"]); + } - // - private void OutputLabels(DataTable dt) - { - string label; + // + private void OutputLabels(DataTable dt) + { + string label; - // Iterate rows of table - foreach (DataRow row in dt.Rows) - { - int labelLen; - label = String.Empty; - label += AddFieldValue(label, row, "Title"); - label += AddFieldValue(label, row, "FirstName"); - label += AddFieldValue(label, row, "MiddleInitial"); - label += AddFieldValue(label, row, "LastName"); - label += AddFieldValue(label, row, "Suffix"); - label += "\n"; - label += AddFieldValue(label, row, "Address1"); - label += AddFieldValue(label, row, "AptNo"); - label += "\n"; - labelLen = label.Length; - label += AddFieldValue(label, row, "Address2"); - if (label.Length != labelLen) + // Iterate rows of table + foreach (DataRow row in dt.Rows) + { + int labelLen; + label = string.Empty; + label += AddFieldValue(label, row, "Title"); + label += AddFieldValue(label, row, "FirstName"); + label += AddFieldValue(label, row, "MiddleInitial"); + label += AddFieldValue(label, row, "LastName"); + label += AddFieldValue(label, row, "Suffix"); + label += "\n"; + label += AddFieldValue(label, row, "Address1"); + label += AddFieldValue(label, row, "AptNo"); label += "\n"; - label += AddFieldValue(label, row, "City"); - label += AddFieldValue(label, row, "State"); - label += AddFieldValue(label, row, "Zip"); - Console.WriteLine(label); - Console.WriteLine(); - } - } + labelLen = label.Length; + label += AddFieldValue(label, row, "Address2"); + if (label.Length != labelLen) + label += "\n"; + label += AddFieldValue(label, row, "City"); + label += AddFieldValue(label, row, "State"); + label += AddFieldValue(label, row, "Zip"); + Console.WriteLine(label); + Console.WriteLine(); + } + } - private string AddFieldValue(string label, DataRow row, - string fieldName) - { - if (!DBNull.Value.Equals(row[fieldName])) - return (string) row[fieldName] + " "; - else - return String.Empty; - } - // + private string AddFieldValue(string label, DataRow row, + string fieldName) + { + if (!DBNull.Value.Equals(row[fieldName])) + return (string)row[fieldName] + " "; + else + return string.Empty; + } + // } diff --git a/snippets/csharp/System/DateTime/.ctor/ctorexample1.cs b/snippets/csharp/System/DateTime/.ctor/ctorexample1.cs index f2e467ac476..03c244d0101 100644 --- a/snippets/csharp/System/DateTime/.ctor/ctorexample1.cs +++ b/snippets/csharp/System/DateTime/.ctor/ctorexample1.cs @@ -2,67 +2,67 @@ public class Example { - public static void Main() - { - ShowYMD(); - Console.WriteLine("-----"); - ShowYMDHMS(); - Console.WriteLine("-----"); - ShowYMDHMSMs(); - Console.WriteLine("-----"); - ShowYMDHMSKind(); - Console.WriteLine("-----"); - ShowYMDHMSMsKind(); + public static void Main() + { + ShowYMD(); + Console.WriteLine("-----"); + ShowYMDHMS(); + Console.WriteLine("-----"); + ShowYMDHMSMs(); + Console.WriteLine("-----"); + ShowYMDHMSKind(); + Console.WriteLine("-----"); + ShowYMDHMSMsKind(); - void ShowYMD() - { - // - DateTime date1 = new DateTime(2010, 8, 18); - Console.WriteLine(date1.ToString()); - // The example displays the following output: - // 8/18/2010 12:00:00 AM - // - } + void ShowYMD() + { + // + DateTime date1 = new(2010, 8, 18); + Console.WriteLine(date1.ToString()); + // The example displays the following output: + // 8/18/2010 12:00:00 AM + // + } - void ShowYMDHMS() - { - // - DateTime date1 = new DateTime(2010, 8, 18, 16, 32, 0); - Console.WriteLine(date1.ToString()); - // The example displays the following output, in this case for en-us culture: - // 8/18/2010 4:32:00 PM - // - } + void ShowYMDHMS() + { + // + DateTime date1 = new(2010, 8, 18, 16, 32, 0); + Console.WriteLine(date1.ToString()); + // The example displays the following output, in this case for en-us culture: + // 8/18/2010 4:32:00 PM + // + } - void ShowYMDHMSMs() - { - // - DateTime date1 = new DateTime(2010, 8, 18, 16, 32, 18, 500); - Console.WriteLine(date1.ToString("M/dd/yyyy h:mm:ss.fff tt")); - // The example displays the following output, in this case for en-us culture: - // 8/18/2010 4:32:18.500 PM - // - } + void ShowYMDHMSMs() + { + // + DateTime date1 = new(2010, 8, 18, 16, 32, 18, 500); + Console.WriteLine(date1.ToString("M/dd/yyyy h:mm:ss.fff tt")); + // The example displays the following output, in this case for en-us culture: + // 8/18/2010 4:32:18.500 PM + // + } - void ShowYMDHMSKind() - { - // - DateTime date1 = new DateTime(2010, 8, 18, 16, 32, 0, DateTimeKind.Local); - Console.WriteLine("{0} {1}", date1, date1.Kind); - // The example displays the following output, in this case for en-us culture: - // 8/18/2010 4:32:00 PM Local - // - } + void ShowYMDHMSKind() + { + // + DateTime date1 = new(2010, 8, 18, 16, 32, 0, DateTimeKind.Local); + Console.WriteLine($"{date1} {date1.Kind}"); + // The example displays the following output, in this case for en-us culture: + // 8/18/2010 4:32:00 PM Local + // + } - void ShowYMDHMSMsKind() - { - // - DateTime date1 = new DateTime(2010, 8, 18, 16, 32, 18, 500, - DateTimeKind.Local); - Console.WriteLine("{0:M/dd/yyyy h:mm:ss.fff tt} {1}", date1, date1.Kind); - // The example displays the following output, in this case for en-us culture: - // 8/18/2010 4:32:18.500 PM Local - // - } - } + void ShowYMDHMSMsKind() + { + // + DateTime date1 = new(2010, 8, 18, 16, 32, 18, 500, + DateTimeKind.Local); + Console.WriteLine($"{date1:M/dd/yyyy h:mm:ss.fff tt} {date1.Kind}"); + // The example displays the following output, in this case for en-us culture: + // 8/18/2010 4:32:18.500 PM Local + // + } + } } diff --git a/snippets/csharp/System/DateTime/.ctor/ctorexample2.cs b/snippets/csharp/System/DateTime/.ctor/ctorexample2.cs index d342a84760c..d785e5eba52 100644 --- a/snippets/csharp/System/DateTime/.ctor/ctorexample2.cs +++ b/snippets/csharp/System/DateTime/.ctor/ctorexample2.cs @@ -6,46 +6,37 @@ public class Example { - public static void Main() - { - Console.WriteLine("Using the Persian Calendar:"); - PersianCalendar persian = new PersianCalendar(); - DateTime date1 = new DateTime(1389, 5, 27, persian); - Console.WriteLine(date1.ToString()); - Console.WriteLine("{0}/{1}/{2}\n", persian.GetMonth(date1), - persian.GetDayOfMonth(date1), - persian.GetYear(date1)); + public static void Main() + { + Console.WriteLine("Using the Persian Calendar:"); + PersianCalendar persian = new(); + DateTime date1 = new(1389, 5, 27, persian); + Console.WriteLine(date1.ToString()); + Console.WriteLine($"{persian.GetMonth(date1)}/{persian.GetDayOfMonth(date1)}/{persian.GetYear(date1)}\n"); - Console.WriteLine("Using the Hijri Calendar:"); - // Get current culture so it can later be restored. - CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; + Console.WriteLine("Using the Hijri Calendar:"); + // Get current culture so it can later be restored. + CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; - // Define Hijri calendar. - HijriCalendar hijri = new HijriCalendar(); - // Make ar-SY the current culture and Hijri the current calendar. - Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SY"); - CultureInfo current = CultureInfo.CurrentCulture; - current.DateTimeFormat.Calendar = hijri; - string dFormat = current.DateTimeFormat.ShortDatePattern; - // Ensure year is displayed as four digits. - dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy"); - current.DateTimeFormat.ShortDatePattern = dFormat; - DateTime date2 = new DateTime(1431, 9, 9, hijri); - Console.WriteLine("{0} culture using the {1} calendar: {2:d}", current, - GetCalendarName(hijri), date2); + // Define Hijri calendar. + HijriCalendar hijri = new(); + // Make ar-SY the current culture and Hijri the current calendar. + Thread.CurrentThread.CurrentCulture = new("ar-SY"); + CultureInfo current = CultureInfo.CurrentCulture; + current.DateTimeFormat.Calendar = hijri; + string dFormat = current.DateTimeFormat.ShortDatePattern; + // Ensure year is displayed as four digits. + dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy"); + current.DateTimeFormat.ShortDatePattern = dFormat; + DateTime date2 = new(1431, 9, 9, hijri); + Console.WriteLine($"{current} culture using the {GetCalendarName(hijri)} calendar: {date2:d}"); - // Restore previous culture. - Thread.CurrentThread.CurrentCulture = dftCulture; - Console.WriteLine("{0} culture using the {1} calendar: {2:d}", - CultureInfo.CurrentCulture, - GetCalendarName(CultureInfo.CurrentCulture.Calendar), - date2); - } + // Restore previous culture. + Thread.CurrentThread.CurrentCulture = dftCulture; + Console.WriteLine($"{CultureInfo.CurrentCulture} culture using the {GetCalendarName(CultureInfo.CurrentCulture.Calendar)} calendar: {date2:d}"); + } - private static string GetCalendarName(Calendar cal) - { - return Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; - } + private static string GetCalendarName(Calendar cal) => Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; } // The example displays the following output: // Using the Persian Calendar: diff --git a/snippets/csharp/System/DateTime/.ctor/ctorexample4.cs b/snippets/csharp/System/DateTime/.ctor/ctorexample4.cs index ec81b0a4fc8..82730a72677 100644 --- a/snippets/csharp/System/DateTime/.ctor/ctorexample4.cs +++ b/snippets/csharp/System/DateTime/.ctor/ctorexample4.cs @@ -6,51 +6,44 @@ public class Example { - public static void Main() - { - Console.WriteLine("Using the Persian Calendar:"); - PersianCalendar persian = new PersianCalendar(); - DateTime date1 = new DateTime(1389, 5, 27, 16, 32, 0, persian); - Console.WriteLine(date1.ToString()); - Console.WriteLine("{0}/{1}/{2} {3}{6}{4:D2}{6}{5:D2}\n", - persian.GetMonth(date1), - persian.GetDayOfMonth(date1), - persian.GetYear(date1), - persian.GetHour(date1), - persian.GetMinute(date1), - persian.GetSecond(date1), - DateTimeFormatInfo.CurrentInfo.TimeSeparator); + public static void Main() + { + Console.WriteLine("Using the Persian Calendar:"); + PersianCalendar persian = new(); + DateTime date1 = new(1389, 5, 27, 16, 32, 0, persian); + Console.WriteLine(date1.ToString()); + Console.WriteLine("{0}/{1}/{2} {3}{6}{4:D2}{6}{5:D2}\n", + persian.GetMonth(date1), + persian.GetDayOfMonth(date1), + persian.GetYear(date1), + persian.GetHour(date1), + persian.GetMinute(date1), + persian.GetSecond(date1), + DateTimeFormatInfo.CurrentInfo.TimeSeparator); - Console.WriteLine("Using the Hijri Calendar:"); - // Get current culture so it can later be restored. - CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; + Console.WriteLine("Using the Hijri Calendar:"); + // Get current culture so it can later be restored. + CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; - // Define Hijri calendar. - HijriCalendar hijri = new HijriCalendar(); - // Make ar-SY the current culture and Hijri the current calendar. - Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SY"); - CultureInfo current = CultureInfo.CurrentCulture; - current.DateTimeFormat.Calendar = hijri; - string dFormat = current.DateTimeFormat.ShortDatePattern; - // Ensure year is displayed as four digits. - dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy"); - current.DateTimeFormat.ShortDatePattern = dFormat; - DateTime date2 = new DateTime(1431, 9, 9, 16, 32, 18, hijri); - Console.WriteLine("{0} culture using the {1} calendar: {2:g}", current, - GetCalendarName(hijri), date2); + // Define Hijri calendar. + HijriCalendar hijri = new(); + // Make ar-SY the current culture and Hijri the current calendar. + Thread.CurrentThread.CurrentCulture = new("ar-SY"); + CultureInfo current = CultureInfo.CurrentCulture; + current.DateTimeFormat.Calendar = hijri; + string dFormat = current.DateTimeFormat.ShortDatePattern; + // Ensure year is displayed as four digits. + dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy"); + current.DateTimeFormat.ShortDatePattern = dFormat; + DateTime date2 = new(1431, 9, 9, 16, 32, 18, hijri); + Console.WriteLine($"{current} culture using the {GetCalendarName(hijri)} calendar: {date2:g}"); - // Restore previous culture. - Thread.CurrentThread.CurrentCulture = dftCulture; - Console.WriteLine("{0} culture using the {1} calendar: {2:g}", - CultureInfo.CurrentCulture, - GetCalendarName(CultureInfo.CurrentCulture.Calendar), - date2); - } + // Restore previous culture. + Thread.CurrentThread.CurrentCulture = dftCulture; + Console.WriteLine($"{CultureInfo.CurrentCulture} culture using the {GetCalendarName(CultureInfo.CurrentCulture.Calendar)} calendar: {date2:g}"); + } - private static string GetCalendarName(Calendar cal) - { - return Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; - } + private static string GetCalendarName(Calendar cal) => Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; } // The example displays the following output: // Using the Persian Calendar: diff --git a/snippets/csharp/System/DateTime/.ctor/ctorexample6.cs b/snippets/csharp/System/DateTime/.ctor/ctorexample6.cs index 2d55cf51eda..fb8954a6ba1 100644 --- a/snippets/csharp/System/DateTime/.ctor/ctorexample6.cs +++ b/snippets/csharp/System/DateTime/.ctor/ctorexample6.cs @@ -6,56 +6,53 @@ public class Example { - public static void Main() - { - Console.WriteLine("Using the Persian Calendar:"); - PersianCalendar persian = new PersianCalendar(); - DateTime date1 = new DateTime(1389, 5, 27, 16, 32, 18, 500, persian); - Console.WriteLine(date1.ToString("M/dd/yyyy h:mm:ss.fff tt")); - Console.WriteLine("{0}/{1}/{2} {3}{7}{4:D2}{7}{5:D2}.{6:G3}\n", - persian.GetMonth(date1), - persian.GetDayOfMonth(date1), - persian.GetYear(date1), - persian.GetHour(date1), - persian.GetMinute(date1), - persian.GetSecond(date1), - persian.GetMilliseconds(date1), - DateTimeFormatInfo.CurrentInfo.TimeSeparator); + public static void Main() + { + Console.WriteLine("Using the Persian Calendar:"); + PersianCalendar persian = new(); + DateTime date1 = new(1389, 5, 27, 16, 32, 18, 500, persian); + Console.WriteLine(date1.ToString("M/dd/yyyy h:mm:ss.fff tt")); + Console.WriteLine("{0}/{1}/{2} {3}{7}{4:D2}{7}{5:D2}.{6:G3}\n", + persian.GetMonth(date1), + persian.GetDayOfMonth(date1), + persian.GetYear(date1), + persian.GetHour(date1), + persian.GetMinute(date1), + persian.GetSecond(date1), + persian.GetMilliseconds(date1), + DateTimeFormatInfo.CurrentInfo.TimeSeparator); - Console.WriteLine("Using the Hijri Calendar:"); - // Get current culture so it can later be restored. - CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; + Console.WriteLine("Using the Hijri Calendar:"); + // Get current culture so it can later be restored. + CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; - // Define strings for use in composite formatting. - string dFormat; - string fmtString; - // Define Hijri calendar. - HijriCalendar hijri = new HijriCalendar(); - // Make ar-SY the current culture and Hijri the current calendar. - Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SY"); - CultureInfo current = CultureInfo.CurrentCulture; - current.DateTimeFormat.Calendar = hijri; - dFormat = current.DateTimeFormat.ShortDatePattern; - // Ensure year is displayed as four digits. - dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy") + " H:mm:ss.fff"; - fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "}"; - DateTime date2 = new DateTime(1431, 9, 9, 16, 32, 18, 500, hijri); - Console.WriteLine(fmtString, current, GetCalendarName(hijri), date2); + // Define strings for use in composite formatting. + string dFormat; + string fmtString; + // Define Hijri calendar. + HijriCalendar hijri = new(); + // Make ar-SY the current culture and Hijri the current calendar. + Thread.CurrentThread.CurrentCulture = new("ar-SY"); + CultureInfo current = CultureInfo.CurrentCulture; + current.DateTimeFormat.Calendar = hijri; + dFormat = current.DateTimeFormat.ShortDatePattern; + // Ensure year is displayed as four digits. + dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy") + " H:mm:ss.fff"; + fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "}"; + DateTime date2 = new(1431, 9, 9, 16, 32, 18, 500, hijri); + Console.WriteLine(fmtString, current, GetCalendarName(hijri), date2); - // Restore previous culture. - Thread.CurrentThread.CurrentCulture = dftCulture; - dFormat = DateTimeFormatInfo.CurrentInfo.ShortDatePattern +" H:mm:ss.fff"; - fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "}"; - Console.WriteLine(fmtString, - CultureInfo.CurrentCulture, - GetCalendarName(CultureInfo.CurrentCulture.Calendar), - date2); - } + // Restore previous culture. + Thread.CurrentThread.CurrentCulture = dftCulture; + dFormat = DateTimeFormatInfo.CurrentInfo.ShortDatePattern + " H:mm:ss.fff"; + fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "}"; + Console.WriteLine(fmtString, + CultureInfo.CurrentCulture, + GetCalendarName(CultureInfo.CurrentCulture.Calendar), + date2); + } - private static string GetCalendarName(Calendar cal) - { - return Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; - } + private static string GetCalendarName(Calendar cal) => Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; } // The example displays the following output: // 8/18/2010 4:32:18.500 PM diff --git a/snippets/csharp/System/DateTime/.ctor/ctorexample9.cs b/snippets/csharp/System/DateTime/.ctor/ctorexample9.cs index 3a7a3048430..0c092add94b 100644 --- a/snippets/csharp/System/DateTime/.ctor/ctorexample9.cs +++ b/snippets/csharp/System/DateTime/.ctor/ctorexample9.cs @@ -6,60 +6,57 @@ public class Example { - public static void Main() - { - Console.WriteLine("Using the Persian Calendar:"); - PersianCalendar persian = new PersianCalendar(); - DateTime date1 = new DateTime(1389, 5, 27, 16, 32, 18, 500, - persian, DateTimeKind.Local); - Console.WriteLine("{0:M/dd/yyyy h:mm:ss.fff tt} {1}", date1, date1.Kind); - Console.WriteLine("{0}/{1}/{2} {3}{8}{4:D2}{8}{5:D2}.{6:G3} {7}\n", - persian.GetMonth(date1), - persian.GetDayOfMonth(date1), - persian.GetYear(date1), - persian.GetHour(date1), - persian.GetMinute(date1), - persian.GetSecond(date1), - persian.GetMilliseconds(date1), - date1.Kind, - DateTimeFormatInfo.CurrentInfo.TimeSeparator); + public static void Main() + { + Console.WriteLine("Using the Persian Calendar:"); + PersianCalendar persian = new(); + DateTime date1 = new(1389, 5, 27, 16, 32, 18, 500, + persian, DateTimeKind.Local); + Console.WriteLine($"{date1:M/dd/yyyy h:mm:ss.fff tt} {date1.Kind}"); + Console.WriteLine("{0}/{1}/{2} {3}{8}{4:D2}{8}{5:D2}.{6:G3} {7}\n", + persian.GetMonth(date1), + persian.GetDayOfMonth(date1), + persian.GetYear(date1), + persian.GetHour(date1), + persian.GetMinute(date1), + persian.GetSecond(date1), + persian.GetMilliseconds(date1), + date1.Kind, + DateTimeFormatInfo.CurrentInfo.TimeSeparator); - Console.WriteLine("Using the Hijri Calendar:"); - // Get current culture so it can later be restored. - CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; + Console.WriteLine("Using the Hijri Calendar:"); + // Get current culture so it can later be restored. + CultureInfo dftCulture = Thread.CurrentThread.CurrentCulture; - // Define strings for use in composite formatting. - string dFormat; - string fmtString; - // Define Hijri calendar. - HijriCalendar hijri = new HijriCalendar(); - // Make ar-SY the current culture and Hijri the current calendar. - Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SY"); - CultureInfo current = CultureInfo.CurrentCulture; - current.DateTimeFormat.Calendar = hijri; - dFormat = current.DateTimeFormat.ShortDatePattern; - // Ensure year is displayed as four digits. - dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy") + " H:mm:ss.fff"; - fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "} {3}"; - DateTime date2 = new DateTime(1431, 9, 9, 16, 32, 18, 500, - hijri, DateTimeKind.Local); - Console.WriteLine(fmtString, current, GetCalendarName(hijri), - date2, date2.Kind); + // Define strings for use in composite formatting. + string dFormat; + string fmtString; + // Define Hijri calendar. + HijriCalendar hijri = new(); + // Make ar-SY the current culture and Hijri the current calendar. + Thread.CurrentThread.CurrentCulture = new("ar-SY"); + CultureInfo current = CultureInfo.CurrentCulture; + current.DateTimeFormat.Calendar = hijri; + dFormat = current.DateTimeFormat.ShortDatePattern; + // Ensure year is displayed as four digits. + dFormat = Regex.Replace(dFormat, "/yy$", "/yyyy") + " H:mm:ss.fff"; + fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "} {3}"; + DateTime date2 = new(1431, 9, 9, 16, 32, 18, 500, + hijri, DateTimeKind.Local); + Console.WriteLine(fmtString, current, GetCalendarName(hijri), + date2, date2.Kind); - // Restore previous culture. - Thread.CurrentThread.CurrentCulture = dftCulture; - dFormat = DateTimeFormatInfo.CurrentInfo.ShortDatePattern +" H:mm:ss.fff"; - fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "} {3}"; - Console.WriteLine(fmtString, - CultureInfo.CurrentCulture, - GetCalendarName(CultureInfo.CurrentCulture.Calendar), - date2, date2.Kind); - } + // Restore previous culture. + Thread.CurrentThread.CurrentCulture = dftCulture; + dFormat = DateTimeFormatInfo.CurrentInfo.ShortDatePattern + " H:mm:ss.fff"; + fmtString = "{0} culture using the {1} calendar: {2:" + dFormat + "} {3}"; + Console.WriteLine(fmtString, + CultureInfo.CurrentCulture, + GetCalendarName(CultureInfo.CurrentCulture.Calendar), + date2, date2.Kind); + } - private static string GetCalendarName(Calendar cal) - { - return Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; - } + private static string GetCalendarName(Calendar cal) => Regex.Match(cal.ToString(), "\\.(\\w+)Calendar").Groups[1].Value; } // The example displays the following output: // Using the Persian Calendar: diff --git a/snippets/csharp/System/DateTime/.ctor/ticks.cs b/snippets/csharp/System/DateTime/.ctor/ticks.cs index c4c2f4e8ab3..00b430f124d 100644 --- a/snippets/csharp/System/DateTime/.ctor/ticks.cs +++ b/snippets/csharp/System/DateTime/.ctor/ticks.cs @@ -7,26 +7,26 @@ class Sample { public static void Main() { -// Instead of using the implicit, default "G" date and time format string, we -// use a custom format string that aligns the results and inserts leading zeroes. - string format = "{0}) The {1} date and time is {2:MM/dd/yyyy hh:mm:ss tt}"; - -// Create a DateTime for the maximum date and time using ticks. - DateTime dt1 = new DateTime(DateTime.MaxValue.Ticks); - -// Create a DateTime for the minimum date and time using ticks. - DateTime dt2 = new DateTime(DateTime.MinValue.Ticks); - -// Create a custom DateTime for 7/28/1979 at 10:35:05 PM using a -// calendar based on the "en-US" culture, and ticks. - long ticks = new DateTime(1979, 07, 28, 22, 35, 5, - new CultureInfo("en-US", false).Calendar).Ticks; - DateTime dt3 = new DateTime(ticks); - - Console.WriteLine(format, 1, "maximum", dt1); - Console.WriteLine(format, 2, "minimum", dt2); - Console.WriteLine(format, 3, "custom ", dt3); - Console.WriteLine("\nThe custom date and time is created from {0:N0} ticks.", ticks); + // Instead of using the implicit, default "G" date and time format string, we + // use a custom format string that aligns the results and inserts leading zeroes. + string format = "{0}) The {1} date and time is {2:MM/dd/yyyy hh:mm:ss tt}"; + + // Create a DateTime for the maximum date and time using ticks. + DateTime dt1 = new(DateTime.MaxValue.Ticks); + + // Create a DateTime for the minimum date and time using ticks. + DateTime dt2 = new(DateTime.MinValue.Ticks); + + // Create a custom DateTime for 7/28/1979 at 10:35:05 PM using a + // calendar based on the "en-US" culture, and ticks. + long ticks = new DateTime(1979, 07, 28, 22, 35, 5, + new CultureInfo("en-US", false).Calendar).Ticks; + DateTime dt3 = new(ticks); + + Console.WriteLine(format, 1, "maximum", dt1); + Console.WriteLine(format, 2, "minimum", dt2); + Console.WriteLine(format, 3, "custom ", dt3); + Console.WriteLine($"\nThe custom date and time is created from {ticks:N0} ticks."); } } /* @@ -39,4 +39,4 @@ public static void Main() The custom date and time is created from 624,376,461,050,000,000 ticks. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/Add/class1.cs b/snippets/csharp/System/DateTime/Add/class1.cs index f1b28df6094..b35d956a0ae 100644 --- a/snippets/csharp/System/DateTime/Add/class1.cs +++ b/snippets/csharp/System/DateTime/Add/class1.cs @@ -1,18 +1,18 @@ -using System; + namespace Add { - class Class1 - { - static void Main(string[] args) - { - // - // Calculate what day of the week is 36 days from this instant. - System.DateTime today = System.DateTime.Now; - System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0); - System.DateTime answer = today.Add(duration); - System.Console.WriteLine("{0:dddd}", answer); - // - } - } + class Class1 + { + static void Main(string[] args) + { + // + // Calculate what day of the week is 36 days from this instant. + System.DateTime today = System.DateTime.Now; + System.TimeSpan duration = new(36, 0, 0, 0); + System.DateTime answer = today.Add(duration); + System.Console.WriteLine($"{answer:dddd}"); + // + } + } } diff --git a/snippets/csharp/System/DateTime/AddDays/class1.cs b/snippets/csharp/System/DateTime/AddDays/class1.cs index 19074a1ef18..2ad1281ab0c 100644 --- a/snippets/csharp/System/DateTime/AddDays/class1.cs +++ b/snippets/csharp/System/DateTime/AddDays/class1.cs @@ -3,13 +3,13 @@ class Class1 { - static void Main() - { - DateTime today = DateTime.Now; - DateTime answer = today.AddDays(36); - Console.WriteLine("Today: {0:dddd}", today); - Console.WriteLine("36 days from today: {0:dddd}", answer); - } + static void Main() + { + DateTime today = DateTime.Now; + DateTime answer = today.AddDays(36); + Console.WriteLine($"Today: {today:dddd}"); + Console.WriteLine($"36 days from today: {answer:dddd}"); + } } // The example displays output like the following: // Today: Wednesday diff --git a/snippets/csharp/System/DateTime/AddHours/AddHours1.cs b/snippets/csharp/System/DateTime/AddHours/AddHours1.cs index 1afc81ca00e..27d5fbbf3ee 100644 --- a/snippets/csharp/System/DateTime/AddHours/AddHours1.cs +++ b/snippets/csharp/System/DateTime/AddHours/AddHours1.cs @@ -3,16 +3,15 @@ public class Example { - public static void Main() - { - double[] hours = {.08333, .16667, .25, .33333, .5, .66667, 1, 2, + public static void Main() + { + double[] hours = {.08333, .16667, .25, .33333, .5, .66667, 1, 2, 29, 30, 31, 90, 365}; - DateTime dateValue = new DateTime(2009, 3, 1, 12, 0, 0); + DateTime dateValue = new(2009, 3, 1, 12, 0, 0); - foreach (double hour in hours) - Console.WriteLine("{0} + {1} hour(s) = {2}", dateValue, hour, - dateValue.AddHours(hour)); - } + foreach (double hour in hours) + Console.WriteLine($"{dateValue} + {hour} hour(s) = {dateValue.AddHours(hour)}"); + } } // The example displays the following output on a system whose current // culture is en-US: diff --git a/snippets/csharp/System/DateTime/AddMilliseconds/addmilliseconds2.cs b/snippets/csharp/System/DateTime/AddMilliseconds/addmilliseconds2.cs index 7eb6b3ca7f2..27798af411c 100644 --- a/snippets/csharp/System/DateTime/AddMilliseconds/addmilliseconds2.cs +++ b/snippets/csharp/System/DateTime/AddMilliseconds/addmilliseconds2.cs @@ -2,33 +2,28 @@ public class Example { - public static void Main() - { - // - string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff"; - DateTime date1 = new DateTime(2010, 9, 8, 16, 0, 0); - Console.WriteLine("Original date: {0} ({1:N0} ticks)\n", - date1.ToString(dateFormat), date1.Ticks); + public static void Main() + { + // + string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff"; + DateTime date1 = new(2010, 9, 8, 16, 0, 0); + Console.WriteLine($"Original date: {date1.ToString(dateFormat)} ({date1.Ticks:N0} ticks)\n"); - DateTime date2 = date1.AddMilliseconds(1); - Console.WriteLine("Second date: {0} ({1:N0} ticks)", - date2.ToString(dateFormat), date2.Ticks); - Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n", - date2 - date1, date2.Ticks - date1.Ticks); + DateTime date2 = date1.AddMilliseconds(1); + Console.WriteLine($"Second date: {date2.ToString(dateFormat)} ({date2.Ticks:N0} ticks)"); + Console.WriteLine($"Difference between dates: {date2 - date1} ({date2.Ticks - date1.Ticks:N0} ticks)\n"); - DateTime date3 = date1.AddMilliseconds(1.5); - Console.WriteLine("Third date: {0} ({1:N0} ticks)", - date3.ToString(dateFormat), date3.Ticks); - Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)", - date3 - date1, date3.Ticks - date1.Ticks); - // The example displays the following output: - // Original date: 09/08/2010 04:00:00.0000000 (634,195,584,000,000,000 ticks) - // - // Second date: 09/08/2010 04:00:00.0010000 (634,195,584,000,010,000 ticks) - // Difference between dates: 00:00:00.0010000 (10,000 ticks) - // - // Third date: 09/08/2010 04:00:00.0020000 (634,195,584,000,020,000 ticks) - // Difference between dates: 00:00:00.0020000 (20,000 ticks) - // - } + DateTime date3 = date1.AddMilliseconds(1.5); + Console.WriteLine($"Third date: {date3.ToString(dateFormat)} ({date3.Ticks:N0} ticks)"); + Console.WriteLine($"Difference between dates: {date3 - date1} ({date3.Ticks - date1.Ticks:N0} ticks)"); + // The example displays the following output: + // Original date: 09/08/2010 04:00:00.0000000 (634,195,584,000,000,000 ticks) + // + // Second date: 09/08/2010 04:00:00.0010000 (634,195,584,000,010,000 ticks) + // Difference between dates: 00:00:00.0010000 (10,000 ticks) + // + // Third date: 09/08/2010 04:00:00.0020000 (634,195,584,000,020,000 ticks) + // Difference between dates: 00:00:00.0020000 (20,000 ticks) + // + } } diff --git a/snippets/csharp/System/DateTime/AddMinutes/addminutes1.cs b/snippets/csharp/System/DateTime/AddMinutes/addminutes1.cs index cd97b0055ce..f2b47304f54 100644 --- a/snippets/csharp/System/DateTime/AddMinutes/addminutes1.cs +++ b/snippets/csharp/System/DateTime/AddMinutes/addminutes1.cs @@ -3,18 +3,17 @@ public class Example { - public static void Main() - { - DateTime dateValue = new DateTime(2013, 9, 15, 12, 0, 0); + public static void Main() + { + DateTime dateValue = new(2013, 9, 15, 12, 0, 0); - double[] minutes = { .01667, .08333, .16667, .25, .33333, + double[] minutes = { .01667, .08333, .16667, .25, .33333, .5, .66667, 1, 2, 15, 30, 17, 45, 60, 180, 60 * 24 }; - foreach (double minute in minutes) - Console.WriteLine("{0} + {1} minute(s) = {2}", dateValue, minute, - dateValue.AddMinutes(minute)); - } + foreach (double minute in minutes) + Console.WriteLine($"{dateValue} + {minute} minute(s) = {dateValue.AddMinutes(minute)}"); + } } // The example displays the following output on a system whose current culture is en-US: // 9/15/2013 12:00:00 PM + 0.01667 minute(s) = 9/15/2013 12:00:01 PM diff --git a/snippets/csharp/System/DateTime/AddMonths/addmonths1.cs b/snippets/csharp/System/DateTime/AddMonths/addmonths1.cs index 64ff759e807..f8abcef4d40 100644 --- a/snippets/csharp/System/DateTime/AddMonths/addmonths1.cs +++ b/snippets/csharp/System/DateTime/AddMonths/addmonths1.cs @@ -3,12 +3,12 @@ public class Example { - public static void Main() - { - var dat = new DateTime(2015, 12, 31); - for (int ctr = 0; ctr <= 15; ctr++) - Console.WriteLine(dat.AddMonths(ctr).ToString("d")); - } + public static void Main() + { + var dat = new DateTime(2015, 12, 31); + for (int ctr = 0; ctr <= 15; ctr++) + Console.WriteLine(dat.AddMonths(ctr).ToString("d")); + } } // The example displays the following output: // 12/31/2015 diff --git a/snippets/csharp/System/DateTime/AddSeconds/addseconds1.cs b/snippets/csharp/System/DateTime/AddSeconds/addseconds1.cs index 0107acc8afd..ceac4b45cf3 100644 --- a/snippets/csharp/System/DateTime/AddSeconds/addseconds1.cs +++ b/snippets/csharp/System/DateTime/AddSeconds/addseconds1.cs @@ -3,26 +3,21 @@ public class Example { - public static void Main() - { - string dateFormat = "MM/dd/yyyy hh:mm:ss"; - DateTime date1 = new DateTime(2014, 9, 8, 16, 0, 0); - Console.WriteLine("Original date: {0} ({1:N0} ticks)\n", - date1.ToString(dateFormat), date1.Ticks); + public static void Main() + { + string dateFormat = "MM/dd/yyyy hh:mm:ss"; + DateTime date1 = new(2014, 9, 8, 16, 0, 0); + Console.WriteLine($"Original date: {date1.ToString(dateFormat)} ({date1.Ticks:N0} ticks)\n"); - DateTime date2 = date1.AddSeconds(30); - Console.WriteLine("Second date: {0} ({1:N0} ticks)", - date2.ToString(dateFormat), date2.Ticks); - Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n", - date2 - date1, date2.Ticks - date1.Ticks); + DateTime date2 = date1.AddSeconds(30); + Console.WriteLine($"Second date: {date2.ToString(dateFormat)} ({date2.Ticks:N0} ticks)"); + Console.WriteLine($"Difference between dates: {date2 - date1} ({date2.Ticks - date1.Ticks:N0} ticks)\n"); - // Add 1 day's worth of seconds (60 secs. * 60 mins * 24 hrs. - DateTime date3 = date1.AddSeconds(60 * 60 * 24); - Console.WriteLine("Third date: {0} ({1:N0} ticks)", - date3.ToString(dateFormat), date3.Ticks); - Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)", - date3 - date1, date3.Ticks - date1.Ticks); - } + // Add 1 day's worth of seconds (60 secs. * 60 mins * 24 hrs. + DateTime date3 = date1.AddSeconds(60 * 60 * 24); + Console.WriteLine($"Third date: {date3.ToString(dateFormat)} ({date3.Ticks:N0} ticks)"); + Console.WriteLine($"Difference between dates: {date3 - date1} ({date3.Ticks - date1.Ticks:N0} ticks)"); + } } // The example displays the following output: // Original date: 09/08/2014 04:00:00 (635,457,888,000,000,000 ticks) diff --git a/snippets/csharp/System/DateTime/AddYears/addyears1.cs b/snippets/csharp/System/DateTime/AddYears/addyears1.cs index 4bffd1dd72c..a682208a1d0 100644 --- a/snippets/csharp/System/DateTime/AddYears/addyears1.cs +++ b/snippets/csharp/System/DateTime/AddYears/addyears1.cs @@ -3,22 +3,20 @@ public class Example { - public static void Main() - { - DateTime baseDate = new DateTime(2000, 2, 29); - Console.WriteLine(" Base Date: {0:d}\n", baseDate); + public static void Main() + { + DateTime baseDate = new(2000, 2, 29); + Console.WriteLine($" Base Date: {baseDate:d}\n"); - // Show dates of previous fifteen years. - for (int ctr = -1; ctr >= -15; ctr--) - Console.WriteLine("{0,2} year(s) ago: {1:d}", - Math.Abs(ctr), baseDate.AddYears(ctr)); - Console.WriteLine(); + // Show dates of previous fifteen years. + for (int ctr = -1; ctr >= -15; ctr--) + Console.WriteLine($"{Math.Abs(ctr),2} year(s) ago: {baseDate.AddYears(ctr):d}"); + Console.WriteLine(); - // Show dates of next fifteen years. - for (int ctr = 1; ctr <= 15; ctr++) - Console.WriteLine("{0,2} year(s) from now: {1:d}", - ctr, baseDate.AddYears(ctr)); - } + // Show dates of next fifteen years. + for (int ctr = 1; ctr <= 15; ctr++) + Console.WriteLine($"{ctr,2} year(s) from now: {baseDate.AddYears(ctr):d}"); + } } // The example displays the following output: // Base Date: 2/29/2000 @@ -54,4 +52,4 @@ public static void Main() // 13 year(s) from now: 2/28/2013 // 14 year(s) from now: 2/28/2014 // 15 year(s) from now: 2/28/2015 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/Compare/compare1.cs b/snippets/csharp/System/DateTime/Compare/compare1.cs index 3f507539c67..a08721410b5 100644 --- a/snippets/csharp/System/DateTime/Compare/compare1.cs +++ b/snippets/csharp/System/DateTime/Compare/compare1.cs @@ -2,25 +2,25 @@ public class Example { - public static void Main() - { - // - DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); - DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0); - int result = DateTime.Compare(date1, date2); - string relationship; + public static void Main() + { + // + DateTime date1 = new(2009, 8, 1, 0, 0, 0); + DateTime date2 = new(2009, 8, 1, 12, 0, 0); + int result = DateTime.Compare(date1, date2); + string relationship; - if (result < 0) - relationship = "is earlier than"; - else if (result == 0) - relationship = "is the same time as"; - else - relationship = "is later than"; + if (result < 0) + relationship = "is earlier than"; + else if (result == 0) + relationship = "is the same time as"; + else + relationship = "is later than"; - Console.WriteLine("{0} {1} {2}", date1, relationship, date2); + Console.WriteLine($"{date1} {relationship} {date2}"); - // The example displays the following output for en-us culture: - // 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM - // - } + // The example displays the following output for en-us culture: + // 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM + // + } } diff --git a/snippets/csharp/System/DateTime/CompareTo/CompareTo_CS1_24564.cs b/snippets/csharp/System/DateTime/CompareTo/CompareTo_CS1_24564.cs index 985f1e1ad60..87476671794 100644 --- a/snippets/csharp/System/DateTime/CompareTo/CompareTo_CS1_24564.cs +++ b/snippets/csharp/System/DateTime/CompareTo/CompareTo_CS1_24564.cs @@ -3,40 +3,36 @@ public class DateTimeComparison { - private enum DateComparisonResult - { - Earlier = -1, - Later = 1, - TheSame = 0 - }; + private enum DateComparisonResult + { + Earlier = -1, + Later = 1, + TheSame = 0 + }; - public static void Main() - { - DateTime thisDate = DateTime.Today; + public static void Main() + { + DateTime thisDate = DateTime.Today; - // Define two DateTime objects for today's date - // next year and last year - DateTime thisDateNextYear, thisDateLastYear; + // Define two DateTime objects for today's date + // next year and last year + DateTime thisDateNextYear, thisDateLastYear; - // Call AddYears instance method to add/substract 1 year - thisDateNextYear = thisDate.AddYears(1); - thisDateLastYear = thisDate.AddYears(-1); + // Call AddYears instance method to add/substract 1 year + thisDateNextYear = thisDate.AddYears(1); + thisDateLastYear = thisDate.AddYears(-1); - // Compare dates - // - DateComparisonResult comparison; - // Compare today to last year - comparison = (DateComparisonResult) thisDate.CompareTo(thisDateLastYear); - Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", - (int) comparison, thisDate, comparison.ToString().ToLower(), - thisDateLastYear); + // Compare dates + // + DateComparisonResult comparison; + // Compare today to last year + comparison = (DateComparisonResult)thisDate.CompareTo(thisDateLastYear); + Console.WriteLine($"CompareTo method returns {(int)comparison}: {thisDate:d} is {comparison.ToString().ToLower()} than {thisDateLastYear:d}"); - // Compare today to next year - comparison = (DateComparisonResult) thisDate.CompareTo(thisDateNextYear); - Console.WriteLine("CompareTo method returns {0}: {1:d} is {2} than {3:d}", - (int) comparison, thisDate, comparison.ToString().ToLower(), - thisDateNextYear); - } + // Compare today to next year + comparison = (DateComparisonResult)thisDate.CompareTo(thisDateNextYear); + Console.WriteLine($"CompareTo method returns {(int)comparison}: {thisDate:d} is {comparison.ToString().ToLower()} than {thisDateNextYear:d}"); + } } // // If run on October 20, 2006, the example produces the following output: diff --git a/snippets/csharp/System/DateTime/CompareTo/class1.cs b/snippets/csharp/System/DateTime/CompareTo/class1.cs index c040bcf1340..50305309a3c 100644 --- a/snippets/csharp/System/DateTime/CompareTo/class1.cs +++ b/snippets/csharp/System/DateTime/CompareTo/class1.cs @@ -5,9 +5,9 @@ namespace CompareTo class Class1 { static void Main(string[] args) - { + { // - System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28); + System.DateTime theDay = new(System.DateTime.Today.Year, 7, 28); int compareValue; try @@ -16,16 +16,16 @@ static void Main(string[] args) } catch (ArgumentException) { - Console.WriteLine("Value is not a DateTime"); - return; + Console.WriteLine("Value is not a DateTime"); + return; } if (compareValue < 0) - System.Console.WriteLine("{0:d} is in the past.", theDay); + System.Console.WriteLine($"{theDay:d} is in the past."); else if (compareValue == 0) - System.Console.WriteLine("{0:d} is today!", theDay); + System.Console.WriteLine($"{theDay:d} is today!"); else // compareValue > 0 - System.Console.WriteLine("{0:d} has not come yet.", theDay); + System.Console.WriteLine($"{theDay:d} has not come yet."); // } } diff --git a/snippets/csharp/System/DateTime/Date/Date1.cs b/snippets/csharp/System/DateTime/Date/Date1.cs index 21fe62d9d2d..c11eadc3bee 100644 --- a/snippets/csharp/System/DateTime/Date/Date1.cs +++ b/snippets/csharp/System/DateTime/Date/Date1.cs @@ -3,19 +3,19 @@ public class Example { - public static void Main() - { - DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0); - Console.WriteLine(date1.ToString()); + public static void Main() + { + DateTime date1 = new(2008, 6, 1, 7, 47, 0); + Console.WriteLine(date1.ToString()); - // Get date-only portion of date, without its time. - DateTime dateOnly = date1.Date; - // Display date using short date string. - Console.WriteLine(dateOnly.ToString("d")); - // Display date using 24-hour clock. - Console.WriteLine(dateOnly.ToString("g")); - Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm")); - } + // Get date-only portion of date, without its time. + DateTime dateOnly = date1.Date; + // Display date using short date string. + Console.WriteLine(dateOnly.ToString("d")); + // Display date using 24-hour clock. + Console.WriteLine(dateOnly.ToString("g")); + Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm")); + } } // The example displays output like the following output: // 6/1/2008 7:47:00 AM diff --git a/snippets/csharp/System/DateTime/Day/Day1.cs b/snippets/csharp/System/DateTime/Day/Day1.cs index ec61303eb2c..fcb4145c2de 100644 --- a/snippets/csharp/System/DateTime/Day/Day1.cs +++ b/snippets/csharp/System/DateTime/Day/Day1.cs @@ -3,24 +3,24 @@ public class Class1 { - public static void Main() - { - // - // Return day of 1/13/2009. - DateTime dateGregorian = new DateTime(2009, 1, 13); - Console.WriteLine(dateGregorian.Day); - // Displays 13 (Gregorian day). + public static void Main() + { + // + // Return day of 1/13/2009. + DateTime dateGregorian = new(2009, 1, 13); + Console.WriteLine(dateGregorian.Day); + // Displays 13 (Gregorian day). - // Create date of 1/13/2009 using Hijri calendar. - HijriCalendar hijri = new HijriCalendar(); - DateTime dateHijri = new DateTime(1430, 1, 17, hijri); - // Return day of date created using Hijri calendar. - Console.WriteLine(dateHijri.Day); - // Displays 13 (Gregorian day). + // Create date of 1/13/2009 using Hijri calendar. + HijriCalendar hijri = new(); + DateTime dateHijri = new(1430, 1, 17, hijri); + // Return day of date created using Hijri calendar. + Console.WriteLine(dateHijri.Day); + // Displays 13 (Gregorian day). - // Display day of date in Hijri calendar. - Console.WriteLine(hijri.GetDayOfMonth(dateHijri)); - // Displays 17 (Hijri day). - // - } + // Display day of date in Hijri calendar. + Console.WriteLine(hijri.GetDayOfMonth(dateHijri)); + // Displays 17 (Hijri day). + // + } } diff --git a/snippets/csharp/System/DateTime/Day/Day2.cs b/snippets/csharp/System/DateTime/Day/Day2.cs index f1d6be03c4d..a3aa0da88f2 100644 --- a/snippets/csharp/System/DateTime/Day/Day2.cs +++ b/snippets/csharp/System/DateTime/Day/Day2.cs @@ -4,30 +4,30 @@ public class Class1 { - public static void Main() - { - // - CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; + public static void Main() + { + // + CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; - // Change current culture to ar-SA. - CultureInfo ci = new CultureInfo("ar-SA"); - Thread.CurrentThread.CurrentCulture = ci; + // Change current culture to ar-SA. + CultureInfo ci = new("ar-SA"); + Thread.CurrentThread.CurrentCulture = ci; - DateTime hijriDate = new DateTime(1430, 1, 17, - Thread.CurrentThread.CurrentCulture.Calendar); - // Display date (uses calendar of current culture by default). - Console.WriteLine(hijriDate.ToString("dd-MM-yyyy")); - // Displays 17-01-1430. + DateTime hijriDate = new(1430, 1, 17, + Thread.CurrentThread.CurrentCulture.Calendar); + // Display date (uses calendar of current culture by default). + Console.WriteLine(hijriDate.ToString("dd-MM-yyyy")); + // Displays 17-01-1430. - // Display day of 17th of Muharram - Console.WriteLine(hijriDate.Day); - // Displays 13 (corresponding day of January in Gregorian calendar). + // Display day of 17th of Muharram + Console.WriteLine(hijriDate.Day); + // Displays 13 (corresponding day of January in Gregorian calendar). - // Display day of 17th of Muharram in Hijri calendar. - Console.WriteLine(Thread.CurrentThread.CurrentCulture.Calendar.GetDayOfMonth(hijriDate)); - // Displays 17. + // Display day of 17th of Muharram in Hijri calendar. + Console.WriteLine(Thread.CurrentThread.CurrentCulture.Calendar.GetDayOfMonth(hijriDate)); + // Displays 17. - Thread.CurrentThread.CurrentCulture = originalCulture; - // - } + Thread.CurrentThread.CurrentCulture = originalCulture; + // + } } diff --git a/snippets/csharp/System/DateTime/Day/class1.cs b/snippets/csharp/System/DateTime/Day/class1.cs index 2248c2bdd7a..cbe792bc8a8 100644 --- a/snippets/csharp/System/DateTime/Day/class1.cs +++ b/snippets/csharp/System/DateTime/Day/class1.cs @@ -1,35 +1,35 @@ -using System; + namespace Minute_Etc { - class Class1 - { - static void Main(string[] args) - { - // - System.DateTime moment = new System.DateTime( - 1999, 1, 13, 3, 57, 32, 11); - // Year gets 1999. - int year = moment.Year; - - // Month gets 1 (January). - int month = moment.Month; - - // Day gets 13. - int day = moment.Day; - - // Hour gets 3. - int hour = moment.Hour; - - // Minute gets 57. - int minute = moment.Minute; - - // Second gets 32. - int second = moment.Second; - - // Millisecond gets 11. - int millisecond = moment.Millisecond; - // - } - } + class Class1 + { + static void Main(string[] args) + { + // + System.DateTime moment = new( + 1999, 1, 13, 3, 57, 32, 11); + // Year gets 1999. + int year = moment.Year; + + // Month gets 1 (January). + int month = moment.Month; + + // Day gets 13. + int day = moment.Day; + + // Hour gets 3. + int hour = moment.Hour; + + // Minute gets 57. + int minute = moment.Minute; + + // Second gets 32. + int second = moment.Second; + + // Millisecond gets 11. + int millisecond = moment.Millisecond; + // + } + } } diff --git a/snippets/csharp/System/DateTime/DayOfWeek/dow.cs b/snippets/csharp/System/DateTime/DayOfWeek/dow.cs index fbbe80f7542..c3fcc48f7ef 100644 --- a/snippets/csharp/System/DateTime/DayOfWeek/dow.cs +++ b/snippets/csharp/System/DateTime/DayOfWeek/dow.cs @@ -6,12 +6,11 @@ class Sample { public static void Main() { -// Assume the current culture is en-US. -// Create a DateTime for the first of May, 2003. - DateTime dt = new DateTime(2003, 5, 1); - Console.WriteLine("Is Thursday the day of the week for {0:d}?: {1}", - dt, dt.DayOfWeek == DayOfWeek.Thursday); - Console.WriteLine("The day of the week for {0:d} is {1}.", dt, dt.DayOfWeek); + // Assume the current culture is en-US. + // Create a DateTime for the first of May, 2003. + DateTime dt = new(2003, 5, 1); + Console.WriteLine($"Is Thursday the day of the week for {dt:d}?: {dt.DayOfWeek == DayOfWeek.Thursday}"); + Console.WriteLine($"The day of the week for {dt:d} is {dt.DayOfWeek}."); } } /* @@ -20,4 +19,4 @@ public static void Main() Is Thursday the day of the week for 5/1/2003?: True The day of the week for 5/1/2003 is Thursday. */ -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/DayOfYear/dayofyear2.cs b/snippets/csharp/System/DateTime/DayOfYear/dayofyear2.cs index 6635c777371..1ac14381e4c 100644 --- a/snippets/csharp/System/DateTime/DayOfYear/dayofyear2.cs +++ b/snippets/csharp/System/DateTime/DayOfYear/dayofyear2.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - DateTime dec31 = new DateTime(2010, 12, 31); - for (int ctr = 0; ctr <= 10; ctr++) { - DateTime dateToDisplay = dec31.AddYears(ctr); - Console.WriteLine("{0:d}: day {1} of {2} {3}", dateToDisplay, - dateToDisplay.DayOfYear, - dateToDisplay.Year, - DateTime.IsLeapYear(dateToDisplay.Year) ? - "(Leap Year)" : ""); - } - } + public static void Main() + { + DateTime dec31 = new(2010, 12, 31); + for (int ctr = 0; ctr <= 10; ctr++) + { + DateTime dateToDisplay = dec31.AddYears(ctr); + Console.WriteLine($"{dateToDisplay:d}: day {dateToDisplay.DayOfYear} of {dateToDisplay.Year} {(DateTime.IsLeapYear(dateToDisplay.Year) ? + "(Leap Year)" : "")}"); + } + } } // The example displays the following output: // 12/31/2010: day 365 of 2010 diff --git a/snippets/csharp/System/DateTime/DaysInMonth/class1.cs b/snippets/csharp/System/DateTime/DaysInMonth/class1.cs index 2068867c7d5..edb78280749 100644 --- a/snippets/csharp/System/DateTime/DaysInMonth/class1.cs +++ b/snippets/csharp/System/DateTime/DaysInMonth/class1.cs @@ -3,22 +3,22 @@ class Example { - static void Main() - { - const int July = 7; - const int Feb = 2; + static void Main() + { + const int July = 7; + const int Feb = 2; - int daysInJuly = System.DateTime.DaysInMonth(2001, July); + int daysInJuly = System.DateTime.DaysInMonth(2001, July); Console.WriteLine(daysInJuly); - // daysInFeb gets 28 because the year 1998 was not a leap year. - int daysInFeb = System.DateTime.DaysInMonth(1998, Feb); + // daysInFeb gets 28 because the year 1998 was not a leap year. + int daysInFeb = System.DateTime.DaysInMonth(1998, Feb); Console.WriteLine(daysInFeb); - // daysInFebLeap gets 29 because the year 1996 was a leap year. - int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb); - Console.WriteLine(daysInFebLeap); - } + // daysInFebLeap gets 29 because the year 1996 was a leap year. + int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb); + Console.WriteLine(daysInFebLeap); + } } // The example displays the following output: // 31 diff --git a/snippets/csharp/System/DateTime/DaysInMonth/daysinmonth3.cs b/snippets/csharp/System/DateTime/DaysInMonth/daysinmonth3.cs index 891e0a918aa..7d887aa9f34 100644 --- a/snippets/csharp/System/DateTime/DaysInMonth/daysinmonth3.cs +++ b/snippets/csharp/System/DateTime/DaysInMonth/daysinmonth3.cs @@ -4,28 +4,28 @@ public class Example { - public static void Main() - { - int[] years = { 2012, 2014 }; - DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo; - Console.WriteLine("Days in the Month for the {0} culture " + - "using the {1} calendar\n", - CultureInfo.CurrentCulture.Name, - dtfi.Calendar.GetType().Name.Replace("Calendar", "")); - Console.WriteLine("{0,-10}{1,-15}{2,4}\n", "Year", "Month", "Days"); + public static void Main() + { + int[] years = { 2012, 2014 }; + DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo; + Console.WriteLine("Days in the Month for the {0} culture " + + "using the {1} calendar\n", + CultureInfo.CurrentCulture.Name, + dtfi.Calendar.GetType().Name.Replace("Calendar", "")); + Console.WriteLine($"{"Year",-10}{"Month",-15}{"Days",4}\n"); - foreach (var year in years) { - for (int ctr = 0; ctr <= dtfi.MonthNames.Length - 1; ctr++) { - if (String.IsNullOrEmpty(dtfi.MonthNames[ctr])) - continue; + foreach (int year in years) + { + for (int ctr = 0; ctr <= dtfi.MonthNames.Length - 1; ctr++) + { + if (string.IsNullOrEmpty(dtfi.MonthNames[ctr])) + continue; - Console.WriteLine("{0,-10}{1,-15}{2,4}", year, - dtfi.MonthNames[ctr], - DateTime.DaysInMonth(year, ctr + 1)); - } - Console.WriteLine(); - } - } + Console.WriteLine($"{year,-10}{dtfi.MonthNames[ctr],-15}{DateTime.DaysInMonth(year, ctr + 1),4}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // Days in the Month for the en-US culture using the Gregorian calendar diff --git a/snippets/csharp/System/DateTime/Equals/class1.cs b/snippets/csharp/System/DateTime/Equals/class1.cs index 4c1e08e638e..103fa73b22d 100644 --- a/snippets/csharp/System/DateTime/Equals/class1.cs +++ b/snippets/csharp/System/DateTime/Equals/class1.cs @@ -1,29 +1,29 @@ -using System; + namespace Equals { - class Class1 - { - static void Main(string[] args) - { - // - System.DateTime today1 = - new System.DateTime(System.DateTime.Today.Ticks); - System.DateTime today2 = - new System.DateTime(System.DateTime.Today.Ticks); - System.DateTime tomorrow = - new System.DateTime( - System.DateTime.Today.AddDays(1).Ticks); + class Class1 + { + static void Main(string[] args) + { + // + System.DateTime today1 = + new(System.DateTime.Today.Ticks); + System.DateTime today2 = + new(System.DateTime.Today.Ticks); + System.DateTime tomorrow = + new( + System.DateTime.Today.AddDays(1).Ticks); - // todayEqualsToday gets true. - bool todayEqualsToday = System.DateTime.Equals(today1, today2); + // todayEqualsToday gets true. + bool todayEqualsToday = System.DateTime.Equals(today1, today2); - // todayEqualsTomorrow gets false. - bool todayEqualsTomorrow = System.DateTime.Equals(today1, tomorrow); - // + // todayEqualsTomorrow gets false. + bool todayEqualsTomorrow = System.DateTime.Equals(today1, tomorrow); + // - System.Console.WriteLine(todayEqualsToday); - System.Console.WriteLine(todayEqualsTomorrow); - } - } + System.Console.WriteLine(todayEqualsToday); + System.Console.WriteLine(todayEqualsTomorrow); + } + } } diff --git a/snippets/csharp/System/DateTime/Equals/sample.cs b/snippets/csharp/System/DateTime/Equals/sample.cs index b411197f64c..a698e6bd1b5 100644 --- a/snippets/csharp/System/DateTime/Equals/sample.cs +++ b/snippets/csharp/System/DateTime/Equals/sample.cs @@ -15,11 +15,11 @@ public static void Main() // Compare the DateTime objects and display the results. bool result = one.Equals(two); - Console.WriteLine("The result of comparing DateTime object one and two is: {0}.", result); + Console.WriteLine($"The result of comparing DateTime object one and two is: {result}."); result = one.Equals(three); - Console.WriteLine("The result of comparing DateTime object one and three is: {0}.", result); + Console.WriteLine($"The result of comparing DateTime object one and three is: {result}."); } } @@ -27,4 +27,4 @@ public static void Main() // // The result of comparing DateTime object one and two is: False. // The result of comparing DateTime object one and three is: True. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/FromBinary/frombinary1.cs b/snippets/csharp/System/DateTime/FromBinary/frombinary1.cs index 9de79296a2e..bd4043621d8 100644 --- a/snippets/csharp/System/DateTime/FromBinary/frombinary1.cs +++ b/snippets/csharp/System/DateTime/FromBinary/frombinary1.cs @@ -1,18 +1,18 @@ -// +// using System; public class Example { - public static void Main() - { - DateTime localDate = new (2010, 3, 14, 2, 30, 0, DateTimeKind.Local); - long binLocal = localDate.ToBinary(); - if (TimeZoneInfo.Local.IsInvalidTime(localDate)) - Console.WriteLine($"{localDate} is an invalid time in the {TimeZoneInfo.Local.StandardName} zone."); + public static void Main() + { + DateTime localDate = new(2010, 3, 14, 2, 30, 0, DateTimeKind.Local); + long binLocal = localDate.ToBinary(); + if (TimeZoneInfo.Local.IsInvalidTime(localDate)) + Console.WriteLine($"{localDate} is an invalid time in the {TimeZoneInfo.Local.StandardName} zone."); - DateTime localDate2 = DateTime.FromBinary(binLocal); - Console.WriteLine($"{localDate} = {localDate2}: {localDate.Equals(localDate2)}"); - } + DateTime localDate2 = DateTime.FromBinary(binLocal); + Console.WriteLine($"{localDate} = {localDate2}: {localDate.Equals(localDate2)}"); + } } // The example displays the following output: // 3/14/2010 2:30:00 AM is an invalid time in the Pacific Standard Time zone. diff --git a/snippets/csharp/System/DateTime/FromFileTime/class1.cs b/snippets/csharp/System/DateTime/FromFileTime/class1.cs index 596c2d89213..9ebde8379ea 100644 --- a/snippets/csharp/System/DateTime/FromFileTime/class1.cs +++ b/snippets/csharp/System/DateTime/FromFileTime/class1.cs @@ -1,45 +1,50 @@ using System; -using System.IO; + namespace FromFileTime { - class Class1 - { - static void Main(string[] args) - { - System.Console.WriteLine("Enter a file's path"); - string filePath = System.Console.ReadLine(); - System.IO.FileInfo fInfo; - try { - fInfo = new System.IO.FileInfo(filePath); - } - catch { - System.Console.WriteLine("Error opening {0}", filePath); - return; - } - long fileTime = System.Convert.ToInt64(fInfo.CreationTime.ToFileTime()); - Class1 theApp = new Class1(); - System.TimeSpan fileAge = theApp.FileAge(fileTime); - System.Console.WriteLine("{0}", fileAge); - } + class Class1 + { + static void Main(string[] args) + { + System.Console.WriteLine("Enter a file's path"); + string filePath = System.Console.ReadLine(); + System.IO.FileInfo fInfo; + try + { + fInfo = new(filePath); + } + catch + { + System.Console.WriteLine($"Error opening {filePath}"); + return; + } + long fileTime = System.Convert.ToInt64(fInfo.CreationTime.ToFileTime()); + Class1 theApp = new(); + System.TimeSpan fileAge = theApp.FileAge(fileTime); + System.Console.WriteLine($"{fileAge}"); + } - // This function takes a file's creation time as an unsigned long, - // and returns its age. - // - public System.TimeSpan FileAge(long fileCreationTime) { + // This function takes a file's creation time as an unsigned long, + // and returns its age. + // + public System.TimeSpan FileAge(long fileCreationTime) + { - System.DateTime now = System.DateTime.Now; - try { - System.DateTime fCreationTime = - System.DateTime.FromFileTime(fileCreationTime); - System.TimeSpan fileAge = now.Subtract(fCreationTime); - return fileAge; - } - catch (ArgumentOutOfRangeException) { - // fileCreationTime is not valid, so re-throw the exception. - throw; - } - } - // - } + System.DateTime now = System.DateTime.Now; + try + { + System.DateTime fCreationTime = + System.DateTime.FromFileTime(fileCreationTime); + System.TimeSpan fileAge = now.Subtract(fCreationTime); + return fileAge; + } + catch (ArgumentOutOfRangeException) + { + // fileCreationTime is not valid, so re-throw the exception. + throw; + } + } + // + } } diff --git a/snippets/csharp/System/DateTime/FromFileTime/fromfiletime1.cs b/snippets/csharp/System/DateTime/FromFileTime/fromfiletime1.cs index c0e8065f522..ffe927cea38 100644 --- a/snippets/csharp/System/DateTime/FromFileTime/fromfiletime1.cs +++ b/snippets/csharp/System/DateTime/FromFileTime/fromfiletime1.cs @@ -3,17 +3,16 @@ public class Example { - public static void Main() - { - DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 00); - Console.WriteLine("Invalid Time: {0}", - TimeZoneInfo.Local.IsInvalidTime(date1)); - long ft = date1.ToFileTime(); - DateTime date2 = DateTime.FromFileTime(ft); - Console.WriteLine("{0} -> {1}", date1, date2); - } + public static void Main() + { + DateTime date1 = new(2010, 3, 14, 2, 30, 00); + Console.WriteLine($"Invalid Time: {TimeZoneInfo.Local.IsInvalidTime(date1)}"); + long ft = date1.ToFileTime(); + DateTime date2 = DateTime.FromFileTime(ft); + Console.WriteLine($"{date1} -> {date2}"); + } } // The example displays the following output: // Invalid Time: True // 3/14/2010 2:30:00 AM -> 3/14/2010 3:30:00 AM -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/GetDateTimeFormats/class1.cs b/snippets/csharp/System/DateTime/GetDateTimeFormats/class1.cs index 31f097dd763..dda831f854f 100644 --- a/snippets/csharp/System/DateTime/GetDateTimeFormats/class1.cs +++ b/snippets/csharp/System/DateTime/GetDateTimeFormats/class1.cs @@ -2,90 +2,94 @@ class Class1 { - static void Main(string[] args) - { - ShowDefaultFormats(); - ShowDefaultFrenchFormats(); - Console.WriteLine("\nDefault 'D' Format:\n"); - ShowDefaultDFormat(); - Console.WriteLine("\nFrench 'D' Format:\n"); - ShowFrenchDFormat(); - } + static void Main(string[] args) + { + ShowDefaultFormats(); + ShowDefaultFrenchFormats(); + Console.WriteLine("\nDefault 'D' Format:\n"); + ShowDefaultDFormat(); + Console.WriteLine("\nFrench 'D' Format:\n"); + ShowFrenchDFormat(); + } - private static void ShowDefaultFormats() - { - // - DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15, 16); + private static void ShowDefaultFormats() + { + // + DateTime july28 = new(2009, 7, 28, 5, 23, 15, 16); - string[] july28Formats = july28.GetDateTimeFormats(); + string[] july28Formats = july28.GetDateTimeFormats(); - // Print out july28 in all DateTime formats using the default culture. - foreach (string format in july28Formats) { - Console.WriteLine(format); - } - // - } + // Print out july28 in all DateTime formats using the default culture. + foreach (string format in july28Formats) + { + Console.WriteLine(format); + } + // + } - private static void ShowDefaultFrenchFormats() - { - // - DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15, 16); - - IFormatProvider culture = - new System.Globalization.CultureInfo("fr-FR", true); - // Get the short date formats using the "fr-FR" culture. - string [] frenchJuly28Formats = - july28.GetDateTimeFormats(culture); + private static void ShowDefaultFrenchFormats() + { + // + DateTime july28 = new(2009, 7, 28, 5, 23, 15, 16); - // Display july28 in various formats using "fr-FR" culture. - foreach (string format in frenchJuly28Formats) { - Console.WriteLine(format); - } - // - } + IFormatProvider culture = + new System.Globalization.CultureInfo("fr-FR", true); + // Get the short date formats using the "fr-FR" culture. + string[] frenchJuly28Formats = + july28.GetDateTimeFormats(culture); - private static void ShowDefaultDFormat() - { - // - DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); - - // Get the long date formats using the current culture. - string [] longJuly28Formats = - july28.GetDateTimeFormats('D'); + // Display july28 in various formats using "fr-FR" culture. + foreach (string format in frenchJuly28Formats) + { + Console.WriteLine(format); + } + // + } - // Display july28 in all long date formats. - foreach (string format in longJuly28Formats) { - Console.WriteLine(format); - } - // The example displays the following output: - // Tuesday, July 28, 2009 - // July 28, 2009 - // Tuesday, 28 July, 2009 - // 28 July, 2009 - // - } + private static void ShowDefaultDFormat() + { + // + DateTime july28 = new(2009, 7, 28, 5, 23, 15); - private static void ShowFrenchDFormat() - { - // - DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); - - IFormatProvider culture = - new System.Globalization.CultureInfo("fr-FR", true); - // Get the short date formats using the "fr-FR" culture. - string [] frenchJuly28Formats = - july28.GetDateTimeFormats('d', culture); + // Get the long date formats using the current culture. + string[] longJuly28Formats = + july28.GetDateTimeFormats('D'); - // Display july28 in short date formats using "fr-FR" culture. - foreach (string format in frenchJuly28Formats) { - Console.WriteLine(format); - } - // The example displays the following output: - // 28/07/2009 - // 28/07/09 - // 28.07.09 - // 28-07-09 - // 2009-07-28 - // - } + // Display july28 in all long date formats. + foreach (string format in longJuly28Formats) + { + Console.WriteLine(format); + } + // The example displays the following output: + // Tuesday, July 28, 2009 + // July 28, 2009 + // Tuesday, 28 July, 2009 + // 28 July, 2009 + // + } + + private static void ShowFrenchDFormat() + { + // + DateTime july28 = new(2009, 7, 28, 5, 23, 15); + + IFormatProvider culture = + new System.Globalization.CultureInfo("fr-FR", true); + // Get the short date formats using the "fr-FR" culture. + string[] frenchJuly28Formats = + july28.GetDateTimeFormats('d', culture); + + // Display july28 in short date formats using "fr-FR" culture. + foreach (string format in frenchJuly28Formats) + { + Console.WriteLine(format); + } + // The example displays the following output: + // 28/07/2009 + // 28/07/09 + // 28.07.09 + // 28-07-09 + // 2009-07-28 + // + } } diff --git a/snippets/csharp/System/DateTime/Hour/Hour1.cs b/snippets/csharp/System/DateTime/Hour/Hour1.cs index ab8f1966f96..ae7876ea5e4 100644 --- a/snippets/csharp/System/DateTime/Hour/Hour1.cs +++ b/snippets/csharp/System/DateTime/Hour/Hour1.cs @@ -2,12 +2,12 @@ public class Class1 { - public static void Main() - { - // - DateTime date1 = new DateTime(2008, 4, 1, 18, 53, 0); - Console.WriteLine(date1.ToString("%h")); // Displays 6 - Console.WriteLine(date1.ToString("h tt")); // Displays 6 PM - // - } + public static void Main() + { + // + DateTime date1 = new(2008, 4, 1, 18, 53, 0); + Console.WriteLine(date1.ToString("%h")); // Displays 6 + Console.WriteLine(date1.ToString("h tt")); // Displays 6 PM + // + } } diff --git a/snippets/csharp/System/DateTime/IsLeapYear/IsLeapYear1.cs b/snippets/csharp/System/DateTime/IsLeapYear/IsLeapYear1.cs index 56d6d92c897..d97d8e8befb 100644 --- a/snippets/csharp/System/DateTime/IsLeapYear/IsLeapYear1.cs +++ b/snippets/csharp/System/DateTime/IsLeapYear/IsLeapYear1.cs @@ -3,21 +3,19 @@ public class IsLeapYear { - public static void Main() - { - for (int year = 1994; year <= 2014; year++) - { - if (DateTime.IsLeapYear(year)) - { - Console.WriteLine("{0} is a leap year.", year); - DateTime leapDay = new DateTime(year, 2, 29); - DateTime nextYear = leapDay.AddYears(1); - Console.WriteLine(" One year from {0} is {1}.", - leapDay.ToString("d"), - nextYear.ToString("d")); - } - } - } + public static void Main() + { + for (int year = 1994; year <= 2014; year++) + { + if (DateTime.IsLeapYear(year)) + { + Console.WriteLine($"{year} is a leap year."); + DateTime leapDay = new(year, 2, 29); + DateTime nextYear = leapDay.AddYears(1); + Console.WriteLine($" One year from {leapDay.ToString("d")} is {nextYear.ToString("d")}."); + } + } + } } // The example produces the following output: // 1996 is a leap year. diff --git a/snippets/csharp/System/DateTime/Kind/ks.cs b/snippets/csharp/System/DateTime/Kind/ks.cs index e444717bea2..5548646ecfa 100644 --- a/snippets/csharp/System/DateTime/Kind/ks.cs +++ b/snippets/csharp/System/DateTime/Kind/ks.cs @@ -59,8 +59,7 @@ public static void Display(string title, DateTime inputDt) // Display the original DateTime. dtString = dispDt.ToString(datePatt); - Console.WriteLine("{0} {1}, Kind = {2}", - title, dtString, dispDt.Kind); + Console.WriteLine($"{title} {dtString}, Kind = {dispDt.Kind}"); // Convert inputDt to local time and display the result. // If inputDt.Kind is DateTimeKind.Utc, the conversion is performed. @@ -70,8 +69,7 @@ public static void Display(string title, DateTime inputDt) dispDt = inputDt.ToLocalTime(); dtString = dispDt.ToString(datePatt); - Console.WriteLine(" ToLocalTime: {0}, Kind = {1}", - dtString, dispDt.Kind); + Console.WriteLine($" ToLocalTime: {dtString}, Kind = {dispDt.Kind}"); // Convert inputDt to universal time and display the result. // If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed. @@ -81,8 +79,7 @@ public static void Display(string title, DateTime inputDt) dispDt = inputDt.ToUniversalTime(); dtString = dispDt.ToString(datePatt); - Console.WriteLine(" ToUniversalTime: {0}, Kind = {1}", - dtString, dispDt.Kind); + Console.WriteLine($" ToUniversalTime: {dtString}, Kind = {dispDt.Kind}"); Console.WriteLine(); } @@ -91,8 +88,7 @@ public static void Display(string title, DateTime inputDt) public static void DisplayNow(string title, DateTime inputDt) { string dtString = inputDt.ToString(datePatt); - Console.WriteLine("{0} {1}, Kind = {2}", - title, dtString, inputDt.Kind); + Console.WriteLine($"{title} {dtString}, Kind = {inputDt.Kind}"); } } diff --git a/snippets/csharp/System/DateTime/MaxValue/MinValue.cs b/snippets/csharp/System/DateTime/MaxValue/MinValue.cs index 85e0532cde8..4ac6c2aff78 100644 --- a/snippets/csharp/System/DateTime/MaxValue/MinValue.cs +++ b/snippets/csharp/System/DateTime/MaxValue/MinValue.cs @@ -2,37 +2,33 @@ public class Example { - public static void Main() - { - // - // Define an uninitialized date. - DateTime date1 = new DateTime(); - Console.Write(date1); - if (date1.Equals(DateTime.MinValue)) - Console.WriteLine(" (Equals Date.MinValue)"); - // The example displays the following output: - // 1/1/0001 12:00:00 AM (Equals Date.MinValue) - // + public static void Main() + { + // + // Define an uninitialized date. + DateTime date1 = new(); + Console.Write(date1); + if (date1.Equals(DateTime.MinValue)) + Console.WriteLine(" (Equals Date.MinValue)"); + // The example displays the following output: + // 1/1/0001 12:00:00 AM (Equals Date.MinValue) + // - // - // Attempt to assign an out-of-range value to a DateTime constructor. - long numberOfTicks = Int64.MaxValue; - DateTime validDate; + // + // Attempt to assign an out-of-range value to a DateTime constructor. + long numberOfTicks = long.MaxValue; + DateTime validDate; - // Validate the value. - if (numberOfTicks >= DateTime.MinValue.Ticks && - numberOfTicks <= DateTime.MaxValue.Ticks) - validDate = new DateTime(numberOfTicks); - else if (numberOfTicks < DateTime.MinValue.Ticks) - Console.WriteLine("{0:N0} is less than {1:N0} ticks.", - numberOfTicks, - DateTime.MinValue.Ticks); - else - Console.WriteLine("{0:N0} is greater than {1:N0} ticks.", - numberOfTicks, - DateTime.MaxValue.Ticks); - // The example displays the following output: - // 9,223,372,036,854,775,807 is greater than 3,155,378,975,999,999,999 ticks. - // - } + // Validate the value. + if (numberOfTicks >= DateTime.MinValue.Ticks && + numberOfTicks <= DateTime.MaxValue.Ticks) + validDate = new(numberOfTicks); + else if (numberOfTicks < DateTime.MinValue.Ticks) + Console.WriteLine($"{numberOfTicks:N0} is less than {DateTime.MinValue.Ticks:N0} ticks."); + else + Console.WriteLine($"{numberOfTicks:N0} is greater than {DateTime.MaxValue.Ticks:N0} ticks."); + // The example displays the following output: + // 9,223,372,036,854,775,807 is greater than 3,155,378,975,999,999,999 ticks. + // + } } diff --git a/snippets/csharp/System/DateTime/Millisecond/Millisecond.cs b/snippets/csharp/System/DateTime/Millisecond/Millisecond.cs index bb64998f2ea..a7883ac06b4 100644 --- a/snippets/csharp/System/DateTime/Millisecond/Millisecond.cs +++ b/snippets/csharp/System/DateTime/Millisecond/Millisecond.cs @@ -4,26 +4,23 @@ public class Class1 { public static void Main() { - // - DateTime date1 = new DateTime(2008, 1, 1, 0, 30, 45, 125); - Console.WriteLine("Milliseconds: {0:fff}", - date1); // displays Milliseconds: 125 - // + // + DateTime date1 = new(2008, 1, 1, 0, 30, 45, 125); + Console.WriteLine($"Milliseconds: {date1:fff}"); // displays Milliseconds: 125 + // - // - DateTime date2 = new DateTime(2008, 1, 1, 0, 30, 45, 125); - Console.WriteLine("Date: {0:o}", - date2); - // Displays the following output to the console: - // Date: 2008-01-01T00:30:45.1250000 - // + // + DateTime date2 = new(2008, 1, 1, 0, 30, 45, 125); + Console.WriteLine($"Date: {date2:o}"); + // Displays the following output to the console: + // Date: 2008-01-01T00:30:45.1250000 + // - // - DateTime date3 = new DateTime(2008, 1, 1, 0, 30, 45, 125); - Console.WriteLine("Date with milliseconds: {0:MM/dd/yyy HH:mm:ss.fff}", - date3); - // Displays the following output to the console: - // Date with milliseconds: 01/01/2008 00:30:45.125 - // + // + DateTime date3 = new(2008, 1, 1, 0, 30, 45, 125); + Console.WriteLine($"Date with milliseconds: {date3:MM/dd/yyy HH:mm:ss.fff}"); + // Displays the following output to the console: + // Date with milliseconds: 01/01/2008 00:30:45.125 + // } } diff --git a/snippets/csharp/System/DateTime/Now/now1.cs b/snippets/csharp/System/DateTime/Now/now1.cs index f2deeb40dd1..4c8c8e1d889 100644 --- a/snippets/csharp/System/DateTime/Now/now1.cs +++ b/snippets/csharp/System/DateTime/Now/now1.cs @@ -4,18 +4,18 @@ public class Example { - public static void Main() - { - DateTime localDate = DateTime.Now; - String[] cultureNames = { "en-US", "en-GB", "fr-FR", + public static void Main() + { + DateTime localDate = DateTime.Now; + string[] cultureNames = { "en-US", "en-GB", "fr-FR", "de-DE", "ru-RU" }; - foreach (var cultureName in cultureNames) { - var culture = new CultureInfo(cultureName); - Console.WriteLine("{0}: {1}", cultureName, - localDate.ToString(culture)); - } - } + foreach (string cultureName in cultureNames) + { + var culture = new CultureInfo(cultureName); + Console.WriteLine($"{cultureName}: {localDate.ToString(culture)}"); + } + } } // The example displays the following output: // en-US: 6/19/2015 10:03:06 AM @@ -23,4 +23,4 @@ public static void Main() // fr-FR: 19/06/2015 10:03:06 // de-DE: 19.06.2015 10:03:06 // ru-RU: 19.06.2015 10:03:06 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/Now/now2.cs b/snippets/csharp/System/DateTime/Now/now2.cs index aaefb30771c..4a6e9dad51b 100644 --- a/snippets/csharp/System/DateTime/Now/now2.cs +++ b/snippets/csharp/System/DateTime/Now/now2.cs @@ -4,22 +4,21 @@ public class Example { - public static void Main() - { - DateTime localDate = DateTime.Now; - DateTime utcDate = DateTime.UtcNow; - String[] cultureNames = { "en-US", "en-GB", "fr-FR", - "de-DE", "ru-RU" } ; + public static void Main() + { + DateTime localDate = DateTime.Now; + DateTime utcDate = DateTime.UtcNow; + string[] cultureNames = { "en-US", "en-GB", "fr-FR", + "de-DE", "ru-RU" }; - foreach (var cultureName in cultureNames) { - var culture = new CultureInfo(cultureName); - Console.WriteLine("{0}:", culture.NativeName); - Console.WriteLine(" Local date and time: {0}, {1:G}", - localDate.ToString(culture), localDate.Kind); - Console.WriteLine(" UTC date and time: {0}, {1:G}\n", - utcDate.ToString(culture), utcDate.Kind); - } - } + foreach (string cultureName in cultureNames) + { + var culture = new CultureInfo(cultureName); + Console.WriteLine($"{culture.NativeName}:"); + Console.WriteLine($" Local date and time: {localDate.ToString(culture)}, {localDate.Kind:G}"); + Console.WriteLine($" UTC date and time: {utcDate.ToString(culture)}, {utcDate.Kind:G}\n"); + } + } } // The example displays the following output: // English (United States): diff --git a/snippets/csharp/System/DateTime/Overview/Calendar.cs b/snippets/csharp/System/DateTime/Overview/Calendar.cs index 09845d52328..afdeda6ce22 100644 --- a/snippets/csharp/System/DateTime/Overview/Calendar.cs +++ b/snippets/csharp/System/DateTime/Overview/Calendar.cs @@ -100,7 +100,7 @@ private static void CalculateWeeks() Console.WriteLine("Using the Gregorian calendar:"); Console.WriteLine($"Date: {dat:d}"); Console.WriteLine($"Day of Week: {dat.DayOfWeek}"); - Console.WriteLine($"Week of year: {greg.GetWeekOfYear(dat, System.Globalization.CalendarWeekRule.FirstDay,DayOfWeek.Sunday)}"); + Console.WriteLine($"Week of year: {greg.GetWeekOfYear(dat, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}"); // The example displays the following output: // Using the Thai Buddhist Era calendar // Date : 18/8/1395 diff --git a/snippets/csharp/System/DateTime/Overview/DateTimeComparisons.cs b/snippets/csharp/System/DateTime/Overview/DateTimeComparisons.cs index b7342dbee56..4a429d6cb6a 100644 --- a/snippets/csharp/System/DateTime/Overview/DateTimeComparisons.cs +++ b/snippets/csharp/System/DateTime/Overview/DateTimeComparisons.cs @@ -1,15 +1,12 @@ using System; -using System.Collections.Generic; -using System.Text; + + namespace SystemDateTimeReference { public static class DateTimeComparisons { - public static void Snippets() - { - TestRoughlyEquals(); - } + public static void Snippets() => TestRoughlyEquals(); // public static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds) diff --git a/snippets/csharp/System/DateTime/Overview/Instantiation.cs b/snippets/csharp/System/DateTime/Overview/Instantiation.cs index 0b833830532..d69a4f239d4 100644 --- a/snippets/csharp/System/DateTime/Overview/Instantiation.cs +++ b/snippets/csharp/System/DateTime/Overview/Instantiation.cs @@ -32,10 +32,10 @@ private static void InstantiateWithReturnValue() private static void InstantiateFromString() { // - var dateString = "5/1/2008 8:30:52 AM"; + string dateString = "5/1/2008 8:30:52 AM"; DateTime date1 = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture); - var iso8601String = "20080501T08:30:52Z"; + string iso8601String = "20080501T08:30:52Z"; DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture); // diff --git a/snippets/csharp/System/DateTime/Overview/Parsing.cs b/snippets/csharp/System/DateTime/Overview/Parsing.cs index d202ca61f61..3e7ca5c8d91 100644 --- a/snippets/csharp/System/DateTime/Overview/Parsing.cs +++ b/snippets/csharp/System/DateTime/Overview/Parsing.cs @@ -19,10 +19,10 @@ private static void ParseStandardFormats() System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"); var date1 = new DateTime(2013, 6, 1, 12, 32, 30); - var badFormats = new List(); + var badFormats = new List(); Console.WriteLine($"{"Date String",-37} {"Date",-19}\n"); - foreach (var dateString in date1.GetDateTimeFormats()) + foreach (string dateString in date1.GetDateTimeFormats()) { DateTime parsedDate; if (DateTime.TryParse(dateString, out parsedDate)) @@ -35,7 +35,7 @@ private static void ParseStandardFormats() if (badFormats.Count > 0) { Console.WriteLine("\nStrings that could not be parsed: "); - foreach (var badFormat in badFormats) + foreach (string badFormat in badFormats) Console.WriteLine($" {badFormat}"); } // Press "Run" to see the output. @@ -50,7 +50,7 @@ private static void ParseCustomFormats() "115216", "521116", " 115216 " }; DateTime parsedDate; - foreach (var dateString in dateStrings) + foreach (string dateString in dateStrings) { if (DateTime.TryParseExact(dateString, formats, null, System.Globalization.DateTimeStyles.AllowWhiteSpaces | @@ -72,7 +72,7 @@ private static void ParseCustomFormats() private static void ParseISO8601() { // - var iso8601String = "20080501T08:30:52Z"; + string iso8601String = "20080501T08:30:52Z"; DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine($"{iso8601String} --> {dateISO8602:g}"); diff --git a/snippets/csharp/System/DateTime/Overview/Persistence.cs b/snippets/csharp/System/DateTime/Overview/Persistence.cs index 6b5630182d7..0245b8cee4b 100644 --- a/snippets/csharp/System/DateTime/Overview/Persistence.cs +++ b/snippets/csharp/System/DateTime/Overview/Persistence.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -62,12 +62,12 @@ private static void RestoreLocalDatesFromString() TimeZoneInfo.ClearCachedData(); Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - StreamReader sr = new StreamReader(filenameTxt); + StreamReader sr = new(filenameTxt); string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); sr.Close(); Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); - foreach (var inputValue in inputValues) + foreach (string inputValue in inputValues) { DateTime dateValue; if (DateTime.TryParse(inputValue, out dateValue)) @@ -137,12 +137,12 @@ private static void RestoreDatesAsInvariantStrings() TimeZoneInfo.ClearCachedData(); Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - StreamReader sr = new StreamReader(filenameTxt); + StreamReader sr = new(filenameTxt); string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); sr.Close(); Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); - foreach (var inputValue in inputValues) + foreach (string inputValue in inputValues) { DateTime dateValue; if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture, @@ -206,7 +206,7 @@ private static void SaveDatesAsInts() var fs = new FileStream(filenameInts, FileMode.Create); var bw = new BinaryWriter(fs); bw.Write(ticks.Length); - foreach (var tick in ticks) + foreach (long tick in ticks) bw.Write(tick); bw.Close(); @@ -218,8 +218,8 @@ private static void RestoreDatesAsInts() TimeZoneInfo.ClearCachedData(); Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - FileStream fs = new FileStream(filenameInts, FileMode.Open); - BinaryReader br = new BinaryReader(fs); + FileStream fs = new(filenameInts, FileMode.Open); + BinaryReader br = new(fs); int items; DateTime[] dates; diff --git a/snippets/csharp/System/DateTime/Overview/Resolution.cs b/snippets/csharp/System/DateTime/Overview/Resolution.cs index 987c52284cf..d4b2800c34c 100644 --- a/snippets/csharp/System/DateTime/Overview/Resolution.cs +++ b/snippets/csharp/System/DateTime/Overview/Resolution.cs @@ -4,10 +4,7 @@ namespace SystemDateTimeReference { public static class Resolution { - public static void Snippets() - { - DemonstrateResolution(); - } + public static void Snippets() => DemonstrateResolution(); private static void DemonstrateResolution() { @@ -15,7 +12,7 @@ private static void DemonstrateResolution() string output = ""; for (int ctr = 0; ctr <= 20; ctr++) { - output += String.Format($"{DateTime.Now.Millisecond}\n"); + output += string.Format($"{DateTime.Now.Millisecond}\n"); // Introduce a delay loop. for (int delay = 0; delay <= 1000; delay++) { } diff --git a/snippets/csharp/System/DateTime/Parse/Parse1.cs b/snippets/csharp/System/DateTime/Parse/Parse1.cs index ed3ae8332a0..2bcb3b1cf6c 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse1.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse1.cs @@ -4,53 +4,61 @@ public class DateTimeParser { - public static void Main() - { - // Assume the current culture is en-US. - // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. + public static void Main() + { + // Assume the current culture is en-US. + // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. - // Use standard en-US date and time value - DateTime dateValue; - string dateString = "2/16/2008 12:15:12 PM"; - try { - dateValue = DateTime.Parse(dateString); - Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue); - } - catch (FormatException) { - Console.WriteLine("Unable to convert '{0}'.", dateString); - } + // Use standard en-US date and time value + DateTime dateValue; + string dateString = "2/16/2008 12:15:12 PM"; + try + { + dateValue = DateTime.Parse(dateString); + Console.WriteLine($"'{dateString}' converted to {dateValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert '{dateString}'."); + } - // Reverse month and day to conform to the fr-FR culture. - // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. - dateString = "16/02/2008 12:15:12"; - try { - dateValue = DateTime.Parse(dateString); - Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue); - } - catch (FormatException) { - Console.WriteLine("Unable to convert '{0}'.", dateString); - } + // Reverse month and day to conform to the fr-FR culture. + // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. + dateString = "16/02/2008 12:15:12"; + try + { + dateValue = DateTime.Parse(dateString); + Console.WriteLine($"'{dateString}' converted to {dateValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert '{dateString}'."); + } - // Call another overload of Parse to successfully convert string - // formatted according to conventions of fr-FR culture. - try { - dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false)); - Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue); - } - catch (FormatException) { - Console.WriteLine("Unable to convert '{0}'.", dateString); - } + // Call another overload of Parse to successfully convert string + // formatted according to conventions of fr-FR culture. + try + { + dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false)); + Console.WriteLine($"'{dateString}' converted to {dateValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert '{dateString}'."); + } - // Parse string with date but no time component. - dateString = "2/16/2008"; - try { - dateValue = DateTime.Parse(dateString); - Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue); - } - catch (FormatException) { - Console.WriteLine("Unable to convert '{0}'.", dateString); - } - } + // Parse string with date but no time component. + dateString = "2/16/2008"; + try + { + dateValue = DateTime.Parse(dateString); + Console.WriteLine($"'{dateString}' converted to {dateValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert '{dateString}'."); + } + } } // The example displays the following output to the console: // '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM. diff --git a/snippets/csharp/System/DateTime/Parse/Parse2.cs b/snippets/csharp/System/DateTime/Parse/Parse2.cs index 622a76e432e..64fed7f3b9c 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse2.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse2.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - string[] dateStrings = {"2008-05-01T07:34:42-5:00", + public static void Main() + { + string[] dateStrings = {"2008-05-01T07:34:42-5:00", "2008-05-01 7:34:42Z", "Thu, 01 May 2008 07:34:42 GMT"}; - foreach (string dateString in dateStrings) - { - DateTime convertedDate = DateTime.Parse(dateString); - Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}"); - } - } + foreach (string dateString in dateStrings) + { + DateTime convertedDate = DateTime.Parse(dateString); + Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}"); + } + } } // These calls to the DateTime.Parse method display the following output: // Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM diff --git a/snippets/csharp/System/DateTime/Parse/Parse3.cs b/snippets/csharp/System/DateTime/Parse/Parse3.cs index 9cf65d9e1a3..66ddf25348c 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse3.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse3.cs @@ -4,37 +4,36 @@ public class ParseDate { - public static void Main() - { - // Define cultures to be used to parse dates. - CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"), + public static void Main() + { + // Define cultures to be used to parse dates. + CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"), CultureInfo.CreateSpecificCulture("fr-FR"), CultureInfo.CreateSpecificCulture("de-DE")}; - // Define string representations of a date to be parsed. - string[] dateStrings = {"01/10/2009 7:34 PM", + // Define string representations of a date to be parsed. + string[] dateStrings = {"01/10/2009 7:34 PM", "10.01.2009 19:34", "10-1-2009 19:34" }; - // Parse dates using each culture. - foreach (CultureInfo culture in cultures) - { - DateTime dateValue; - Console.WriteLine("Attempted conversions using {0} culture.", - culture.Name); - foreach (string dateString in dateStrings) - { - try { - dateValue = DateTime.Parse(dateString, culture); - Console.WriteLine(" Converted '{0}' to {1}.", - dateString, dateValue.ToString("f", culture)); + // Parse dates using each culture. + foreach (CultureInfo culture in cultures) + { + DateTime dateValue; + Console.WriteLine($"Attempted conversions using {culture.Name} culture."); + foreach (string dateString in dateStrings) + { + try + { + dateValue = DateTime.Parse(dateString, culture); + Console.WriteLine($" Converted '{dateString}' to {dateValue.ToString("f", culture)}."); + } + catch (FormatException) + { + Console.WriteLine($" Unable to convert '{dateString}' for culture {culture.Name}."); + } } - catch (FormatException) { - Console.WriteLine(" Unable to convert '{0}' for culture {1}.", - dateString, culture.Name); - } - } - Console.WriteLine(); - } - } + Console.WriteLine(); + } + } } // The example displays the following output to the console: // Attempted conversions using en-US culture. diff --git a/snippets/csharp/System/DateTime/Parse/Parse4.cs b/snippets/csharp/System/DateTime/Parse/Parse4.cs index 42ccf378781..b1127e5b082 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse4.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse4.cs @@ -4,77 +4,81 @@ public class ParseDateExample { - public static void Main() - { - string dateString; - CultureInfo culture ; - DateTimeStyles styles; - DateTime result; + public static void Main() + { + string dateString; + CultureInfo culture; + DateTimeStyles styles; + DateTime result; - // Parse a date and time with no styles. - dateString = "03/01/2009 10:00 AM"; - culture = CultureInfo.CreateSpecificCulture("en-US"); - styles = DateTimeStyles.None; - try { - result = DateTime.Parse(dateString, culture, styles); - Console.WriteLine("{0} converted to {1} {2}.", - dateString, result, result.Kind.ToString()); - } - catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date and time.", - dateString); - } + // Parse a date and time with no styles. + dateString = "03/01/2009 10:00 AM"; + culture = CultureInfo.CreateSpecificCulture("en-US"); + styles = DateTimeStyles.None; + try + { + result = DateTime.Parse(dateString, culture, styles); + Console.WriteLine($"{dateString} converted to {result} {result.Kind.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } - // Parse the same date and time with the AssumeLocal style. - styles = DateTimeStyles.AssumeLocal; - try { - result = DateTime.Parse(dateString, culture, styles); - Console.WriteLine("{0} converted to {1} {2}.", - dateString, result, result.Kind.ToString()); - } - catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); - } + // Parse the same date and time with the AssumeLocal style. + styles = DateTimeStyles.AssumeLocal; + try + { + result = DateTime.Parse(dateString, culture, styles); + Console.WriteLine($"{dateString} converted to {result} {result.Kind.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } - // Parse a date and time that is assumed to be local. - // This time is five hours behind UTC. The local system's time zone is - // eight hours behind UTC. - dateString = "2009/03/01T10:00:00-5:00"; - styles = DateTimeStyles.AssumeLocal; - try { - result = DateTime.Parse(dateString, culture, styles); - Console.WriteLine("{0} converted to {1} {2}.", - dateString, result, result.Kind.ToString()); - } - catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); - } + // Parse a date and time that is assumed to be local. + // This time is five hours behind UTC. The local system's time zone is + // eight hours behind UTC. + dateString = "2009/03/01T10:00:00-5:00"; + styles = DateTimeStyles.AssumeLocal; + try + { + result = DateTime.Parse(dateString, culture, styles); + Console.WriteLine($"{dateString} converted to {result} {result.Kind.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } - // Attempt to convert a string in improper ISO 8601 format. - dateString = "03/01/2009T10:00:00-5:00"; - try { - result = DateTime.Parse(dateString, culture, styles); - Console.WriteLine("{0} converted to {1} {2}.", - dateString, result, result.Kind.ToString()); - } - catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); - } + // Attempt to convert a string in improper ISO 8601 format. + dateString = "03/01/2009T10:00:00-5:00"; + try + { + result = DateTime.Parse(dateString, culture, styles); + Console.WriteLine($"{dateString} converted to {result} {result.Kind.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } - // Assume a date and time string formatted for the fr-FR culture is the local - // time and convert it to UTC. - dateString = "2008-03-01 10:00"; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal; - try { - result = DateTime.Parse(dateString, culture, styles); - Console.WriteLine("{0} converted to {1} {2}.", - dateString, result, result.Kind.ToString()); - } - catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); - } - } + // Assume a date and time string formatted for the fr-FR culture is the local + // time and convert it to UTC. + dateString = "2008-03-01 10:00"; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal; + try + { + result = DateTime.Parse(dateString, culture, styles); + Console.WriteLine($"{dateString} converted to {result} {result.Kind.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } + } } // The example displays the following output to the console: // 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified. diff --git a/snippets/csharp/System/DateTime/Parse/Parse5.cs b/snippets/csharp/System/DateTime/Parse/Parse5.cs index db607cff75f..fc75a85246a 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse5.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse5.cs @@ -4,16 +4,16 @@ [assembly: CLSCompliant(true)] public class Class1 { - public static void Main() - { - // - string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00", + public static void Main() + { + // + string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00", "2008-09-15T09:30:41.7752486Z", "2008-09-15T09:30:41.7752486", "2008-09-15T09:30:41.7752486-04:00", "Mon, 15 Sep 2008 09:30:41 GMT" }; - foreach (string formattedDate in formattedDates) - { + foreach (string formattedDate in formattedDates) + { Console.WriteLine(formattedDate); DateTime roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind); @@ -22,23 +22,23 @@ public static void Main() DateTime noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None); Console.WriteLine($" Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time."); - } - // The example displays the following output: - // 2008-09-15T09:30:41.7752486-07:00 - // With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time. - // Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time. - // 2008-09-15T09:30:41.7752486Z - // With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time. - // Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time. - // 2008-09-15T09:30:41.7752486 - // With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time. - // Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time. - // 2008-09-15T09:30:41.7752486-04:00 - // With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time. - // Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time. - // Mon, 15 Sep 2008 09:30:41 GMT - // With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time. - // Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time. - // - } + } + // The example displays the following output: + // 2008-09-15T09:30:41.7752486-07:00 + // With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time. + // Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time. + // 2008-09-15T09:30:41.7752486Z + // With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time. + // Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time. + // 2008-09-15T09:30:41.7752486 + // With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time. + // Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time. + // 2008-09-15T09:30:41.7752486-04:00 + // With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time. + // Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time. + // Mon, 15 Sep 2008 09:30:41 GMT + // With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time. + // Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time. + // + } } diff --git a/snippets/csharp/System/DateTime/Parse/Parse6.cs b/snippets/csharp/System/DateTime/Parse/Parse6.cs index 2376c19a154..fbfc8248c05 100644 --- a/snippets/csharp/System/DateTime/Parse/Parse6.cs +++ b/snippets/csharp/System/DateTime/Parse/Parse6.cs @@ -2,9 +2,9 @@ public class Example { - public static void Main() - { - (string dateAsString, string description)[] dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"), + public static void Main() + { + (string dateAsString, string description)[] dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"), ("08/18/2018", "String with a date component only"), ("8/2018", "String with a month and year component only"), ("8/18", "String with a month and day component only"), @@ -15,12 +15,13 @@ public static void Main() ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"), ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }; - Console.WriteLine($"Today is {DateTime.Now:d}\n"); + Console.WriteLine($"Today is {DateTime.Now:d}\n"); - foreach (var item in dateInfo) { - Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}"); - } - } + foreach (var item in dateInfo) + { + Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}"); + } + } } // The example displays output like the following: // Today is 2/22/2018 diff --git a/snippets/csharp/System/DateTime/ParseExact/ParseExact1.cs b/snippets/csharp/System/DateTime/ParseExact/ParseExact1.cs index 788b1f8434d..f2527193330 100644 --- a/snippets/csharp/System/DateTime/ParseExact/ParseExact1.cs +++ b/snippets/csharp/System/DateTime/ParseExact/ParseExact1.cs @@ -4,81 +4,93 @@ public class Example { - public static void Main() - { - string dateString, format; - DateTime result; - CultureInfo provider = CultureInfo.InvariantCulture; + public static void Main() + { + string dateString, format; + DateTime result; + CultureInfo provider = CultureInfo.InvariantCulture; - // Parse date-only value with invariant culture. - dateString = "06/15/2008"; - format = "d"; - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date-only value with invariant culture. + dateString = "06/15/2008"; + format = "d"; + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date-only value without leading zero in month using "d" format. - // Should throw a FormatException because standard short date pattern of - // invariant culture requires two-digit month. - dateString = "6/15/2008"; - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date-only value without leading zero in month using "d" format. + // Should throw a FormatException because standard short date pattern of + // invariant culture requires two-digit month. + dateString = "6/15/2008"; + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date and time with custom specifier. - dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; - format = "ddd dd MMM yyyy h:mm tt zzz"; - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date and time with custom specifier. + dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; + format = "ddd dd MMM yyyy h:mm tt zzz"; + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date and time with offset but without offset's minutes. - // Should throw a FormatException because "zzz" specifier requires leading - // zero in hours. - dateString = "Sun 15 Jun 2008 8:30 AM -06"; - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date and time with offset but without offset's minutes. + // Should throw a FormatException because "zzz" specifier requires leading + // zero in hours. + dateString = "Sun 15 Jun 2008 8:30 AM -06"; + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - dateString = "15/06/2008 08:30"; - format = "g"; - provider = new CultureInfo("fr-FR"); - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + dateString = "15/06/2008 08:30"; + format = "g"; + provider = new("fr-FR"); + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse a date that includes seconds and milliseconds - // by using the French (France) and invariant cultures. - dateString = "18/08/2015 06:30:15.006542"; - format = "dd/MM/yyyy HH:mm:ss.ffffff"; - try { - result = DateTime.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) { - Console.WriteLine("{0} is not in the correct format.", dateString); - } - } + // Parse a date that includes seconds and milliseconds + // by using the French (France) and invariant cultures. + dateString = "18/08/2015 06:30:15.006542"; + format = "dd/MM/yyyy HH:mm:ss.ffffff"; + try + { + result = DateTime.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } + } } // The example displays the following output: // 06/15/2008 converts to 6/15/2008 12:00:00 AM. diff --git a/snippets/csharp/System/DateTime/ParseExact/parseexact2.cs b/snippets/csharp/System/DateTime/ParseExact/parseexact2.cs index d49c48c3a7d..8afe1867564 100644 --- a/snippets/csharp/System/DateTime/ParseExact/parseexact2.cs +++ b/snippets/csharp/System/DateTime/ParseExact/parseexact2.cs @@ -4,94 +4,102 @@ public class Example { - public static void Main() - { - CultureInfo enUS = new CultureInfo("en-US"); - string dateString; - DateTime dateValue; + public static void Main() + { + CultureInfo enUS = new("en-US"); + string dateString; + DateTime dateValue; - // Parse date with no style flags. - dateString = " 5/01/2009 8:30 AM"; - try { - dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } - // Allow a leading space in the date string. - try { - dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } + // Parse date with no style flags. + dateString = " 5/01/2009 8:30 AM"; + try + { + dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } + // Allow a leading space in the date string. + try + { + dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } - // Use custom formats with M and MM. - dateString = "5/01/2009 09:00"; - try { - dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } - // Allow a leading space in the date string. - try { - dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } + // Use custom formats with M and MM. + dateString = "5/01/2009 09:00"; + try + { + dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } + // Allow a leading space in the date string. + try + { + dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } - // Parse a string with time zone information. - dateString = "05/01/2009 01:30:42 PM -05:00"; - try { - dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } - // Allow a leading space in the date string. - try { - dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, - DateTimeStyles.AdjustToUniversal); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } + // Parse a string with time zone information. + dateString = "05/01/2009 01:30:42 PM -05:00"; + try + { + dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } + // Allow a leading space in the date string. + try + { + dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, + DateTimeStyles.AdjustToUniversal); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } - // Parse a string representing UTC. - dateString = "2008-06-11T16:11:20.0904778Z"; - try { - dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, - DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } - try { - dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind); - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - } - catch (FormatException) { - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } - } + // Parse a string representing UTC. + dateString = "2008-06-11T16:11:20.0904778Z"; + try + { + dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, + DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } + try + { + dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind); + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } + } } // The example displays the following output: // ' 5/01/2009 8:30 AM' is not in an acceptable format. diff --git a/snippets/csharp/System/DateTime/ParseExact/parseexact3.cs b/snippets/csharp/System/DateTime/ParseExact/parseexact3.cs index 86cc86775e6..aa6deb0f99b 100644 --- a/snippets/csharp/System/DateTime/ParseExact/parseexact3.cs +++ b/snippets/csharp/System/DateTime/ParseExact/parseexact3.cs @@ -4,33 +4,35 @@ public class Example { - public static void Main() - { - string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", + public static void Main() + { + string[] formats = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", "M/d/yyyy h:mm", "M/d/yyyy h:mm", "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm", "MM/d/yyyy HH:mm:ss.ffffff" }; - string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", + string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", "5/1/2009 6:32:00", "05/01/2009 06:32", "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00", "08/28/2015 16:17:39.125", "08/28/2015 16:17:39.125000" }; - DateTime dateValue; + DateTime dateValue; - foreach (string dateString in dateStrings) - { - try { - dateValue = DateTime.ParseExact(dateString, formats, - new CultureInfo("en-US"), - DateTimeStyles.None); - Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue); - } - catch (FormatException) { - Console.WriteLine("Unable to convert '{0}' to a date.", dateString); - } - } - } + foreach (string dateString in dateStrings) + { + try + { + dateValue = DateTime.ParseExact(dateString, formats, + new CultureInfo("en-US"), + DateTimeStyles.None); + Console.WriteLine($"Converted '{dateString}' to {dateValue}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to convert '{dateString}' to a date."); + } + } + } } // The example displays the following output: // Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. diff --git a/snippets/csharp/System/DateTime/Ticks/Ticks.cs b/snippets/csharp/System/DateTime/Ticks/Ticks.cs index a4f0d3c604b..2539bfd0c58 100644 --- a/snippets/csharp/System/DateTime/Ticks/Ticks.cs +++ b/snippets/csharp/System/DateTime/Ticks/Ticks.cs @@ -2,33 +2,30 @@ public class Class1 { - public static void Main() - { - // - DateTime centuryBegin = new DateTime(2001, 1, 1); - DateTime currentDate = DateTime.Now; + public static void Main() + { + // + DateTime centuryBegin = new(2001, 1, 1); + DateTime currentDate = DateTime.Now; - long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks; - TimeSpan elapsedSpan = new TimeSpan(elapsedTicks); + long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks; + TimeSpan elapsedSpan = new(elapsedTicks); - Console.WriteLine("Elapsed from the beginning of the century to {0:f}:", - currentDate); - Console.WriteLine(" {0:N0} nanoseconds", elapsedTicks * 100); - Console.WriteLine(" {0:N0} ticks", elapsedTicks); - Console.WriteLine(" {0:N2} seconds", elapsedSpan.TotalSeconds); - Console.WriteLine(" {0:N2} minutes", elapsedSpan.TotalMinutes); - Console.WriteLine(" {0:N0} days, {1} hours, {2} minutes, {3} seconds", - elapsedSpan.Days, elapsedSpan.Hours, - elapsedSpan.Minutes, elapsedSpan.Seconds); + Console.WriteLine($"Elapsed from the beginning of the century to {currentDate:f}:"); + Console.WriteLine($" {elapsedTicks * 100:N0} nanoseconds"); + Console.WriteLine($" {elapsedTicks:N0} ticks"); + Console.WriteLine($" {elapsedSpan.TotalSeconds:N2} seconds"); + Console.WriteLine($" {elapsedSpan.TotalMinutes:N2} minutes"); + Console.WriteLine($" {elapsedSpan.Days:N0} days, {elapsedSpan.Hours} hours, {elapsedSpan.Minutes} minutes, {elapsedSpan.Seconds} seconds"); - // This example displays an output similar to the following: - // - // Elapsed from the beginning of the century to Thursday, 14 November 2019 18:21: - // 595,448,498,171,000,000 nanoseconds - // 5,954,484,981,710,000 ticks - // 595,448,498.17 seconds - // 9,924,141.64 minutes - // 6,891 days, 18 hours, 21 minutes, 38 seconds - // - } + // This example displays an output similar to the following: + // + // Elapsed from the beginning of the century to Thursday, 14 November 2019 18:21: + // 595,448,498,171,000,000 nanoseconds + // 5,954,484,981,710,000 ticks + // 595,448,498.17 seconds + // 9,924,141.64 minutes + // 6,891 days, 18 hours, 21 minutes, 38 seconds + // + } } diff --git a/snippets/csharp/System/DateTime/TimeOfDay/timeofday1.cs b/snippets/csharp/System/DateTime/TimeOfDay/timeofday1.cs index 62eef974982..a093245dbb0 100644 --- a/snippets/csharp/System/DateTime/TimeOfDay/timeofday1.cs +++ b/snippets/csharp/System/DateTime/TimeOfDay/timeofday1.cs @@ -3,17 +3,18 @@ public class Example { - public static void Main() - { - DateTime[] dates = { DateTime.Now, + public static void Main() + { + DateTime[] dates = { DateTime.Now, new DateTime(2013, 9, 14, 9, 28, 0), new DateTime(2011, 5, 28, 10, 35, 0), new DateTime(1979, 12, 25, 14, 30, 0) }; - foreach (var date in dates) { - Console.WriteLine("Day: {0:d} Time: {1:g}", date.Date, date.TimeOfDay); - Console.WriteLine("Day: {0:d} Time: {0:t}\n", date); - } - } + foreach (var date in dates) + { + Console.WriteLine($"Day: {date.Date:d} Time: {date.TimeOfDay:g}"); + Console.WriteLine("Day: {0:d} Time: {0:t}\n", date); + } + } } // The example displays output like the following: // Day: 7/25/2012 Time: 10:08:12.9713744 diff --git a/snippets/csharp/System/DateTime/ToFileTime/class1.cs b/snippets/csharp/System/DateTime/ToFileTime/class1.cs index 18b33dc3a52..db02a3ac6ed 100644 --- a/snippets/csharp/System/DateTime/ToFileTime/class1.cs +++ b/snippets/csharp/System/DateTime/ToFileTime/class1.cs @@ -1,29 +1,29 @@ -using System; + namespace ToFileTime { - class Class1 - { - // - static void Main(string[] args) - { - System.Console.WriteLine("Enter the file path:"); - string filePath = System.Console.ReadLine(); + class Class1 + { + // + static void Main(string[] args) + { + System.Console.WriteLine("Enter the file path:"); + string filePath = System.Console.ReadLine(); - if (System.IO.File.Exists(filePath)) { - System.DateTime fileCreationDateTime = - System.IO.File.GetCreationTime(filePath); + if (System.IO.File.Exists(filePath)) + { + System.DateTime fileCreationDateTime = + System.IO.File.GetCreationTime(filePath); - long fileCreationFileTime = fileCreationDateTime.ToFileTime(); + long fileCreationFileTime = fileCreationDateTime.ToFileTime(); - System.Console.WriteLine("{0} in file time is {1}.", - fileCreationDateTime, - fileCreationFileTime); - } - else { - System.Console.WriteLine("{0} is an invalid file", filePath); - } - } - // - } + System.Console.WriteLine($"{fileCreationDateTime} in file time is {fileCreationFileTime}."); + } + else + { + System.Console.WriteLine($"{filePath} is an invalid file"); + } + } + // + } } diff --git a/snippets/csharp/System/DateTime/ToLocalTime/class1.cs b/snippets/csharp/System/DateTime/ToLocalTime/class1.cs index d014b7f09b5..facdd349039 100644 --- a/snippets/csharp/System/DateTime/ToLocalTime/class1.cs +++ b/snippets/csharp/System/DateTime/ToLocalTime/class1.cs @@ -3,42 +3,42 @@ class Example { - static void Main() - { - DateTime localDateTime, univDateTime; - - Console.WriteLine("Enter a date and time."); - string strDateTime = Console.ReadLine(); + static void Main() + { + DateTime localDateTime, univDateTime; - try { - localDateTime = DateTime.Parse(strDateTime); - univDateTime = localDateTime.ToUniversalTime(); + Console.WriteLine("Enter a date and time."); + string strDateTime = Console.ReadLine(); - Console.WriteLine("{0} local time is {1} universal time.", - localDateTime, - univDateTime); - } - catch (FormatException) { - Console.WriteLine("Invalid format."); - return; - } + try + { + localDateTime = DateTime.Parse(strDateTime); + univDateTime = localDateTime.ToUniversalTime(); - Console.WriteLine("Enter a date and time in universal time."); - strDateTime = Console.ReadLine(); + Console.WriteLine($"{localDateTime} local time is {univDateTime} universal time."); + } + catch (FormatException) + { + Console.WriteLine("Invalid format."); + return; + } - try { - univDateTime = DateTime.Parse(strDateTime); - localDateTime = univDateTime.ToLocalTime(); + Console.WriteLine("Enter a date and time in universal time."); + strDateTime = Console.ReadLine(); - Console.WriteLine("{0} universal time is {1} local time.", - univDateTime, - localDateTime); - } - catch (FormatException) { - Console.WriteLine("Invalid format."); - return; - } - } + try + { + univDateTime = DateTime.Parse(strDateTime); + localDateTime = univDateTime.ToLocalTime(); + + Console.WriteLine($"{univDateTime} universal time is {localDateTime} local time."); + } + catch (FormatException) + { + Console.WriteLine("Invalid format."); + return; + } + } } // The example displays output like the following when run on a // computer whose culture is en-US in the Pacific Standard Time zone: diff --git a/snippets/csharp/System/DateTime/ToLocalTime/tolocaltime1.cs b/snippets/csharp/System/DateTime/ToLocalTime/tolocaltime1.cs index 767a9984b1f..8f119ce8925 100644 --- a/snippets/csharp/System/DateTime/ToLocalTime/tolocaltime1.cs +++ b/snippets/csharp/System/DateTime/ToLocalTime/tolocaltime1.cs @@ -3,17 +3,16 @@ public class Example { - public static void Main() - { - DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 0, DateTimeKind.Local); - Console.WriteLine("Invalid time: {0}", - TimeZoneInfo.Local.IsInvalidTime(date1)); - DateTime utcDate1 = date1.ToUniversalTime(); - DateTime date2 = utcDate1.ToLocalTime(); - Console.WriteLine("{0} --> {1}", date1, date2); - } + public static void Main() + { + DateTime date1 = new(2010, 3, 14, 2, 30, 0, DateTimeKind.Local); + Console.WriteLine($"Invalid time: {TimeZoneInfo.Local.IsInvalidTime(date1)}"); + DateTime utcDate1 = date1.ToUniversalTime(); + DateTime date2 = utcDate1.ToLocalTime(); + Console.WriteLine($"{date1} --> {date2}"); + } } // The example displays the following output: // Invalid time: True // 3/14/2010 2:30:00 AM --> 3/14/2010 3:30:00 AM -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTime/ToLongDateString/sls.cs b/snippets/csharp/System/DateTime/ToLongDateString/sls.cs index 2f72c94efd6..9aaaad091db 100644 --- a/snippets/csharp/System/DateTime/ToLongDateString/sls.cs +++ b/snippets/csharp/System/DateTime/ToLongDateString/sls.cs @@ -8,7 +8,7 @@ public static void Main() { // Initialize a DateTime object. Console.WriteLine("Initialize the DateTime object to May 16, 2001 3:02:15 AM.\n"); - DateTime dateAndTime = new System.DateTime(2001, 5, 16, 3, 2, 15); + DateTime dateAndTime = new(2001, 5, 16, 3, 2, 15); // Display the name of the current culture. Console.WriteLine($"Current culture: \"{CultureInfo.CurrentCulture.Name}\"\n"); diff --git a/snippets/csharp/System/DateTime/ToLongTimeString/sls.cs b/snippets/csharp/System/DateTime/ToLongTimeString/sls.cs index ba445f866e0..14410d4207a 100644 --- a/snippets/csharp/System/DateTime/ToLongTimeString/sls.cs +++ b/snippets/csharp/System/DateTime/ToLongTimeString/sls.cs @@ -5,29 +5,28 @@ public class Sample { - public static void Main() - { - // Create an array of culture names. - String[] names = { "en-US", "en-GB", "fr-FR", "de-DE" }; - // Initialize a DateTime object. - DateTime dateValue = new System.DateTime(2013, 5, 28, 10, 30, 15); + public static void Main() + { + // Create an array of culture names. + string[] names = { "en-US", "en-GB", "fr-FR", "de-DE" }; + // Initialize a DateTime object. + DateTime dateValue = new(2013, 5, 28, 10, 30, 15); - // Iterate the array of culture names. - foreach (var name in names) { - // Change the culture of the current thread. - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(name); - // Display the name of the current culture and the date. - Console.WriteLine("Current culture: {0}", CultureInfo.CurrentCulture.Name); - Console.WriteLine("Date: {0:G}", dateValue); + // Iterate the array of culture names. + foreach (string name in names) + { + // Change the culture of the current thread. + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(name); + // Display the name of the current culture and the date. + Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Date: {dateValue:G}"); - // Display the long time pattern and the long time. - Console.WriteLine("Long time pattern: '{0}'", - DateTimeFormatInfo.CurrentInfo.LongTimePattern); - Console.WriteLine("Long time with format string: {0:T}", dateValue); - Console.WriteLine("Long time with ToLongTimeString: {0}\n", - dateValue.ToLongTimeString()); - } - } + // Display the long time pattern and the long time. + Console.WriteLine($"Long time pattern: '{DateTimeFormatInfo.CurrentInfo.LongTimePattern}'"); + Console.WriteLine($"Long time with format string: {dateValue:T}"); + Console.WriteLine($"Long time with ToLongTimeString: {dateValue.ToLongTimeString()}\n"); + } + } } // The example displays the following output: // Current culture: en-US diff --git a/snippets/csharp/System/DateTime/ToShortDateString/ToShortDateString.cs b/snippets/csharp/System/DateTime/ToShortDateString/ToShortDateString.cs index a3dda772900..e9be1ba9981 100644 --- a/snippets/csharp/System/DateTime/ToShortDateString/ToShortDateString.cs +++ b/snippets/csharp/System/DateTime/ToShortDateString/ToShortDateString.cs @@ -5,38 +5,33 @@ public class Example { - public static void Main() - { - DateTime dateToDisplay = new DateTime(2009, 6, 1, 8, 42, 50); - CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; - // Change culture to en-US. - Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - Console.WriteLine("Displaying short date for {0} culture:", - Thread.CurrentThread.CurrentCulture.Name); - Console.WriteLine(" {0} (Short Date String)", - dateToDisplay.ToShortDateString()); - // Display using 'd' standard format specifier to illustrate it is - // identical to the string returned by ToShortDateString. - Console.WriteLine(" {0} ('d' standard format specifier)", - dateToDisplay.ToString("d")); - Console.WriteLine(); + public static void Main() + { + DateTime dateToDisplay = new(2009, 6, 1, 8, 42, 50); + CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; + // Change culture to en-US. + Thread.CurrentThread.CurrentCulture = new("en-US"); + Console.WriteLine($"Displaying short date for {Thread.CurrentThread.CurrentCulture.Name} culture:"); + Console.WriteLine($" {dateToDisplay.ToShortDateString()} (Short Date String)"); + // Display using 'd' standard format specifier to illustrate it is + // identical to the string returned by ToShortDateString. + Console.WriteLine($" {dateToDisplay.ToString("d")} ('d' standard format specifier)"); + Console.WriteLine(); - // Change culture to fr-FR. - Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); - Console.WriteLine("Displaying short date for {0} culture:", - Thread.CurrentThread.CurrentCulture.Name); - Console.WriteLine(" {0}", dateToDisplay.ToShortDateString()); - Console.WriteLine(); + // Change culture to fr-FR. + Thread.CurrentThread.CurrentCulture = new("fr-FR"); + Console.WriteLine($"Displaying short date for {Thread.CurrentThread.CurrentCulture.Name} culture:"); + Console.WriteLine($" {dateToDisplay.ToShortDateString()}"); + Console.WriteLine(); - // Change culture to nl-NL. - Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL"); - Console.WriteLine("Displaying short date for {0} culture:", - Thread.CurrentThread.CurrentCulture.Name); - Console.WriteLine(" {0}", dateToDisplay.ToShortDateString()); + // Change culture to nl-NL. + Thread.CurrentThread.CurrentCulture = new("nl-NL"); + Console.WriteLine($"Displaying short date for {Thread.CurrentThread.CurrentCulture.Name} culture:"); + Console.WriteLine($" {dateToDisplay.ToShortDateString()}"); - // Restore original culture. - Thread.CurrentThread.CurrentCulture = originalCulture; - } + // Restore original culture. + Thread.CurrentThread.CurrentCulture = originalCulture; + } } // The example displays the following output: // Displaying short date for en-US culture: diff --git a/snippets/csharp/System/DateTime/ToString/ToString1.cs b/snippets/csharp/System/DateTime/ToString/ToString1.cs index e11a9affdd4..f9b744728cb 100644 --- a/snippets/csharp/System/DateTime/ToString/ToString1.cs +++ b/snippets/csharp/System/DateTime/ToString/ToString1.cs @@ -7,7 +7,7 @@ public class ToStringExample1 public static void Main() { CultureInfo currentCulture = CultureInfo.CurrentCulture; - DateTime exampleDate = new DateTime(2021, 5, 1, 18, 32, 6); + DateTime exampleDate = new(2021, 5, 1, 18, 32, 6); // Change the current culture to en-US and display the date. CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); diff --git a/snippets/csharp/System/DateTime/ToString/ToString2.cs b/snippets/csharp/System/DateTime/ToString/ToString2.cs index 0f199955723..0b259933cc9 100644 --- a/snippets/csharp/System/DateTime/ToString/ToString2.cs +++ b/snippets/csharp/System/DateTime/ToString/ToString2.cs @@ -3,26 +3,24 @@ public class DateToStringExample2 { - public static void Main() - { - DateTime dateValue = new DateTime(2008, 6, 15, 21, 15, 07); - // Create an array of standard format strings. - string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", + public static void Main() + { + DateTime dateValue = new(2008, 6, 15, 21, 15, 07); + // Create an array of standard format strings. + string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", "R", "s", "t", "T", "u", "U", "y"}; - // Output date and time using each standard format string. - foreach (string standardFmt in standardFmts) - Console.WriteLine("{0}: {1}", standardFmt, - dateValue.ToString(standardFmt)); - Console.WriteLine(); + // Output date and time using each standard format string. + foreach (string standardFmt in standardFmts) + Console.WriteLine($"{standardFmt}: {dateValue.ToString(standardFmt)}"); + Console.WriteLine(); - // Create an array of some custom format strings. - string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", + // Create an array of some custom format strings. + string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" }; - // Output date and time using each custom format string. - foreach (string customFmt in customFmts) - Console.WriteLine("'{0}': {1}", customFmt, - dateValue.ToString(customFmt)); - } + // Output date and time using each custom format string. + foreach (string customFmt in customFmts) + Console.WriteLine($"'{customFmt}': {dateValue.ToString(customFmt)}"); + } } // This example displays the following output to the console: // d: 6/15/2008 diff --git a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception1.cs b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception1.cs index 106f5d22920..2e70c910023 100644 --- a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception1.cs +++ b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception1.cs @@ -4,22 +4,21 @@ public class Example { - public static void Main() - { - CultureInfo jaJP = new CultureInfo("ja-JP"); - jaJP.DateTimeFormat.Calendar = new JapaneseCalendar(); - DateTime date1 = new DateTime(1867, 1, 1); + public static void Main() + { + CultureInfo jaJP = new("ja-JP"); + jaJP.DateTimeFormat.Calendar = new JapaneseCalendar(); + DateTime date1 = new(1867, 1, 1); - try { - Console.WriteLine(date1.ToString(jaJP)); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", - date1, - jaJP.DateTimeFormat.Calendar.MinSupportedDateTime, - jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime); - } - } + try + { + Console.WriteLine(date1.ToString(jaJP)); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"{date1:d} is earlier than {jaJP.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"); + } + } } // The example displays the following output: // 1/1/1867 is earlier than 9/8/1868 or later than 12/31/9999 } diff --git a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception2.cs b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception2.cs index 980ac5b27b8..6f79fdb18d7 100644 --- a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception2.cs +++ b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception2.cs @@ -7,9 +7,9 @@ public class Example2 { public static void Main() { - DateTime date1 = new DateTime(550, 1, 1); + DateTime date1 = new(550, 1, 1); CultureInfo dft; - CultureInfo arSY = new CultureInfo("ar-SY"); + CultureInfo arSY = new("ar-SY"); arSY.DateTimeFormat.Calendar = new HijriCalendar(); // Change current culture to ar-SY. @@ -23,10 +23,7 @@ public static void Main() } catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0} is earlier than {1} or later than {2}", - date1.ToString("d", CultureInfo.InvariantCulture), - arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture), - arSY.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)); + Console.WriteLine($"{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {arSY.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)}"); } // Restore the default culture. diff --git a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception3.cs b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception3.cs index d49ac80bba2..138b0ecb15b 100644 --- a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception3.cs +++ b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception3.cs @@ -7,9 +7,9 @@ public class Example3 { public static void Main() { - DateTime date1 = new DateTime(1550, 7, 21); + DateTime date1 = new(1550, 7, 21); CultureInfo dft; - CultureInfo heIL = new CultureInfo("he-IL"); + CultureInfo heIL = new("he-IL"); heIL.DateTimeFormat.Calendar = new HebrewCalendar(); // Change current culture to he-IL. @@ -23,10 +23,7 @@ public static void Main() } catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0} is earlier than {1} or later than {2}", - date1.ToString("d", CultureInfo.InvariantCulture), - heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture), - heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)); + Console.WriteLine($"{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)}"); } // Restore the default culture. diff --git a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception4.cs b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception4.cs index 4d791732099..7399988047b 100644 --- a/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception4.cs +++ b/snippets/csharp/System/DateTime/ToString/datetime.tostring.argumentoutofrangeexception4.cs @@ -6,9 +6,9 @@ public class Example4 { public static void Main() { - CultureInfo arSA = new CultureInfo("ar-SA"); + CultureInfo arSA = new("ar-SA"); arSA.DateTimeFormat.Calendar = new UmAlQuraCalendar(); - DateTime date1 = new DateTime(1890, 9, 10); + DateTime date1 = new(1890, 9, 10); try { @@ -16,10 +16,7 @@ public static void Main() } catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", - date1, - arSA.DateTimeFormat.Calendar.MinSupportedDateTime, - arSA.DateTimeFormat.Calendar.MaxSupportedDateTime); + Console.WriteLine($"{date1:d} is earlier than {arSA.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {arSA.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"); } } } diff --git a/snippets/csharp/System/DateTime/ToString/source.cs b/snippets/csharp/System/DateTime/ToString/source.cs index b33f0f8c72e..ef183d9d767 100644 --- a/snippets/csharp/System/DateTime/ToString/source.cs +++ b/snippets/csharp/System/DateTime/ToString/source.cs @@ -7,7 +7,7 @@ public class MainClass public static void Main(string[] args) { DateTime dt = DateTime.Now; - String[] format = { + string[] format = { "d", "D", "f", "F", "g", "G", diff --git a/snippets/csharp/System/DateTime/ToString/tostring3.cs b/snippets/csharp/System/DateTime/ToString/tostring3.cs index e34a55034c3..eae42df6c81 100644 --- a/snippets/csharp/System/DateTime/ToString/tostring3.cs +++ b/snippets/csharp/System/DateTime/ToString/tostring3.cs @@ -4,29 +4,27 @@ public class ToStringExample4 { - public static void Main1() - { - // Create an array of all supported standard date and time format specifiers. - string[] formats = {"d", "D", "f", "F", "g", "G", "m", "o", "r", + public static void Main1() + { + // Create an array of all supported standard date and time format specifiers. + string[] formats = {"d", "D", "f", "F", "g", "G", "m", "o", "r", "s", "t", "T", "u", "U", "Y"}; - // Create an array of four cultures. - CultureInfo[] cultures = {CultureInfo.GetCultureInfo("de-DE"), + // Create an array of four cultures. + CultureInfo[] cultures = {CultureInfo.GetCultureInfo("de-DE"), CultureInfo.GetCultureInfo("en-US"), CultureInfo.GetCultureInfo("es-ES"), CultureInfo.GetCultureInfo("fr-FR")}; - // Define date to be displayed. - DateTime dateToDisplay = new DateTime(2008, 10, 31, 17, 4, 32); + // Define date to be displayed. + DateTime dateToDisplay = new(2008, 10, 31, 17, 4, 32); - // Iterate each standard format specifier. - foreach (string formatSpecifier in formats) - { - foreach (CultureInfo culture in cultures) - Console.WriteLine("{0} Format Specifier {1, 10} Culture {2, 40}", - formatSpecifier, culture.Name, - dateToDisplay.ToString(formatSpecifier, culture)); - Console.WriteLine(); - } - } + // Iterate each standard format specifier. + foreach (string formatSpecifier in formats) + { + foreach (CultureInfo culture in cultures) + Console.WriteLine($"{formatSpecifier} Format Specifier {culture.Name,10} Culture {dateToDisplay.ToString(formatSpecifier, culture),40}"); + Console.WriteLine(); + } + } } // The example displays the following output: @@ -34,72 +32,72 @@ public static void Main1() // d Format Specifier en-US Culture 10/31/2008 // d Format Specifier es-ES Culture 31/10/2008 // d Format Specifier fr-FR Culture 31/10/2008 -// +// // D Format Specifier de-DE Culture Freitag, 31. Oktober 2008 // D Format Specifier en-US Culture Friday, October 31, 2008 // D Format Specifier es-ES Culture viernes, 31 de octubre de 2008 // D Format Specifier fr-FR Culture vendredi 31 octobre 2008 -// +// // f Format Specifier de-DE Culture Freitag, 31. Oktober 2008 17:04 // f Format Specifier en-US Culture Friday, October 31, 2008 5:04 PM // f Format Specifier es-ES Culture viernes, 31 de octubre de 2008 17:04 // f Format Specifier fr-FR Culture vendredi 31 octobre 2008 17:04 -// +// // F Format Specifier de-DE Culture Freitag, 31. Oktober 2008 17:04:32 // F Format Specifier en-US Culture Friday, October 31, 2008 5:04:32 PM // F Format Specifier es-ES Culture viernes, 31 de octubre de 2008 17:04:32 // F Format Specifier fr-FR Culture vendredi 31 octobre 2008 17:04:32 -// +// // g Format Specifier de-DE Culture 31.10.2008 17:04 // g Format Specifier en-US Culture 10/31/2008 5:04 PM // g Format Specifier es-ES Culture 31/10/2008 17:04 // g Format Specifier fr-FR Culture 31/10/2008 17:04 -// +// // G Format Specifier de-DE Culture 31.10.2008 17:04:32 // G Format Specifier en-US Culture 10/31/2008 5:04:32 PM // G Format Specifier es-ES Culture 31/10/2008 17:04:32 // G Format Specifier fr-FR Culture 31/10/2008 17:04:32 -// +// // m Format Specifier de-DE Culture 31. Oktober // m Format Specifier en-US Culture October 31 // m Format Specifier es-ES Culture 31 de octubre // m Format Specifier fr-FR Culture 31 octobre -// +// // o Format Specifier de-DE Culture 2008-10-31T17:04:32.0000000 // o Format Specifier en-US Culture 2008-10-31T17:04:32.0000000 // o Format Specifier es-ES Culture 2008-10-31T17:04:32.0000000 // o Format Specifier fr-FR Culture 2008-10-31T17:04:32.0000000 -// +// // r Format Specifier de-DE Culture Fri, 31 Oct 2008 17:04:32 GMT // r Format Specifier en-US Culture Fri, 31 Oct 2008 17:04:32 GMT // r Format Specifier es-ES Culture Fri, 31 Oct 2008 17:04:32 GMT // r Format Specifier fr-FR Culture Fri, 31 Oct 2008 17:04:32 GMT -// +// // s Format Specifier de-DE Culture 2008-10-31T17:04:32 // s Format Specifier en-US Culture 2008-10-31T17:04:32 // s Format Specifier es-ES Culture 2008-10-31T17:04:32 // s Format Specifier fr-FR Culture 2008-10-31T17:04:32 -// +// // t Format Specifier de-DE Culture 17:04 // t Format Specifier en-US Culture 5:04 PM // t Format Specifier es-ES Culture 17:04 // t Format Specifier fr-FR Culture 17:04 -// +// // T Format Specifier de-DE Culture 17:04:32 // T Format Specifier en-US Culture 5:04:32 PM // T Format Specifier es-ES Culture 17:04:32 // T Format Specifier fr-FR Culture 17:04:32 -// +// // u Format Specifier de-DE Culture 2008-10-31 17:04:32Z // u Format Specifier en-US Culture 2008-10-31 17:04:32Z // u Format Specifier es-ES Culture 2008-10-31 17:04:32Z // u Format Specifier fr-FR Culture 2008-10-31 17:04:32Z -// +// // U Format Specifier de-DE Culture Freitag, 31. Oktober 2008 09:04:32 // U Format Specifier en-US Culture Friday, October 31, 2008 9:04:32 AM // U Format Specifier es-ES Culture viernes, 31 de octubre de 2008 9:04:32 // U Format Specifier fr-FR Culture vendredi 31 octobre 2008 09:04:32 -// +// // Y Format Specifier de-DE Culture Oktober 2008 // Y Format Specifier en-US Culture October 2008 // Y Format Specifier es-ES Culture octubre de 2008 diff --git a/snippets/csharp/System/DateTime/ToString/tostring5.cs b/snippets/csharp/System/DateTime/ToString/tostring5.cs index 67fecd6bea2..88a85acfde9 100644 --- a/snippets/csharp/System/DateTime/ToString/tostring5.cs +++ b/snippets/csharp/System/DateTime/ToString/tostring5.cs @@ -8,13 +8,13 @@ public static void Main3() { string[] formats = { "G", "MM/yyyy", @"MM\/dd\/yyyy HH:mm", "yyyyMMdd" }; string[] cultureNames = { "en-US", "fr-FR" }; - DateTime date = new DateTime(2015, 8, 18, 13, 31, 17); - foreach (var cultureName in cultureNames) + DateTime date = new(2015, 8, 18, 13, 31, 17); + foreach (string cultureName in cultureNames) { var culture = new CultureInfo(cultureName); CultureInfo.CurrentCulture = culture; Console.WriteLine(culture.NativeName); - foreach (var format in formats) + foreach (string format in formats) Console.WriteLine($" {format}: {date.ToString(format)}"); Console.WriteLine(); } diff --git a/snippets/csharp/System/DateTime/Today/Today1.cs b/snippets/csharp/System/DateTime/Today/Today1.cs index 7c7f11f433c..0b0baf7e857 100644 --- a/snippets/csharp/System/DateTime/Today/Today1.cs +++ b/snippets/csharp/System/DateTime/Today/Today1.cs @@ -3,18 +3,18 @@ public class Example { - public static void Main() - { - // Get the current date. - DateTime thisDay = DateTime.Today; - // Display the date in the default (general) format. - Console.WriteLine(thisDay.ToString()); - Console.WriteLine(); - // Display the date in a variety of formats. - Console.WriteLine(thisDay.ToString("d")); - Console.WriteLine(thisDay.ToString("D")); - Console.WriteLine(thisDay.ToString("g")); - } + public static void Main() + { + // Get the current date. + DateTime thisDay = DateTime.Today; + // Display the date in the default (general) format. + Console.WriteLine(thisDay.ToString()); + Console.WriteLine(); + // Display the date in a variety of formats. + Console.WriteLine(thisDay.ToString("d")); + Console.WriteLine(thisDay.ToString("D")); + Console.WriteLine(thisDay.ToString("g")); + } } // The example displays output similar to the following: // 5/3/2012 12:00:00 AM diff --git a/snippets/csharp/System/DateTime/TryParse/TryParse1.cs b/snippets/csharp/System/DateTime/TryParse/TryParse1.cs index 2f669a58f7e..0b2ae0f05be 100644 --- a/snippets/csharp/System/DateTime/TryParse/TryParse1.cs +++ b/snippets/csharp/System/DateTime/TryParse/TryParse1.cs @@ -4,26 +4,24 @@ public class Example { - public static void Main() - { - string[] dateStrings = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8", + public static void Main() + { + string[] dateStrings = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8", "2009-05-01T14:57:32.8375298-04:00", "5/01/2008", "5/01/2008 14:57:32.80 -07:00", "1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM", "Fri, 15 May 2009 20:10:57 GMT" }; - DateTime dateValue; + DateTime dateValue; - Console.WriteLine("Attempting to parse strings using {0} culture.", - CultureInfo.CurrentCulture.Name); - foreach (string dateString in dateStrings) - { - if (DateTime.TryParse(dateString, out dateValue)) - Console.WriteLine(" Converted '{0}' to {1} ({2}).", dateString, - dateValue, dateValue.Kind); - else - Console.WriteLine(" Unable to parse '{0}'.", dateString); - } - } + Console.WriteLine($"Attempting to parse strings using {CultureInfo.CurrentCulture.Name} culture."); + foreach (string dateString in dateStrings) + { + if (DateTime.TryParse(dateString, out dateValue)) + Console.WriteLine($" Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($" Unable to parse '{dateString}'."); + } + } } // The example displays output like the following: // Attempting to parse strings using en-US culture. diff --git a/snippets/csharp/System/DateTime/TryParse/tryparse2.cs b/snippets/csharp/System/DateTime/TryParse/tryparse2.cs index 25afb8e80b9..0727881de1a 100644 --- a/snippets/csharp/System/DateTime/TryParse/tryparse2.cs +++ b/snippets/csharp/System/DateTime/TryParse/tryparse2.cs @@ -4,62 +4,56 @@ public class Example { - public static void Main() - { - string dateString; - CultureInfo culture; - DateTimeStyles styles; - DateTime dateResult; + public static void Main() + { + string dateString; + CultureInfo culture; + DateTimeStyles styles; + DateTime dateResult; - // Parse a date and time with no styles. - dateString = "03/01/2009 10:00 AM"; - culture = CultureInfo.CreateSpecificCulture("en-US"); - styles = DateTimeStyles.None; - if (DateTime.TryParse(dateString, culture, styles, out dateResult)) - Console.WriteLine("{0} converted to {1} {2}.", - dateString, dateResult, dateResult.Kind); - else - Console.WriteLine("Unable to convert {0} to a date and time.", - dateString); + // Parse a date and time with no styles. + dateString = "03/01/2009 10:00 AM"; + culture = CultureInfo.CreateSpecificCulture("en-US"); + styles = DateTimeStyles.None; + if (DateTime.TryParse(dateString, culture, styles, out dateResult)) + Console.WriteLine($"{dateString} converted to {dateResult} {dateResult.Kind}."); + else + Console.WriteLine($"Unable to convert {dateString} to a date and time."); - // Parse the same date and time with the AssumeLocal style. - styles = DateTimeStyles.AssumeLocal; - if (DateTime.TryParse(dateString, culture, styles, out dateResult)) - Console.WriteLine("{0} converted to {1} {2}.", - dateString, dateResult, dateResult.Kind); - else - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); + // Parse the same date and time with the AssumeLocal style. + styles = DateTimeStyles.AssumeLocal; + if (DateTime.TryParse(dateString, culture, styles, out dateResult)) + Console.WriteLine($"{dateString} converted to {dateResult} {dateResult.Kind}."); + else + Console.WriteLine($"Unable to convert {dateString} to a date and time."); - // Parse a date and time that is assumed to be local. - // This time is five hours behind UTC. The local system's time zone is - // eight hours behind UTC. - dateString = "2009/03/01T10:00:00-5:00"; - styles = DateTimeStyles.AssumeLocal; - if (DateTime.TryParse(dateString, culture, styles, out dateResult)) - Console.WriteLine("{0} converted to {1} {2}.", - dateString, dateResult, dateResult.Kind); - else - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); + // Parse a date and time that is assumed to be local. + // This time is five hours behind UTC. The local system's time zone is + // eight hours behind UTC. + dateString = "2009/03/01T10:00:00-5:00"; + styles = DateTimeStyles.AssumeLocal; + if (DateTime.TryParse(dateString, culture, styles, out dateResult)) + Console.WriteLine($"{dateString} converted to {dateResult} {dateResult.Kind}."); + else + Console.WriteLine($"Unable to convert {dateString} to a date and time."); - // Attempt to convert a string in improper ISO 8601 format. - dateString = "03/01/2009T10:00:00-5:00"; - if (DateTime.TryParse(dateString, culture, styles, out dateResult)) - Console.WriteLine("{0} converted to {1} {2}.", - dateString, dateResult, dateResult.Kind); - else - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); + // Attempt to convert a string in improper ISO 8601 format. + dateString = "03/01/2009T10:00:00-5:00"; + if (DateTime.TryParse(dateString, culture, styles, out dateResult)) + Console.WriteLine($"{dateString} converted to {dateResult} {dateResult.Kind}."); + else + Console.WriteLine($"Unable to convert {dateString} to a date and time."); - // Assume a date and time string formatted for the fr-FR culture is the local - // time and convert it to UTC. - dateString = "2008-03-01 10:00"; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal; - if (DateTime.TryParse(dateString, culture, styles, out dateResult)) - Console.WriteLine("{0} converted to {1} {2}.", - dateString, dateResult, dateResult.Kind); - else - Console.WriteLine("Unable to convert {0} to a date and time.", dateString); - } + // Assume a date and time string formatted for the fr-FR culture is the local + // time and convert it to UTC. + dateString = "2008-03-01 10:00"; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal; + if (DateTime.TryParse(dateString, culture, styles, out dateResult)) + Console.WriteLine($"{dateString} converted to {dateResult} {dateResult.Kind}."); + else + Console.WriteLine($"Unable to convert {dateString} to a date and time."); + } } // The example displays the following output to the console: // 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified. diff --git a/snippets/csharp/System/DateTime/TryParseExact/TryParseExact1.cs b/snippets/csharp/System/DateTime/TryParseExact/TryParseExact1.cs index 6ee21cb1ac3..6b307f0e9f3 100644 --- a/snippets/csharp/System/DateTime/TryParseExact/TryParseExact1.cs +++ b/snippets/csharp/System/DateTime/TryParseExact/TryParseExact1.cs @@ -4,79 +4,71 @@ public class Example { - public static void Main() - { - CultureInfo enUS = new CultureInfo("en-US"); - string dateString; - DateTime dateValue; + public static void Main() + { + CultureInfo enUS = new("en-US"); + string dateString; + DateTime dateValue; - // Parse date with no style flags. - dateString = " 5/01/2009 8:30 AM"; - if (DateTime.TryParseExact(dateString, "g", enUS, - DateTimeStyles.None, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Parse date with no style flags. + dateString = " 5/01/2009 8:30 AM"; + if (DateTime.TryParseExact(dateString, "g", enUS, + DateTimeStyles.None, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Allow a leading space in the date string. - if (DateTime.TryParseExact(dateString, "g", enUS, - DateTimeStyles.AllowLeadingWhite, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Allow a leading space in the date string. + if (DateTime.TryParseExact(dateString, "g", enUS, + DateTimeStyles.AllowLeadingWhite, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Use custom formats with M and MM. - dateString = "5/01/2009 09:00"; - if (DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, - DateTimeStyles.None, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Use custom formats with M and MM. + dateString = "5/01/2009 09:00"; + if (DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, + DateTimeStyles.None, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Allow a leading space in the date string. - if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, - DateTimeStyles.None, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Allow a leading space in the date string. + if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, + DateTimeStyles.None, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Parse a string with time zone information. - dateString = "05/01/2009 01:30:42 PM -05:00"; - if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, - DateTimeStyles.None, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Parse a string with time zone information. + dateString = "05/01/2009 01:30:42 PM -05:00"; + if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, + DateTimeStyles.None, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Allow a leading space in the date string. - if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, - DateTimeStyles.AdjustToUniversal, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Allow a leading space in the date string. + if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, + DateTimeStyles.AdjustToUniversal, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - // Parse a string representing UTC. - dateString = "2008-06-11T16:11:20.0904778Z"; - if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, - DateTimeStyles.None, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); + // Parse a string representing UTC. + dateString = "2008-06-11T16:11:20.0904778Z"; + if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, + DateTimeStyles.None, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); - if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind, out dateValue)) - Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, - dateValue.Kind); - else - Console.WriteLine("'{0}' is not in an acceptable format.", dateString); - } + if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue} ({dateValue.Kind})."); + else + Console.WriteLine($"'{dateString}' is not in an acceptable format."); + } } // The example displays the following output: // ' 5/01/2009 8:30 AM' is not in an acceptable format. diff --git a/snippets/csharp/System/DateTime/TryParseExact/TryParseExact2.cs b/snippets/csharp/System/DateTime/TryParseExact/TryParseExact2.cs index 25203ce20f0..a633a04e32f 100644 --- a/snippets/csharp/System/DateTime/TryParseExact/TryParseExact2.cs +++ b/snippets/csharp/System/DateTime/TryParseExact/TryParseExact2.cs @@ -4,29 +4,29 @@ public class Example { - public static void Main() - { - string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", + public static void Main() + { + string[] formats = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", "M/d/yyyy h:mm", "M/d/yyyy h:mm", "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"}; - string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", + string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", "5/1/2009 6:32:00", "05/01/2009 06:32", "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; - DateTime dateValue; + DateTime dateValue; - foreach (string dateString in dateStrings) - { - if (DateTime.TryParseExact(dateString, formats, - new CultureInfo("en-US"), - DateTimeStyles.None, - out dateValue)) - Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue); - else - Console.WriteLine("Unable to convert '{0}' to a date.", dateString); - } - } + foreach (string dateString in dateStrings) + { + if (DateTime.TryParseExact(dateString, formats, + new CultureInfo("en-US"), + DateTimeStyles.None, + out dateValue)) + Console.WriteLine($"Converted '{dateString}' to {dateValue}."); + else + Console.WriteLine($"Unable to convert '{dateString}' to a date."); + } + } } // The example displays the following output: // Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. diff --git a/snippets/csharp/System/DateTime/Year/Year.cs b/snippets/csharp/System/DateTime/Year/Year.cs index 19b275305ca..b20502a15b0 100644 --- a/snippets/csharp/System/DateTime/Year/Year.cs +++ b/snippets/csharp/System/DateTime/Year/Year.cs @@ -7,21 +7,21 @@ public class YearMethodExample { public static void Main() { - // Initialize date variable and display year - DateTime date1 = new DateTime(2008, 1, 1, 6, 32, 0); - Console.WriteLine(date1.Year); // Displays 2008 + // Initialize date variable and display year + DateTime date1 = new(2008, 1, 1, 6, 32, 0); + Console.WriteLine(date1.Year); // Displays 2008 - // Set culture to th-TH - Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH"); - Console.WriteLine(date1.Year); // Displays 2008 + // Set culture to th-TH + Thread.CurrentThread.CurrentCulture = new("th-TH"); + Console.WriteLine(date1.Year); // Displays 2008 - // display year using current culture's calendar - Calendar thaiCalendar = CultureInfo.CurrentCulture.Calendar; - Console.WriteLine(thaiCalendar.GetYear(date1)); // Displays 2551 + // display year using current culture's calendar + Calendar thaiCalendar = CultureInfo.CurrentCulture.Calendar; + Console.WriteLine(thaiCalendar.GetYear(date1)); // Displays 2551 - // display year using Persian calendar - PersianCalendar persianCalendar = new PersianCalendar(); - Console.WriteLine(persianCalendar.GetYear(date1)); // Displays 1386 - } + // display year using Persian calendar + PersianCalendar persianCalendar = new(); + Console.WriteLine(persianCalendar.GetYear(date1)); // Displays 1386 + } } // diff --git a/snippets/csharp/System/DateTime/op_Addition/class1.cs b/snippets/csharp/System/DateTime/op_Addition/class1.cs index dee2c077f9b..1605ba0dea3 100644 --- a/snippets/csharp/System/DateTime/op_Addition/class1.cs +++ b/snippets/csharp/System/DateTime/op_Addition/class1.cs @@ -1,37 +1,37 @@ -using System; + namespace OpOverloads { - class Class1 - { - static void Main(string[] args) - { - // Addition operator - // - System.DateTime dTime = new System.DateTime(1980, 8, 5); + class Class1 + { + static void Main(string[] args) + { + // Addition operator + // + System.DateTime dTime = new(1980, 8, 5); - // tSpan is 17 days, 4 hours, 2 minutes and 1 second. - System.TimeSpan tSpan - = new System.TimeSpan(17, 4, 2, 1); + // tSpan is 17 days, 4 hours, 2 minutes and 1 second. + System.TimeSpan tSpan + = new(17, 4, 2, 1); - // Result gets 8/22/1980 4:02:01 AM. - System.DateTime result = dTime + tSpan; - // + // Result gets 8/22/1980 4:02:01 AM. + System.DateTime result = dTime + tSpan; + // - System.Console.WriteLine(result); + System.Console.WriteLine(result); - // Equality operator. - // - System.DateTime april19 = new DateTime(2001, 4, 19); - System.DateTime otherDate = new DateTime(1991, 6, 5); + // Equality operator. + // + System.DateTime april19 = new(2001, 4, 19); + System.DateTime otherDate = new(1991, 6, 5); - // areEqual gets false. - bool areEqual = april19 == otherDate; - - otherDate = new DateTime(2001, 4, 19); - // areEqual gets true. - areEqual = april19 == otherDate; - // - } - } + // areEqual gets false. + bool areEqual = april19 == otherDate; + + otherDate = new(2001, 4, 19); + // areEqual gets true. + areEqual = april19 == otherDate; + // + } + } } diff --git a/snippets/csharp/System/DateTime/op_Subtraction/class1.cs b/snippets/csharp/System/DateTime/op_Subtraction/class1.cs index a10bf3b0e1e..a3d4da9143d 100644 --- a/snippets/csharp/System/DateTime/op_Subtraction/class1.cs +++ b/snippets/csharp/System/DateTime/op_Subtraction/class1.cs @@ -1,32 +1,32 @@ -using System; + namespace Subtract { - class Class1 - { - static void Main(string[] args) - { - // - System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0); - System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0); - System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0); + class Class1 + { + static void Main(string[] args) + { + // + System.DateTime date1 = new(1996, 6, 3, 22, 15, 0); + System.DateTime date2 = new(1996, 12, 6, 13, 2, 0); + System.DateTime date3 = new(1996, 10, 12, 8, 42, 0); - // diff1 gets 185 days, 14 hours, and 47 minutes. - System.TimeSpan diff1 = date2.Subtract(date1); + // diff1 gets 185 days, 14 hours, and 47 minutes. + System.TimeSpan diff1 = date2.Subtract(date1); - // date4 gets 4/9/1996 5:55:00 PM. - System.DateTime date4 = date3.Subtract(diff1); + // date4 gets 4/9/1996 5:55:00 PM. + System.DateTime date4 = date3.Subtract(diff1); - // diff2 gets 55 days 4 hours and 20 minutes. - System.TimeSpan diff2 = date2 - date3; + // diff2 gets 55 days 4 hours and 20 minutes. + System.TimeSpan diff2 = date2 - date3; - // date5 gets 4/9/1996 5:55:00 PM. - System.DateTime date5 = date1 - diff2; - // + // date5 gets 4/9/1996 5:55:00 PM. + System.DateTime date5 = date1 - diff2; + // System.Console.WriteLine(diff1); - System.Console.WriteLine(date4); - System.Console.WriteLine(diff2); - System.Console.WriteLine(date4); - } - } + System.Console.WriteLine(date4); + System.Console.WriteLine(diff2); + System.Console.WriteLine(date4); + } + } } diff --git a/snippets/csharp/System/DateTimeOffset/.ctor/Constructors.cs b/snippets/csharp/System/DateTimeOffset/.ctor/Constructors.cs index ca480955cfc..8f6c75a92d7 100644 --- a/snippets/csharp/System/DateTimeOffset/.ctor/Constructors.cs +++ b/snippets/csharp/System/DateTimeOffset/.ctor/Constructors.cs @@ -3,183 +3,181 @@ public class Class1 { - public static void Main() - { - ConstructWithDateTime(); - Console.WriteLine(); - ConstructWithTicks(); - Console.WriteLine(); - ConstructWithDateAndOffset(); - Console.WriteLine(); - ConstructNonLocalWithLocalTicks(); - Console.WriteLine(); - ConstructWithDateElements(); - Console.WriteLine(); - ConstructWithDateElements2(); - Console.WriteLine(); - ConstructWithDateElements3(); - Console.WriteLine(); - ConstructWithCalendar(); - } + public static void Main() + { + ConstructWithDateTime(); + Console.WriteLine(); + ConstructWithTicks(); + Console.WriteLine(); + ConstructWithDateAndOffset(); + Console.WriteLine(); + ConstructNonLocalWithLocalTicks(); + Console.WriteLine(); + ConstructWithDateElements(); + Console.WriteLine(); + ConstructWithDateElements2(); + Console.WriteLine(); + ConstructWithDateElements3(); + Console.WriteLine(); + ConstructWithCalendar(); + } - private static void ConstructWithDateTime() - { - // - DateTime localNow = DateTime.Now; - DateTimeOffset localOffset = new DateTimeOffset(localNow); - Console.WriteLine(localOffset.ToString()); + private static void ConstructWithDateTime() + { + // + DateTime localNow = DateTime.Now; + DateTimeOffset localOffset = new(localNow); + Console.WriteLine(localOffset.ToString()); - DateTime utcNow = DateTime.UtcNow; - DateTimeOffset utcOffset = new DateTimeOffset(utcNow); - Console.WriteLine(utcOffset.ToString()); + DateTime utcNow = DateTime.UtcNow; + DateTimeOffset utcOffset = new(utcNow); + Console.WriteLine(utcOffset.ToString()); - DateTime unspecifiedNow = DateTime.SpecifyKind(DateTime.Now, - DateTimeKind.Unspecified); - DateTimeOffset unspecifiedOffset = new DateTimeOffset(unspecifiedNow); - Console.WriteLine(unspecifiedOffset.ToString()); - // - // The code produces the following output if run on Feb. 23, 2007, on - // a system 8 hours earlier than UTC: - // 2/23/2007 4:21:58 PM -08:00 - // 2/24/2007 12:21:58 AM +00:00 - // 2/23/2007 4:21:58 PM -08:00 - // - } + DateTime unspecifiedNow = DateTime.SpecifyKind(DateTime.Now, + DateTimeKind.Unspecified); + DateTimeOffset unspecifiedOffset = new(unspecifiedNow); + Console.WriteLine(unspecifiedOffset.ToString()); + // + // The code produces the following output if run on Feb. 23, 2007, on + // a system 8 hours earlier than UTC: + // 2/23/2007 4:21:58 PM -08:00 + // 2/24/2007 12:21:58 AM +00:00 + // 2/23/2007 4:21:58 PM -08:00 + // + } - private static void ConstructWithTicks() - { - // - DateTime dateWithoutOffset = new DateTime(2007, 7, 16, 13, 32, 00); - DateTimeOffset timeFromTicks = new DateTimeOffset(dateWithoutOffset.Ticks, - new TimeSpan(-5, 0, 0)); - Console.WriteLine(timeFromTicks.ToString()); - // The code produces the following output: - // 7/16/2007 1:32:00 PM -05:00 - // - } + private static void ConstructWithTicks() + { + // + DateTime dateWithoutOffset = new(2007, 7, 16, 13, 32, 00); + DateTimeOffset timeFromTicks = new(dateWithoutOffset.Ticks, + new TimeSpan(-5, 0, 0)); + Console.WriteLine(timeFromTicks.ToString()); + // The code produces the following output: + // 7/16/2007 1:32:00 PM -05:00 + // + } - private static void ConstructWithDateAndOffset() - { - // - DateTime localTime = new DateTime(2007, 07, 12, 06, 32, 00); - DateTimeOffset dateAndOffset = new DateTimeOffset(localTime, - TimeZoneInfo.Local.GetUtcOffset(localTime)); - Console.WriteLine(dateAndOffset); - // The code produces the following output: - // 7/12/2007 6:32:00 AM -07:00 - // - } + private static void ConstructWithDateAndOffset() + { + // + DateTime localTime = new(2007, 07, 12, 06, 32, 00); + DateTimeOffset dateAndOffset = new(localTime, + TimeZoneInfo.Local.GetUtcOffset(localTime)); + Console.WriteLine(dateAndOffset); + // The code produces the following output: + // 7/12/2007 6:32:00 AM -07:00 + // + } - private static void ConstructNonLocalWithLocalTicks() - { - // - DateTime localTime = DateTime.Now; - DateTimeOffset nonLocalDateWithOffset = new DateTimeOffset(localTime.Ticks, - new TimeSpan(2, 0, 0)); - Console.WriteLine(nonLocalDateWithOffset); - // - // The code produces the following output if run on Feb. 23, 2007: - // 2/23/2007 4:37:50 PM +02:00 - // - } + private static void ConstructNonLocalWithLocalTicks() + { + // + DateTime localTime = DateTime.Now; + DateTimeOffset nonLocalDateWithOffset = new(localTime.Ticks, + new TimeSpan(2, 0, 0)); + Console.WriteLine(nonLocalDateWithOffset); + // + // The code produces the following output if run on Feb. 23, 2007: + // 2/23/2007 4:37:50 PM +02:00 + // + } - private static void ConstructWithDateElements() - { - // - DateTime specificDate = new DateTime(2008, 5, 1, 06, 32, 00); - DateTimeOffset offsetDate = new DateTimeOffset(specificDate.Year, - specificDate.Month, - specificDate.Day, - specificDate.Hour, - specificDate.Minute, - specificDate.Second, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("Current time: {0}", offsetDate); - Console.WriteLine("Corresponding UTC time: {0}", offsetDate.UtcDateTime); - // The code produces the following output: - // Current time: 5/1/2008 6:32:00 AM -05:00 - // Corresponding UTC time: 5/1/2008 11:32:00 AM - // - } + private static void ConstructWithDateElements() + { + // + DateTime specificDate = new(2008, 5, 1, 06, 32, 00); + DateTimeOffset offsetDate = new(specificDate.Year, + specificDate.Month, + specificDate.Day, + specificDate.Hour, + specificDate.Minute, + specificDate.Second, + new TimeSpan(-5, 0, 0)); + Console.WriteLine($"Current time: {offsetDate}"); + Console.WriteLine($"Corresponding UTC time: {offsetDate.UtcDateTime}"); + // The code produces the following output: + // Current time: 5/1/2008 6:32:00 AM -05:00 + // Corresponding UTC time: 5/1/2008 11:32:00 AM + // + } - private static void ConstructWithDateElements2() - { - // - DateTime specificDate = new DateTime(2008, 5, 1, 6, 32, 05); - DateTimeOffset offsetDate = new DateTimeOffset(specificDate.Year - 1, - specificDate.Month, - specificDate.Day, - specificDate.Hour, - specificDate.Minute, - specificDate.Second, - 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("Current time: {0}", offsetDate); - Console.WriteLine("Corresponding UTC time: {0}", offsetDate.UtcDateTime); - // The code produces the following output: - // Current time: 5/1/2007 6:32:05 AM -05:00 - // Corresponding UTC time: 5/1/2007 11:32:05 AM - // - } + private static void ConstructWithDateElements2() + { + // + DateTime specificDate = new(2008, 5, 1, 6, 32, 05); + DateTimeOffset offsetDate = new(specificDate.Year - 1, + specificDate.Month, + specificDate.Day, + specificDate.Hour, + specificDate.Minute, + specificDate.Second, + 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine($"Current time: {offsetDate}"); + Console.WriteLine($"Corresponding UTC time: {offsetDate.UtcDateTime}"); + // The code produces the following output: + // Current time: 5/1/2007 6:32:05 AM -05:00 + // Corresponding UTC time: 5/1/2007 11:32:05 AM + // + } - private static void ConstructWithDateElements3() - { - // - string fmt = "dd MMM yyyy HH:mm:ss"; - DateTime thisDate = new DateTime(2007, 06, 12, 19, 00, 14, 16); - DateTimeOffset offsetDate = new DateTimeOffset(thisDate.Year, - thisDate.Month, - thisDate.Day, - thisDate.Hour, - thisDate.Minute, - thisDate.Second, - thisDate.Millisecond, - new TimeSpan(2, 0, 0)); - Console.WriteLine("Current time: {0}:{1}", offsetDate.ToString(fmt), offsetDate.Millisecond); - // The code produces the following output: - // Current time: 12 Jun 2007 19:00:14:16 - // - } + private static void ConstructWithDateElements3() + { + // + string fmt = "dd MMM yyyy HH:mm:ss"; + DateTime thisDate = new(2007, 06, 12, 19, 00, 14, 16); + DateTimeOffset offsetDate = new(thisDate.Year, + thisDate.Month, + thisDate.Day, + thisDate.Hour, + thisDate.Minute, + thisDate.Second, + thisDate.Millisecond, + new TimeSpan(2, 0, 0)); + Console.WriteLine($"Current time: {offsetDate.ToString(fmt)}:{offsetDate.Millisecond}"); + // The code produces the following output: + // Current time: 12 Jun 2007 19:00:14:16 + // + } - private static void ConstructWithCalendar() - { - // - CultureInfo fmt; - int year; - Calendar cal; - DateTimeOffset dateInCal; + private static void ConstructWithCalendar() + { + // + CultureInfo fmt; + int year; + Calendar cal; + DateTimeOffset dateInCal; - // Instantiate DateTimeOffset with Hebrew calendar - year = 5770; - cal = new HebrewCalendar(); - fmt = new CultureInfo("he-IL"); - fmt.DateTimeFormat.Calendar = cal; - dateInCal = new DateTimeOffset(year, 7, 12, - 15, 30, 0, 0, - cal, - new TimeSpan(2, 0, 0)); - // Display the date in the Hebrew calendar - Console.WriteLine("Date in Hebrew Calendar: {0:g}", - dateInCal.ToString(fmt)); - // Display the date in the Gregorian calendar - Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal); - Console.WriteLine(); + // Instantiate DateTimeOffset with Hebrew calendar + year = 5770; + cal = new HebrewCalendar(); + fmt = new("he-IL"); + fmt.DateTimeFormat.Calendar = cal; + dateInCal = new(year, 7, 12, + 15, 30, 0, 0, + cal, + new TimeSpan(2, 0, 0)); + // Display the date in the Hebrew calendar + Console.WriteLine($"Date in Hebrew Calendar: {dateInCal.ToString(fmt):g}"); + // Display the date in the Gregorian calendar + Console.WriteLine($"Date in Gregorian Calendar: {dateInCal:g}"); + Console.WriteLine(); - // Instantiate DateTimeOffset with Hijri calendar - year = 1431; - cal = new HijriCalendar(); - fmt = new CultureInfo("ar-SA"); - fmt.DateTimeFormat.Calendar = cal; - dateInCal = new DateTimeOffset(year, 7, 12, - 15, 30, 0, 0, - cal, - new TimeSpan(2, 0, 0)); - // Display the date in the Hijri calendar - Console.WriteLine("Date in Hijri Calendar: {0:g}", - dateInCal.ToString(fmt)); - // Display the date in the Gregorian calendar - Console.WriteLine("Date in Gregorian Calendar: {0:g}", dateInCal); - Console.WriteLine(); - // - } + // Instantiate DateTimeOffset with Hijri calendar + year = 1431; + cal = new HijriCalendar(); + fmt = new("ar-SA"); + fmt.DateTimeFormat.Calendar = cal; + dateInCal = new(year, 7, 12, + 15, 30, 0, 0, + cal, + new TimeSpan(2, 0, 0)); + // Display the date in the Hijri calendar + Console.WriteLine($"Date in Hijri Calendar: {dateInCal.ToString(fmt):g}"); + // Display the date in the Gregorian calendar + Console.WriteLine($"Date in Gregorian Calendar: {dateInCal:g}"); + Console.WriteLine(); + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/Add/Methods.cs b/snippets/csharp/System/DateTimeOffset/Add/Methods.cs index 376bd86b6b9..c219d7ab937 100644 --- a/snippets/csharp/System/DateTimeOffset/Add/Methods.cs +++ b/snippets/csharp/System/DateTimeOffset/Add/Methods.cs @@ -4,415 +4,374 @@ 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(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 #{ctr + 1} at {currentTime}."); + } + // + } + + private static void ShowStartOfWorkWeek() + { + // + DateTimeOffset workDay = new(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 {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(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(" {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(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(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 {latestBirthday:d}."); + // + } + + // + private static void CompareForEquality1() + { + DateTimeOffset firstTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + DateTimeOffset secondTime = firstTime; + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = new(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine($"{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(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + object secondTime = firstTime; + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = null; + Console.WriteLine($"{firstTime} = {secondTime}: {firstTime.Equals(secondTime)}"); + + secondTime = new DateTime(2007, 9, 1, 6, 45, 00); + Console.WriteLine($"{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(2007, 11, 15, 11, 35, 00, + DateTimeOffset.Now.Offset); + DateTimeOffset secondTime = firstTime; + Console.WriteLine($"{firstTime} = {secondTime}: {DateTimeOffset.Equals(firstTime, secondTime)}"); + + // The value of firstTime remains unchanged + secondTime = new(firstTime.DateTime, + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine($"{firstTime} = {secondTime}: {DateTimeOffset.Equals(firstTime, secondTime)}"); + + // value of firstTime remains unchanged + secondTime = new(firstTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine($"{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(2007, 10, 31, 0, 0, 0, + DateTimeOffset.Now.Offset); + + DateTimeOffset otherTime = instanceTime; + Console.WriteLine($"{instanceTime} = {otherTime}: {instanceTime.EqualsExact(otherTime)}"); + + otherTime = new(instanceTime.DateTime, + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine($"{instanceTime} = {otherTime}: {instanceTime.EqualsExact(otherTime)}"); + + otherTime = new(instanceTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine($"{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(2018, 10, 25, 18, 0, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset secondDate = new(2018, 10, 25, 18, 0, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset thirdDate = new(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(2007, 12, 3, 11, 30, 0, + new TimeSpan(-8, 0, 0)); + TimeSpan duration = new(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(2007, 3, 11, 3, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine($"Converted {originalTime.ToString()} to {localTime.ToString()}."); + + originalTime = new(2007, 3, 11, 4, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine($"Converted {originalTime.ToString()} to {localTime.ToString()}."); + + // Define a summer UTC time + originalTime = new(2007, 6, 15, 8, 0, 0, + TimeSpan.Zero); + localTime = originalTime.ToLocalTime(); + Console.WriteLine($"Converted {originalTime.ToString()} to {localTime.ToString()}."); + + // Define a winter time + originalTime = new(2007, 11, 30, 14, 0, 0, + new TimeSpan(3, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine($"Converted {originalTime.ToString()} to {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(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($"{localTime} = {otherTime}: {localTime.Equals(otherTime)}"); + Console.WriteLine($"{localTime} exactly equals {otherTime}: {localTime.EqualsExact(otherTime)}"); + Console.WriteLine(); + + // Convert other time to UTC + universalTime = localTime.ToUniversalTime(); + Console.WriteLine($"Universal time: {universalTime}"); + Console.WriteLine($"{otherTime} = {universalTime}: {universalTime.Equals(otherTime)}"); + Console.WriteLine($"{otherTime} exactly equals {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/snippets/csharp/System/DateTimeOffset/Add/Methods2.cs b/snippets/csharp/System/DateTimeOffset/Add/Methods2.cs index 108bf6c036e..b3850b14c1e 100644 --- a/snippets/csharp/System/DateTimeOffset/Add/Methods2.cs +++ b/snippets/csharp/System/DateTimeOffset/Add/Methods2.cs @@ -3,38 +3,38 @@ public class CompareTimes { - private enum TimeComparison - { - Earlier = -1, - Same = 0, - Later = 1 - }; + private enum TimeComparison + { + Earlier = -1, + Same = 0, + Later = 1 + }; - public static void Main() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); + public static void Main() + { + DateTimeOffset firstTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); - DateTimeOffset secondTime = firstTime; - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) DateTimeOffset.Compare(firstTime, secondTime)); + DateTimeOffset secondTime = firstTime; + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)DateTimeOffset.Compare(firstTime, secondTime)); - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) DateTimeOffset.Compare(firstTime, secondTime)); + secondTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)DateTimeOffset.Compare(firstTime, secondTime)); - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) DateTimeOffset.Compare(firstTime, secondTime)); - // The example displays the following output to the console: - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -07:00: Same - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -06:00: Later - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 8:45:00 AM -05:00: Same - } + secondTime = new(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)DateTimeOffset.Compare(firstTime, secondTime)); + // The example displays the following output to the console: + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -07:00: Same + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -06:00: Later + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 8:45:00 AM -05:00: Same + } } // diff --git a/snippets/csharp/System/DateTimeOffset/Add/Methods3.cs b/snippets/csharp/System/DateTimeOffset/Add/Methods3.cs index 998bd30eb16..a37103974ee 100644 --- a/snippets/csharp/System/DateTimeOffset/Add/Methods3.cs +++ b/snippets/csharp/System/DateTimeOffset/Add/Methods3.cs @@ -3,38 +3,38 @@ public class CompareTimes { - private enum TimeComparison - { - Earlier = -1, - Same = 0, - Later = 1 - }; + private enum TimeComparison + { + Earlier = -1, + Same = 0, + Later = 1 + }; - public static void Main() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); + public static void Main() + { + DateTimeOffset firstTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); - DateTimeOffset secondTime = firstTime; - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) firstTime.CompareTo(secondTime)); + DateTimeOffset secondTime = firstTime; + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)firstTime.CompareTo(secondTime)); - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) firstTime.CompareTo(secondTime)); + secondTime = new(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)firstTime.CompareTo(secondTime)); - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("Comparing {0} and {1}: {2}", - firstTime, secondTime, - (TimeComparison) firstTime.CompareTo(secondTime)); - // The example displays the following output to the console: - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -07:00: Same - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -06:00: Later - // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 8:45:00 AM -05:00: Same - } + secondTime = new(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("Comparing {0} and {1}: {2}", + firstTime, secondTime, + (TimeComparison)firstTime.CompareTo(secondTime)); + // The example displays the following output to the console: + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -07:00: Same + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 6:45:00 AM -06:00: Later + // Comparing 9/1/2007 6:45:00 AM -07:00 and 9/1/2007 8:45:00 AM -05:00: Same + } } // diff --git a/snippets/csharp/System/DateTimeOffset/Compare/Syntax.cs b/snippets/csharp/System/DateTimeOffset/Compare/Syntax.cs index 94b9b8e4672..f60fabc0f2a 100644 --- a/snippets/csharp/System/DateTimeOffset/Compare/Syntax.cs +++ b/snippets/csharp/System/DateTimeOffset/Compare/Syntax.cs @@ -2,80 +2,74 @@ public class Class1 { - private static DateTimeOffset dto; + private static DateTimeOffset dto; - public Class1() - { - dto = DateTimeOffset.Now; - } + public Class1() => dto = DateTimeOffset.Now; - public DateTime UtcDateTime - { - get { return dto.UtcDateTime; } - } + public DateTime UtcDateTime => dto.UtcDateTime; - public static void Main() - { - int retVal; - DateTime now = DateTime.Now; - retVal = Comparison(now, - new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, new TimeSpan(-4, 0, 0))); - Class1 thisInst = new Class1(); - Console.WriteLine(retVal); - Console.WriteLine(thisInst.Equality(DateTimeOffset.Now)); - Console.WriteLine(thisInst.Equality2(dto)); - Console.WriteLine(thisInst.Equality3()); - Console.WriteLine(thisInst.GreaterThan()); - } + public static void Main() + { + int retVal; + DateTime now = DateTime.Now; + retVal = Comparison(now, + new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, new TimeSpan(-4, 0, 0))); + Class1 thisInst = new(); + Console.WriteLine(retVal); + Console.WriteLine(thisInst.Equality(DateTimeOffset.Now)); + Console.WriteLine(thisInst.Equality2(dto)); + Console.WriteLine(thisInst.Equality3()); + Console.WriteLine(thisInst.GreaterThan()); + } - private static int Comparison(DateTimeOffset first, DateTimeOffset second) - { - // - return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); - // - } + private static int Comparison(DateTimeOffset first, DateTimeOffset second) + { + // + return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); + // + } - private bool Equality(DateTimeOffset other) - { - // - return this.UtcDateTime == other.UtcDateTime; - // - } + private bool Equality(DateTimeOffset other) + { + // + return this.UtcDateTime == other.UtcDateTime; + // + } - private bool Equality2(object obj) - { - // - return this.UtcDateTime == ((DateTimeOffset) obj).UtcDateTime; - // - } + private bool Equality2(object obj) + { + // + return this.UtcDateTime == ((DateTimeOffset)obj).UtcDateTime; + // + } - private bool Equality3() - { - DateTimeOffset first = DateTimeOffset.Now; - DateTimeOffset second = DateTimeOffset.Now; - // - return first.UtcDateTime == second.UtcDateTime; - // - } + private bool Equality3() + { + DateTimeOffset first = DateTimeOffset.Now; + DateTimeOffset second = DateTimeOffset.Now; + // + return first.UtcDateTime == second.UtcDateTime; + // + } - private bool GreaterThan() - { - DateTimeOffset right = DateTimeOffset.Now; - DateTimeOffset left = DateTimeOffset.Now; - // - return left.UtcDateTime > right.UtcDateTime; - // - // - return left.UtcDateTime >= right.UtcDateTime; - // - // - return left.UtcDateTime != right.UtcDateTime; - // - // - return left.UtcDateTime < right.UtcDateTime; - // - // - return left.UtcDateTime <= right.UtcDateTime; - // - } + private bool GreaterThan() + { + DateTimeOffset right = DateTimeOffset.Now; + DateTimeOffset left = DateTimeOffset.Now; + // + return left.UtcDateTime > right.UtcDateTime; + // + // + return left.UtcDateTime >= right.UtcDateTime; + // + // + return left.UtcDateTime != right.UtcDateTime; + // + // + return left.UtcDateTime < right.UtcDateTime; + // + // + return left.UtcDateTime <= right.UtcDateTime; + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/Date/Properties.cs b/snippets/csharp/System/DateTimeOffset/Date/Properties.cs index 802aec5370c..75ef1e0fd32 100644 --- a/snippets/csharp/System/DateTimeOffset/Date/Properties.cs +++ b/snippets/csharp/System/DateTimeOffset/Date/Properties.cs @@ -3,440 +3,400 @@ public class Class1 { - public static void Main() - { - ShowDateFormats(); - Console.WriteLine("----------"); - ConvertToDateTime(); - Console.WriteLine("----------"); - ShowFirstOfMonth(); - Console.WriteLine("----------"); - ShowHour(); - Console.WriteLine("----------"); - ConvertToLocalTime(); - Console.WriteLine("----------"); - ShowMinute(); - Console.WriteLine("----------"); - ShowMonth(); - Console.WriteLine("----------"); - ShowDay(); - Console.WriteLine("----------"); - ShowResolution(); - Console.WriteLine("----------"); - ShowMilliseconds(); - Console.WriteLine("----------"); - ShowLocalOffset(); - Console.WriteLine("----------"); - ShowSeconds(); - Console.WriteLine("----------"); - IllustrateTicks(); - Console.WriteLine("----------"); - ShowTime(); - Console.WriteLine("----------"); - ConvertToUtc(); - Console.WriteLine("----------"); - CompareUtcAndLocal(); - Console.WriteLine("----------"); - ShowYear(); - Console.WriteLine("----------"); - } - - private static void ShowDateFormats() - { - // - // Illustrate Date property and date formatting - DateTimeOffset thisDate = new DateTimeOffset(2008, 3, 17, 1, 32, 0, new TimeSpan(-5, 0, 0)); - string fmt; // format specifier - - // Display date only using "D" format specifier - // For en-us culture, displays: - // 'D' format specifier: Monday, March 17, 2008 - fmt = "D"; - Console.WriteLine("'{0}' format specifier: {1}", - fmt, thisDate.Date.ToString(fmt)); - - // Display date only using "d" format specifier - // For en-us culture, displays: - // 'd' format specifier: 3/17/2008 - fmt = "d"; - Console.WriteLine("'{0}' format specifier: {1}", - fmt, thisDate.Date.ToString(fmt)); - - // Display date only using "Y" (or "y") format specifier - // For en-us culture, displays: - // 'Y' format specifier: March, 2008 - fmt = "Y"; - Console.WriteLine("'{0}' format specifier: {1}", - fmt, thisDate.Date.ToString(fmt)); - - // Display date only using custom format specifier - // For en-us culture, displays: - // 'dd MMM yyyy' format specifier: 17 Mar 2008 - fmt = "dd MMM yyyy"; - Console.WriteLine("'{0}' format specifier: {1}", - fmt, thisDate.Date.ToString(fmt)); - // - } - - private static void ConvertToDateTime() - { - // - DateTimeOffset offsetDate; - DateTime regularDate; - - offsetDate = DateTimeOffset.Now; - regularDate = offsetDate.DateTime; - Console.WriteLine("{0} converts to {1}, Kind {2}.", - offsetDate.ToString(), - regularDate, - regularDate.Kind); - - offsetDate = DateTimeOffset.UtcNow; - regularDate = offsetDate.DateTime; - Console.WriteLine("{0} converts to {1}, Kind {2}.", - offsetDate.ToString(), - regularDate, - regularDate.Kind); - // If run on 3/6/2007 at 17:11, produces the following output: - // - // 3/6/2007 5:11:22 PM -08:00 converts to 3/6/2007 5:11:22 PM, Kind Unspecified. - // 3/7/2007 1:11:22 AM +00:00 converts to 3/7/2007 1:11:22 AM, Kind Unspecified. - // - } - - private static void ShowFirstOfMonth() - { - // - DateTimeOffset startOfMonth = new DateTimeOffset(2008, 1, 1, 0, 0, 0, + public static void Main() + { + ShowDateFormats(); + Console.WriteLine("----------"); + ConvertToDateTime(); + Console.WriteLine("----------"); + ShowFirstOfMonth(); + Console.WriteLine("----------"); + ShowHour(); + Console.WriteLine("----------"); + ConvertToLocalTime(); + Console.WriteLine("----------"); + ShowMinute(); + Console.WriteLine("----------"); + ShowMonth(); + Console.WriteLine("----------"); + ShowDay(); + Console.WriteLine("----------"); + ShowResolution(); + Console.WriteLine("----------"); + ShowMilliseconds(); + Console.WriteLine("----------"); + ShowLocalOffset(); + Console.WriteLine("----------"); + ShowSeconds(); + Console.WriteLine("----------"); + IllustrateTicks(); + Console.WriteLine("----------"); + ShowTime(); + Console.WriteLine("----------"); + ConvertToUtc(); + Console.WriteLine("----------"); + CompareUtcAndLocal(); + Console.WriteLine("----------"); + ShowYear(); + Console.WriteLine("----------"); + } + + private static void ShowDateFormats() + { + // + // Illustrate Date property and date formatting + DateTimeOffset thisDate = new(2008, 3, 17, 1, 32, 0, new TimeSpan(-5, 0, 0)); + string fmt; // format specifier + + // Display date only using "D" format specifier + // For en-us culture, displays: + // 'D' format specifier: Monday, March 17, 2008 + fmt = "D"; + Console.WriteLine($"'{fmt}' format specifier: {thisDate.Date.ToString(fmt)}"); + + // Display date only using "d" format specifier + // For en-us culture, displays: + // 'd' format specifier: 3/17/2008 + fmt = "d"; + Console.WriteLine($"'{fmt}' format specifier: {thisDate.Date.ToString(fmt)}"); + + // Display date only using "Y" (or "y") format specifier + // For en-us culture, displays: + // 'Y' format specifier: March, 2008 + fmt = "Y"; + Console.WriteLine($"'{fmt}' format specifier: {thisDate.Date.ToString(fmt)}"); + + // Display date only using custom format specifier + // For en-us culture, displays: + // 'dd MMM yyyy' format specifier: 17 Mar 2008 + fmt = "dd MMM yyyy"; + Console.WriteLine($"'{fmt}' format specifier: {thisDate.Date.ToString(fmt)}"); + // + } + + private static void ConvertToDateTime() + { + // + DateTimeOffset offsetDate; + DateTime regularDate; + + offsetDate = DateTimeOffset.Now; + regularDate = offsetDate.DateTime; + Console.WriteLine($"{offsetDate.ToString()} converts to {regularDate}, Kind {regularDate.Kind}."); + + offsetDate = DateTimeOffset.UtcNow; + regularDate = offsetDate.DateTime; + Console.WriteLine($"{offsetDate.ToString()} converts to {regularDate}, Kind {regularDate.Kind}."); + // If run on 3/6/2007 at 17:11, produces the following output: + // + // 3/6/2007 5:11:22 PM -08:00 converts to 3/6/2007 5:11:22 PM, Kind Unspecified. + // 3/7/2007 1:11:22 AM +00:00 converts to 3/7/2007 1:11:22 AM, Kind Unspecified. + // + } + + private static void ShowFirstOfMonth() + { + // + DateTimeOffset startOfMonth = new(2008, 1, 1, 0, 0, 0, + DateTimeOffset.Now.Offset); + int year = startOfMonth.Year; + do + { + Console.WriteLine($"{startOfMonth:MMM d, yyyy} is a {startOfMonth.DayOfWeek}."); + startOfMonth = startOfMonth.AddMonths(1); + } + while (startOfMonth.Year == year); + // This example writes the following output to the console: + // Jan 1, 2008 is a Tuesday. + // Feb 1, 2008 is a Friday. + // Mar 1, 2008 is a Saturday. + // Apr 1, 2008 is a Tuesday. + // May 1, 2008 is a Thursday. + // Jun 1, 2008 is a Sunday. + // Jul 1, 2008 is a Tuesday. + // Aug 1, 2008 is a Friday. + // Sep 1, 2008 is a Monday. + // Oct 1, 2008 is a Wednesday. + // Nov 1, 2008 is a Saturday. + // Dec 1, 2008 is a Monday. + // + + // + DateTimeOffset displayDate = new(2008, 1, 1, 13, 18, 00, + DateTimeOffset.Now.Offset); + Console.WriteLine($"{displayDate:D}"); // Output: Tuesday, January 01, 2008 + Console.WriteLine("{0:d} is a {0:dddd}.", + displayDate); // Output: 1/1/2008 is a Tuesday. + // + + // + DateTimeOffset thisDate = new(2007, 6, 1, 6, 15, 0, + DateTimeOffset.Now.Offset); + string weekdayName = thisDate.ToString("dddd", + new CultureInfo("fr-fr")); + Console.WriteLine(weekdayName); // Displays vendredi + // + } + + private static void ShowHour() + { + // + DateTimeOffset theTime = new(2008, 3, 1, 14, 15, 00, DateTimeOffset.Now.Offset); - int year = startOfMonth.Year; - do - { - Console.WriteLine("{0:MMM d, yyyy} is a {1}.", startOfMonth, startOfMonth.DayOfWeek); - startOfMonth = startOfMonth.AddMonths(1); - } - while (startOfMonth.Year == year); - // This example writes the following output to the console: - // Jan 1, 2008 is a Tuesday. - // Feb 1, 2008 is a Friday. - // Mar 1, 2008 is a Saturday. - // Apr 1, 2008 is a Tuesday. - // May 1, 2008 is a Thursday. - // Jun 1, 2008 is a Sunday. - // Jul 1, 2008 is a Tuesday. - // Aug 1, 2008 is a Friday. - // Sep 1, 2008 is a Monday. - // Oct 1, 2008 is a Wednesday. - // Nov 1, 2008 is a Saturday. - // Dec 1, 2008 is a Monday. - // - - // - DateTimeOffset displayDate = new DateTimeOffset(2008, 1, 1, 13, 18, 00, - DateTimeOffset.Now.Offset); - Console.WriteLine("{0:D}", displayDate); // Output: Tuesday, January 01, 2008 - Console.WriteLine("{0:d} is a {0:dddd}.", - displayDate); // Output: 1/1/2008 is a Tuesday. - // - - // - DateTimeOffset thisDate = new DateTimeOffset(2007, 6, 1, 6, 15, 0, + Console.WriteLine($"The hour component of {theTime} is {theTime.Hour}."); + + Console.WriteLine($"The hour component of {theTime} is{theTime.ToString(" H")}."); + + Console.WriteLine($"The hour component of {theTime} is {theTime.ToString("HH")}."); + // The example produces the following output: + // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. + // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. + // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. + // + } + + private static void ConvertToLocalTime() + { + // + DateTimeOffset dto; + + // Current time + dto = DateTimeOffset.Now; + Console.WriteLine(dto.LocalDateTime); + // UTC time + dto = DateTimeOffset.UtcNow; + Console.WriteLine(dto.LocalDateTime); + + // Transition to DST in local time zone occurs on 3/11/2007 at 2:00 AM + dto = new(2007, 3, 11, 3, 30, 0, new TimeSpan(-7, 0, 0)); + Console.WriteLine(dto.LocalDateTime); + dto = new(2007, 3, 11, 2, 30, 0, new TimeSpan(-7, 0, 0)); + Console.WriteLine(dto.LocalDateTime); + // Invalid time in local time zone + dto = new(2007, 3, 11, 2, 30, 0, new TimeSpan(-8, 0, 0)); + Console.WriteLine(TimeZoneInfo.Local.IsInvalidTime(dto.DateTime)); + Console.WriteLine(dto.LocalDateTime); + + // Transition from DST in local time zone occurs on 11/4/07 at 2:00 AM + // This is an ambiguous time + dto = new(2007, 11, 4, 1, 30, 0, new TimeSpan(-7, 0, 0)); + Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); + Console.WriteLine(dto.LocalDateTime); + dto = new(2007, 11, 4, 2, 30, 0, new TimeSpan(-7, 0, 0)); + Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); + Console.WriteLine(dto.LocalDateTime); + // This is also an ambiguous time + dto = new(2007, 11, 4, 1, 30, 0, new TimeSpan(-8, 0, 0)); + Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); + Console.WriteLine(dto.LocalDateTime); + // If run on 3/8/2007 at 4:56 PM, the code produces the following + // output: + // 3/8/2007 4:56:03 PM + // 3/8/2007 4:56:03 PM + // 3/11/2007 3:30:00 AM + // 3/11/2007 1:30:00 AM + // True + // 3/11/2007 3:30:00 AM + // True + // 11/4/2007 1:30:00 AM + // 11/4/2007 1:30:00 AM + // True + // 11/4/2007 1:30:00 AM + // + } + + private static void ShowMinute() + { + // + DateTimeOffset theTime = new(2008, 5, 1, 10, 3, 0, DateTimeOffset.Now.Offset); - string weekdayName = thisDate.ToString("dddd", - new CultureInfo("fr-fr")); - Console.WriteLine(weekdayName); // Displays vendredi - // - } - - private static void ShowHour() - { - // - DateTimeOffset theTime = new DateTimeOffset(2008, 3, 1, 14, 15, 00, - DateTimeOffset.Now.Offset); - Console.WriteLine("The hour component of {0} is {1}.", - theTime, theTime.Hour); - - Console.WriteLine("The hour component of {0} is{1}.", - theTime, theTime.ToString(" H")); - - Console.WriteLine("The hour component of {0} is {1}.", - theTime, theTime.ToString("HH")); - // The example produces the following output: - // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. - // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. - // The hour component of 3/1/2008 2:15:00 PM -08:00 is 14. - // - } - - private static void ConvertToLocalTime() - { - // - DateTimeOffset dto; - - // Current time - dto = DateTimeOffset.Now; - Console.WriteLine(dto.LocalDateTime); - // UTC time - dto = DateTimeOffset.UtcNow; - Console.WriteLine(dto.LocalDateTime); - - // Transition to DST in local time zone occurs on 3/11/2007 at 2:00 AM - dto = new DateTimeOffset(2007, 3, 11, 3, 30, 0, new TimeSpan(-7, 0, 0)); - Console.WriteLine(dto.LocalDateTime); - dto = new DateTimeOffset(2007, 3, 11, 2, 30, 0, new TimeSpan(-7, 0, 0)); - Console.WriteLine(dto.LocalDateTime); - // Invalid time in local time zone - dto = new DateTimeOffset(2007, 3, 11, 2, 30, 0, new TimeSpan(-8, 0, 0)); - Console.WriteLine(TimeZoneInfo.Local.IsInvalidTime(dto.DateTime)); - Console.WriteLine(dto.LocalDateTime); - - // Transition from DST in local time zone occurs on 11/4/07 at 2:00 AM - // This is an ambiguous time - dto = new DateTimeOffset(2007, 11, 4, 1, 30, 0, new TimeSpan(-7, 0, 0)); - Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); - Console.WriteLine(dto.LocalDateTime); - dto = new DateTimeOffset(2007, 11, 4, 2, 30, 0, new TimeSpan(-7, 0, 0)); - Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); - Console.WriteLine(dto.LocalDateTime); - // This is also an ambiguous time - dto = new DateTimeOffset(2007, 11, 4, 1, 30, 0, new TimeSpan(-8, 0, 0)); - Console.WriteLine(TimeZoneInfo.Local.IsAmbiguousTime(dto)); - Console.WriteLine(dto.LocalDateTime); - // If run on 3/8/2007 at 4:56 PM, the code produces the following - // output: - // 3/8/2007 4:56:03 PM - // 3/8/2007 4:56:03 PM - // 3/11/2007 3:30:00 AM - // 3/11/2007 1:30:00 AM - // True - // 3/11/2007 3:30:00 AM - // True - // 11/4/2007 1:30:00 AM - // 11/4/2007 1:30:00 AM - // True - // 11/4/2007 1:30:00 AM - // - } - - private static void ShowMinute() - { - // - DateTimeOffset theTime = new DateTimeOffset(2008, 5, 1, 10, 3, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("The minute component of {0} is {1}.", - theTime, theTime.Minute); + Console.WriteLine($"The minute component of {theTime} is {theTime.Minute}."); - Console.WriteLine("The minute component of {0} is{1}.", - theTime, theTime.ToString(" m")); + Console.WriteLine($"The minute component of {theTime} is{theTime.ToString(" m")}."); - Console.WriteLine("The minute component of {0} is {1}.", - theTime, theTime.ToString("mm")); - // The example produces the following output: - // The minute component of 5/1/2008 10:03:00 AM -08:00 is 3. - // The minute component of 5/1/2008 10:03:00 AM -08:00 is 3. - // The minute component of 5/1/2008 10:03:00 AM -08:00 is 03. - // - } + Console.WriteLine($"The minute component of {theTime} is {theTime.ToString("mm")}."); + // The example produces the following output: + // The minute component of 5/1/2008 10:03:00 AM -08:00 is 3. + // The minute component of 5/1/2008 10:03:00 AM -08:00 is 3. + // The minute component of 5/1/2008 10:03:00 AM -08:00 is 03. + // + } private static void ShowMonth() { - // - DateTimeOffset theTime = new DateTimeOffset(2008, 9, 7, 11, 25, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("The month component of {0} is {1}.", - theTime, theTime.Month); - - Console.WriteLine("The month component of {0} is{1}.", - theTime, theTime.ToString(" M")); - - Console.WriteLine("The month component of {0} is {1}.", - theTime, theTime.ToString("MM")); - // The example produces the following output: - // The month component of 9/7/2008 11:25:00 AM -08:00 is 9. - // The month component of 9/7/2008 11:25:00 AM -08:00 is 9. - // The month component of 9/7/2008 11:25:00 AM -08:00 is 09. - // - } + // + DateTimeOffset theTime = new(2008, 9, 7, 11, 25, 0, + DateTimeOffset.Now.Offset); + Console.WriteLine($"The month component of {theTime} is {theTime.Month}."); + + Console.WriteLine($"The month component of {theTime} is{theTime.ToString(" M")}."); + + Console.WriteLine($"The month component of {theTime} is {theTime.ToString("MM")}."); + // The example produces the following output: + // The month component of 9/7/2008 11:25:00 AM -08:00 is 9. + // The month component of 9/7/2008 11:25:00 AM -08:00 is 9. + // The month component of 9/7/2008 11:25:00 AM -08:00 is 09. + // + } private static void ShowDay() { - // - DateTimeOffset theTime = new DateTimeOffset(2007, 5, 1, 16, 35, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("The day component of {0} is {1}.", - theTime, theTime.Day); - - Console.WriteLine("The day component of {0} is{1}.", - theTime, theTime.ToString(" d")); - - Console.WriteLine("The day component of {0} is {1}.", - theTime, theTime.ToString("dd")); - // The example produces the following output: - // The day component of 5/1/2007 4:35:00 PM -08:00 is 1. - // The day component of 5/1/2007 4:35:00 PM -08:00 is 1. - // The day component of 5/1/2007 4:35:00 PM -08:00 is 01. - // - } - - private static void ShowResolution() - { - // - DateTimeOffset dto; - int ctr = 0; - int ms = 0; - do { - dto = DateTimeOffset.Now; - if (dto.Millisecond != ms) - { - ms = dto.Millisecond; - Console.WriteLine("{0}:{1:d3} ms. {2}", - dto.ToString("M/d/yyyy h:mm:ss"), - ms, dto.ToString("zzz")); - ctr++; - } - } while (ctr < 100); - // - } - - private static void ShowMilliseconds() - { - // - DateTimeOffset date1 = new DateTimeOffset(2008, 3, 5, 5, 45, 35, 649, - new TimeSpan(-7, 0, 0)); - Console.WriteLine("Milliseconds value of {0} is {1}.", - date1.ToString("MM/dd/yyyy hh:mm:ss.fff"), - date1.Millisecond); - // The example produces the following output: - // - // Milliseconds value of 03/05/2008 05:45:35.649 is 649. - // - } - - private static void ShowLocalOffset() - { - // - DateTimeOffset localTime = DateTimeOffset.Now; - Console.WriteLine("The local time zone is {0} hours and {1} minutes {2} than UTC.", - Math.Abs(localTime.Offset.Hours), - localTime.Offset.Minutes, - localTime.Offset.Hours < 0 ? "earlier" : "later"); - // The example displays output similar to the following for a system in the - // U.S. Pacific Standard Time zone: - // The local time zone is 8 hours and 0 minutes earlier than UTC. - // - } - - private static void ShowSeconds() - { - // - DateTimeOffset theTime = new DateTimeOffset(2008, 6, 12, 21, 16, 32, - DateTimeOffset.Now.Offset); - Console.WriteLine("The second component of {0} is {1}.", - theTime, theTime.Second); - - Console.WriteLine("The second component of {0} is{1}.", - theTime, theTime.ToString(" s")); - - Console.WriteLine("The second component of {0} is {1}.", - theTime, theTime.ToString("ss")); - // The example produces the following output: - // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. - // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. - // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. - // - } - - private static void IllustrateTicks() - { - // - // Attempt to initialize date to number of ticks - // in July 1, 2008 1:23:07. - // - // There are 10,000,000 100-nanosecond intervals in a second - const long NSPerSecond = 10000000; - long ticks; - ticks = 7 * NSPerSecond; // Ticks in a 7 seconds - ticks += 23 * 60 * NSPerSecond; // Ticks in 23 minutes - ticks += 1 * 60 * 60 * NSPerSecond; // Ticks in 1 hour - ticks += 60 * 60 * 24 * NSPerSecond; // Ticks in 1 day - ticks += 181 * 60 * 60 * 24 * NSPerSecond; // Ticks in 6 months - ticks += 2007 * 60 * 60 * 24 * 365L * NSPerSecond; // Ticks in 2007 years - ticks += 486 * 60 * 60 * 24 * NSPerSecond; // Adjustment for leap years - DateTimeOffset dto = new DateTimeOffset( - ticks, - DateTimeOffset.Now.Offset); - Console.WriteLine("There are {0:n0} ticks in {1}.", - dto.Ticks, - dto.ToString()); - // The example displays the following output: - // There are 633,504,721,870,000,000 ticks in 7/1/2008 1:23:07 AM -08:00. - // - } - - private static void ShowTime() - { - // - DateTimeOffset currentDate = new DateTimeOffset(2008, 5, 10, 5, 32, 16, - DateTimeOffset.Now.Offset); - TimeSpan currentTime = currentDate.TimeOfDay; - Console.WriteLine("The current time is {0}.", currentTime.ToString()); - // The example produces the following output: - // The current time is 05:32:16. - // - } - - private static void ConvertToUtc() - { - // - DateTimeOffset offsetTime = new DateTimeOffset(2007, 11, 25, 11, 14, 00, - new TimeSpan(3, 0, 0)); - Console.WriteLine("{0} is equivalent to {1} {2}", - offsetTime.ToString(), - offsetTime.UtcDateTime.ToString(), - offsetTime.UtcDateTime.Kind.ToString()); - // The example displays the following output: - // 11/25/2007 11:14:00 AM +03:00 is equivalent to 11/25/2007 8:14:00 AM Utc - // - } - - private static void CompareUtcAndLocal() - { - // - DateTimeOffset localTime = DateTimeOffset.Now; - DateTimeOffset utcTime = DateTimeOffset.UtcNow; - - Console.WriteLine("Local Time: {0}", localTime.ToString("T")); - Console.WriteLine("Difference from UTC: {0}", localTime.Offset.ToString()); - Console.WriteLine("UTC: {0}", utcTime.ToString("T")); - // If run on a particular date at 1:19 PM, the example produces - // the following output: - // Local Time: 1:19:43 PM - // Difference from UTC: -07:00:00 - // UTC: 8:19:43 PM - // - } - - private static void ShowYear() - { - // - DateTimeOffset theTime = new DateTimeOffset(2008, 2, 17, 9, 0, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("The year component of {0} is {1}.", - theTime, theTime.Year); - - Console.WriteLine("The year component of {0} is{1}.", - theTime, theTime.ToString(" y")); - - Console.WriteLine("The year component of {0} is {1}.", - theTime, theTime.ToString("yy")); - - Console.WriteLine("The year component of {0} is {1}.", - theTime, theTime.ToString("yyyy")); - // The example produces the following output: - // The year component of 2/17/2008 9:00:00 AM -07:00 is 2008. - // The year component of 2/17/2008 9:00:00 AM -07:00 is 8. - // The year component of 2/17/2008 9:00:00 AM -07:00 is 08. - // The year component of 2/17/2008 9:00:00 AM -07:00 is 2008. - // - } + // + DateTimeOffset theTime = new(2007, 5, 1, 16, 35, 0, + DateTimeOffset.Now.Offset); + Console.WriteLine($"The day component of {theTime} is {theTime.Day}."); + + Console.WriteLine($"The day component of {theTime} is{theTime.ToString(" d")}."); + + Console.WriteLine($"The day component of {theTime} is {theTime.ToString("dd")}."); + // The example produces the following output: + // The day component of 5/1/2007 4:35:00 PM -08:00 is 1. + // The day component of 5/1/2007 4:35:00 PM -08:00 is 1. + // The day component of 5/1/2007 4:35:00 PM -08:00 is 01. + // + } + + private static void ShowResolution() + { + // + DateTimeOffset dto; + int ctr = 0; + int ms = 0; + do + { + dto = DateTimeOffset.Now; + if (dto.Millisecond != ms) + { + ms = dto.Millisecond; + Console.WriteLine($"{dto.ToString("M/d/yyyy h:mm:ss")}:{ms:d3} ms. {dto.ToString("zzz")}"); + ctr++; + } + } while (ctr < 100); + // + } + + private static void ShowMilliseconds() + { + // + DateTimeOffset date1 = new(2008, 3, 5, 5, 45, 35, 649, + new TimeSpan(-7, 0, 0)); + Console.WriteLine($"Milliseconds value of {date1.ToString("MM/dd/yyyy hh:mm:ss.fff")} is {date1.Millisecond}."); + // The example produces the following output: + // + // Milliseconds value of 03/05/2008 05:45:35.649 is 649. + // + } + + private static void ShowLocalOffset() + { + // + DateTimeOffset localTime = DateTimeOffset.Now; + Console.WriteLine($"The local time zone is {Math.Abs(localTime.Offset.Hours)} hours and {localTime.Offset.Minutes} minutes {(localTime.Offset.Hours < 0 ? "earlier" : "later")} than UTC."); + // The example displays output similar to the following for a system in the + // U.S. Pacific Standard Time zone: + // The local time zone is 8 hours and 0 minutes earlier than UTC. + // + } + + private static void ShowSeconds() + { + // + DateTimeOffset theTime = new(2008, 6, 12, 21, 16, 32, + DateTimeOffset.Now.Offset); + Console.WriteLine($"The second component of {theTime} is {theTime.Second}."); + + Console.WriteLine($"The second component of {theTime} is{theTime.ToString(" s")}."); + + Console.WriteLine($"The second component of {theTime} is {theTime.ToString("ss")}."); + // The example produces the following output: + // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. + // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. + // The second component of 6/12/2008 9:16:32 PM -07:00 is 32. + // + } + + private static void IllustrateTicks() + { + // + // Attempt to initialize date to number of ticks + // in July 1, 2008 1:23:07. + // + // There are 10,000,000 100-nanosecond intervals in a second + const long NSPerSecond = 10000000; + long ticks; + ticks = 7 * NSPerSecond; // Ticks in a 7 seconds + ticks += 23 * 60 * NSPerSecond; // Ticks in 23 minutes + ticks += 1 * 60 * 60 * NSPerSecond; // Ticks in 1 hour + ticks += 60 * 60 * 24 * NSPerSecond; // Ticks in 1 day + ticks += 181 * 60 * 60 * 24 * NSPerSecond; // Ticks in 6 months + ticks += 2007 * 60 * 60 * 24 * 365L * NSPerSecond; // Ticks in 2007 years + ticks += 486 * 60 * 60 * 24 * NSPerSecond; // Adjustment for leap years + DateTimeOffset dto = new( + ticks, + DateTimeOffset.Now.Offset); + Console.WriteLine($"There are {dto.Ticks:n0} ticks in {dto.ToString()}."); + // The example displays the following output: + // There are 633,504,721,870,000,000 ticks in 7/1/2008 1:23:07 AM -08:00. + // + } + + private static void ShowTime() + { + // + DateTimeOffset currentDate = new(2008, 5, 10, 5, 32, 16, + DateTimeOffset.Now.Offset); + TimeSpan currentTime = currentDate.TimeOfDay; + Console.WriteLine($"The current time is {currentTime.ToString()}."); + // The example produces the following output: + // The current time is 05:32:16. + // + } + + private static void ConvertToUtc() + { + // + DateTimeOffset offsetTime = new(2007, 11, 25, 11, 14, 00, + new TimeSpan(3, 0, 0)); + Console.WriteLine($"{offsetTime.ToString()} is equivalent to {offsetTime.UtcDateTime.ToString()} {offsetTime.UtcDateTime.Kind.ToString()}"); + // The example displays the following output: + // 11/25/2007 11:14:00 AM +03:00 is equivalent to 11/25/2007 8:14:00 AM Utc + // + } + + private static void CompareUtcAndLocal() + { + // + DateTimeOffset localTime = DateTimeOffset.Now; + DateTimeOffset utcTime = DateTimeOffset.UtcNow; + + Console.WriteLine($"Local Time: {localTime.ToString("T")}"); + Console.WriteLine($"Difference from UTC: {localTime.Offset.ToString()}"); + Console.WriteLine($"UTC: {utcTime.ToString("T")}"); + // If run on a particular date at 1:19 PM, the example produces + // the following output: + // Local Time: 1:19:43 PM + // Difference from UTC: -07:00:00 + // UTC: 8:19:43 PM + // + } + + private static void ShowYear() + { + // + DateTimeOffset theTime = new(2008, 2, 17, 9, 0, 0, + DateTimeOffset.Now.Offset); + Console.WriteLine($"The year component of {theTime} is {theTime.Year}."); + + Console.WriteLine($"The year component of {theTime} is{theTime.ToString(" y")}."); + + Console.WriteLine($"The year component of {theTime} is {theTime.ToString("yy")}."); + + Console.WriteLine($"The year component of {theTime} is {theTime.ToString("yyyy")}."); + // The example produces the following output: + // The year component of 2/17/2008 9:00:00 AM -07:00 is 2008. + // The year component of 2/17/2008 9:00:00 AM -07:00 is 8. + // The year component of 2/17/2008 9:00:00 AM -07:00 is 08. + // The year component of 2/17/2008 9:00:00 AM -07:00 is 2008. + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/FromFileTime/FileTime.cs b/snippets/csharp/System/DateTimeOffset/FromFileTime/FileTime.cs index 664be3058f5..6b8126dc794 100644 --- a/snippets/csharp/System/DateTimeOffset/FromFileTime/FileTime.cs +++ b/snippets/csharp/System/DateTimeOffset/FromFileTime/FileTime.cs @@ -5,105 +5,105 @@ public struct FileTime { - public uint dwLowDateTime; - public uint dwHighDateTime; + public uint dwLowDateTime; + public uint dwHighDateTime; - public static implicit operator long(FileTime fileTime) - { - long returnedLong; - // Convert 4 high-order bytes to a byte array - byte[] highBytes = BitConverter.GetBytes(fileTime.dwHighDateTime); - // Resize the array to 8 bytes (for a Long) - Array.Resize(ref highBytes, 8); + public static implicit operator long(FileTime fileTime) + { + long returnedLong; + // Convert 4 high-order bytes to a byte array + byte[] highBytes = BitConverter.GetBytes(fileTime.dwHighDateTime); + // Resize the array to 8 bytes (for a Long) + Array.Resize(ref highBytes, 8); - // Assign high-order bytes to first 4 bytes of Long - returnedLong = BitConverter.ToInt64(highBytes, 0); - // Shift high-order bytes into position - returnedLong = returnedLong << 32; - // Or with low-order bytes - returnedLong = returnedLong | fileTime.dwLowDateTime; - // Return long - return returnedLong; - } + // Assign high-order bytes to first 4 bytes of Long + returnedLong = BitConverter.ToInt64(highBytes, 0); + // Shift high-order bytes into position + returnedLong = returnedLong << 32; + // Or with low-order bytes + returnedLong = returnedLong | fileTime.dwLowDateTime; + // Return long + return returnedLong; + } } public class FileTimes { - private const int OPEN_EXISTING = 3; - private const int INVALID_HANDLE_VALUE = -1; + private const int OPEN_EXISTING = 3; + private const int INVALID_HANDLE_VALUE = -1; - [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] - private static extern int CreateFile(string lpFileName, - int dwDesiredAccess, - int dwShareMode, - int lpSecurityAttributes, - int dwCreationDisposition, - int dwFlagsAndAttributes, - int hTemplateFile); + [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] + private static extern int CreateFile(string lpFileName, + int dwDesiredAccess, + int dwShareMode, + int lpSecurityAttributes, + int dwCreationDisposition, + int dwFlagsAndAttributes, + int hTemplateFile); - [DllImport("Kernel32.dll")] - private static extern bool GetFileTime(int hFile, - out FileTime lpCreationTime, - out FileTime lpLastAccessTime, - out FileTime lpLastWriteTime); + [DllImport("Kernel32.dll")] + private static extern bool GetFileTime(int hFile, + out FileTime lpCreationTime, + out FileTime lpLastAccessTime, + out FileTime lpLastWriteTime); - [DllImport("Kernel32.dll")] - private static extern bool CloseHandle(int hFile); + [DllImport("Kernel32.dll")] + private static extern bool CloseHandle(int hFile); - public static void Main() - { - // Open file %windir%\write.exe - string winDir = Environment.SystemDirectory; - if (!(winDir.EndsWith(Path.DirectorySeparatorChar.ToString()))) - winDir += Path.DirectorySeparatorChar; - winDir += "write.exe"; + public static void Main() + { + // Open file %windir%\write.exe + string winDir = Environment.SystemDirectory; + if (!(winDir.EndsWith(Path.DirectorySeparatorChar.ToString()))) + winDir += Path.DirectorySeparatorChar; + winDir += "write.exe"; - // Get file time using Windows API - // - // Open file - int hFile = CreateFile(winDir, 0, 0, 0, OPEN_EXISTING, 0, 0); - if (hFile == INVALID_HANDLE_VALUE) - { - Console.WriteLine("Unable to access {0}.", winDir); - } - else - { - FileTime creationTime, accessTime, writeTime; - if (GetFileTime(hFile, out creationTime, out accessTime, out writeTime)) - { - CloseHandle(hFile); - long fileCreationTime = (long) creationTime; - long fileAccessTime = accessTime; - long fileWriteTime = (long) writeTime; + // Get file time using Windows API + // + // Open file + int hFile = CreateFile(winDir, 0, 0, 0, OPEN_EXISTING, 0, 0); + if (hFile == INVALID_HANDLE_VALUE) + { + Console.WriteLine($"Unable to access {winDir}."); + } + else + { + FileTime creationTime, accessTime, writeTime; + if (GetFileTime(hFile, out creationTime, out accessTime, out writeTime)) + { + CloseHandle(hFile); + long fileCreationTime = (long)creationTime; + long fileAccessTime = accessTime; + long fileWriteTime = (long)writeTime; - Console.WriteLine("File {0} Retrieved Using the Windows API:", winDir); - Console.WriteLine(" Created: {0:d}", DateTimeOffset.FromFileTime(fileCreationTime).ToString()); - Console.WriteLine(" Last Access: {0:d}", DateTimeOffset.FromFileTime(fileAccessTime).ToString()); - Console.WriteLine(" Last Write: {0:d}", DateTimeOffset.FromFileTime(fileWriteTime).ToString()); - Console.WriteLine(); - } - } + Console.WriteLine($"File {winDir} Retrieved Using the Windows API:"); + Console.WriteLine($" Created: {DateTimeOffset.FromFileTime(fileCreationTime).ToString():d}"); + Console.WriteLine($" Last Access: {DateTimeOffset.FromFileTime(fileAccessTime).ToString():d}"); + Console.WriteLine($" Last Write: {DateTimeOffset.FromFileTime(fileWriteTime).ToString():d}"); + Console.WriteLine(); + } + } - // Get date and time, convert to file time, then convert back - FileInfo fileInfo = new FileInfo(winDir); - DateTimeOffset infoCreationTime, infoAccessTime, infoWriteTime; - long ftCreationTime, ftAccessTime, ftWriteTime; + // Get date and time, convert to file time, then convert back + FileInfo fileInfo = new(winDir); + DateTimeOffset infoCreationTime, infoAccessTime, infoWriteTime; + long ftCreationTime, ftAccessTime, ftWriteTime; - // Get dates and times of file creation, last access, and last write - infoCreationTime = fileInfo.CreationTime; - infoAccessTime = fileInfo.LastAccessTime; - infoWriteTime = fileInfo.LastWriteTime; - // Convert values to file times - ftCreationTime = infoCreationTime.ToFileTime(); - ftAccessTime = infoAccessTime.ToFileTime(); - ftWriteTime = infoWriteTime.ToFileTime(); + // Get dates and times of file creation, last access, and last write + infoCreationTime = fileInfo.CreationTime; + infoAccessTime = fileInfo.LastAccessTime; + infoWriteTime = fileInfo.LastWriteTime; + // Convert values to file times + ftCreationTime = infoCreationTime.ToFileTime(); + ftAccessTime = infoAccessTime.ToFileTime(); + ftWriteTime = infoWriteTime.ToFileTime(); - // Convert file times back to DateTimeOffset values - Console.WriteLine("File {0} Retrieved Using a FileInfo Object:", winDir); - Console.WriteLine(" Created: {0:d}", DateTimeOffset.FromFileTime(ftCreationTime).ToString()); - Console.WriteLine(" Last Access: {0:d}", DateTimeOffset.FromFileTime(ftAccessTime).ToString()); - Console.WriteLine(" Last Write: {0:d}", DateTimeOffset.FromFileTime(ftWriteTime).ToString()); - } + // Convert file times back to DateTimeOffset values + Console.WriteLine($"File {winDir} Retrieved Using a FileInfo Object:"); + Console.WriteLine($" Created: {DateTimeOffset.FromFileTime(ftCreationTime).ToString():d}"); + Console.WriteLine($" Last Access: {DateTimeOffset.FromFileTime(ftAccessTime).ToString():d}"); + Console.WriteLine($" Last Write: {DateTimeOffset.FromFileTime(ftWriteTime).ToString():d}"); + } } // The example produces the following output: // File C:\WINDOWS\system32\write.exe Retrieved Using the Windows API: diff --git a/snippets/csharp/System/DateTimeOffset/Now/now1.cs b/snippets/csharp/System/DateTimeOffset/Now/now1.cs index ddeee70da1b..ddfaf365bf0 100644 --- a/snippets/csharp/System/DateTimeOffset/Now/now1.cs +++ b/snippets/csharp/System/DateTimeOffset/Now/now1.cs @@ -3,21 +3,20 @@ public class Example { - public static void Main() - { - String[] fmtStrings = { "d", "D", "f", "F", "g", "G", "M", + public static void Main() + { + string[] fmtStrings = { "d", "D", "f", "F", "g", "G", "M", "R", "s", "t", "T", "u", "y" }; - DateTimeOffset value = DateTimeOffset.Now; - // Display date in default format. - Console.WriteLine(value); - Console.WriteLine(); + DateTimeOffset value = DateTimeOffset.Now; + // Display date in default format. + Console.WriteLine(value); + Console.WriteLine(); - // Display date using each of the specified formats. - foreach (var fmtString in fmtStrings) - Console.WriteLine("{0} --> {1}", - fmtString, value.ToString(fmtString)); - } + // Display date using each of the specified formats. + foreach (string fmtString in fmtStrings) + Console.WriteLine($"{fmtString} --> {value.ToString(fmtString)}"); + } } // The example displays output similar to the following: // 11/19/2012 10:57:11 AM -08:00 @@ -35,4 +34,4 @@ public static void Main() // T --> 10:57:11 AM // u --> 2012-11-19 18:57:11Z // y --> November, 2012 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DateTimeOffset/Overview/Type.cs b/snippets/csharp/System/DateTimeOffset/Overview/Type.cs index 8dd78a8128f..f62e1ad47cd 100644 --- a/snippets/csharp/System/DateTimeOffset/Overview/Type.cs +++ b/snippets/csharp/System/DateTimeOffset/Overview/Type.cs @@ -3,28 +3,27 @@ public class DateArithmetic { - public static void Main() - { - DateTime date1, date2; - DateTimeOffset dateOffset1, dateOffset2; - TimeSpan difference; + public static void Main() + { + DateTime date1, date2; + DateTimeOffset dateOffset1, dateOffset2; + TimeSpan difference; - // Find difference between Date.Now and Date.UtcNow - date1 = DateTime.Now; - date2 = DateTime.UtcNow; - difference = date1 - date2; - Console.WriteLine("{0} - {1} = {2}", date1, date2, difference); + // Find difference between Date.Now and Date.UtcNow + date1 = DateTime.Now; + date2 = DateTime.UtcNow; + difference = date1 - date2; + Console.WriteLine($"{date1} - {date2} = {difference}"); - // Find difference between Now and UtcNow using DateTimeOffset - dateOffset1 = DateTimeOffset.Now; - dateOffset2 = DateTimeOffset.UtcNow; - difference = dateOffset1 - dateOffset2; - Console.WriteLine("{0} - {1} = {2}", - dateOffset1, dateOffset2, difference); - // If run in the Pacific Standard time zone on 4/2/2007, the example - // displays the following output to the console: - // 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00 - // 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00 - } + // Find difference between Now and UtcNow using DateTimeOffset + dateOffset1 = DateTimeOffset.Now; + dateOffset2 = DateTimeOffset.UtcNow; + difference = dateOffset1 - dateOffset2; + Console.WriteLine($"{dateOffset1} - {dateOffset2} = {difference}"); + // If run in the Pacific Standard time zone on 4/2/2007, the example + // displays the following output to the console: + // 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00 + // 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00 + } } // diff --git a/snippets/csharp/System/DateTimeOffset/Parse/ParseExamples.cs b/snippets/csharp/System/DateTimeOffset/Parse/ParseExamples.cs index 3b2dd58dd2a..dad1d689ed9 100644 --- a/snippets/csharp/System/DateTimeOffset/Parse/ParseExamples.cs +++ b/snippets/csharp/System/DateTimeOffset/Parse/ParseExamples.cs @@ -3,91 +3,85 @@ public class Class1 { - public static void Main() - { - ParseOverload1(); - ParseOverload2(); - ParseOverload3(); - } + public static void Main() + { + ParseOverload1(); + ParseOverload2(); + ParseOverload3(); + } - private static void ParseOverload1() - { - // - string dateString; - DateTimeOffset offsetDate; + private static void ParseOverload1() + { + // + string dateString; + DateTimeOffset offsetDate; - // String with date only - dateString = "05/01/2008"; - offsetDate = DateTimeOffset.Parse(dateString); - Console.WriteLine(offsetDate.ToString()); + // String with date only + dateString = "05/01/2008"; + offsetDate = DateTimeOffset.Parse(dateString); + Console.WriteLine(offsetDate.ToString()); - // String with time only - dateString = "11:36 PM"; - offsetDate = DateTimeOffset.Parse(dateString); - Console.WriteLine(offsetDate.ToString()); + // String with time only + dateString = "11:36 PM"; + offsetDate = DateTimeOffset.Parse(dateString); + Console.WriteLine(offsetDate.ToString()); - // String with date and offset - dateString = "05/01/2008 +1:00"; - offsetDate = DateTimeOffset.Parse(dateString); - Console.WriteLine(offsetDate.ToString()); + // String with date and offset + dateString = "05/01/2008 +1:00"; + offsetDate = DateTimeOffset.Parse(dateString); + Console.WriteLine(offsetDate.ToString()); - // String with day abbreviation - dateString = "Thu May 01, 2008"; - offsetDate = DateTimeOffset.Parse(dateString); - Console.WriteLine(offsetDate.ToString()); - // - } + // String with day abbreviation + dateString = "Thu May 01, 2008"; + offsetDate = DateTimeOffset.Parse(dateString); + Console.WriteLine(offsetDate.ToString()); + // + } - private static void ParseOverload2() - { - // - DateTimeFormatInfo fmt = new CultureInfo("fr-fr").DateTimeFormat; - string dateString; - DateTimeOffset offsetDate; + private static void ParseOverload2() + { + // + DateTimeFormatInfo fmt = new CultureInfo("fr-fr").DateTimeFormat; + string dateString; + DateTimeOffset offsetDate; - dateString = "03-12-07"; - offsetDate = DateTimeOffset.Parse(dateString, fmt); - Console.WriteLine("{0} returns {1}", - dateString, - offsetDate.ToString()); + dateString = "03-12-07"; + offsetDate = DateTimeOffset.Parse(dateString, fmt); + Console.WriteLine($"{dateString} returns {offsetDate.ToString()}"); - dateString = "15/09/07 08:45:00 +1:00"; - offsetDate = DateTimeOffset.Parse(dateString, fmt); - Console.WriteLine("{0} returns {1}", - dateString, - offsetDate.ToString()); + dateString = "15/09/07 08:45:00 +1:00"; + offsetDate = DateTimeOffset.Parse(dateString, fmt); + Console.WriteLine($"{dateString} returns {offsetDate.ToString()}"); - dateString = "mar. 1 janvier 2008 1:00:00 +1:00"; - offsetDate = DateTimeOffset.Parse(dateString, fmt); - Console.WriteLine("{0} returns {1}", - dateString, - offsetDate.ToString()); - // The example displays the following output to the console: - // 03-12-07 returns 12/3/2007 12:00:00 AM -08:00 - // 15/09/07 08:45:00 +1:00 returns 9/15/2007 8:45:00 AM +01:00 - // mar. 1 janvier 2008 1:00:00 +1:00 returns 1/1/2008 1:00:00 AM +01:00 - // - } + dateString = "mar. 1 janvier 2008 1:00:00 +1:00"; + offsetDate = DateTimeOffset.Parse(dateString, fmt); + Console.WriteLine($"{dateString} returns {offsetDate.ToString()}"); + // The example displays the following output to the console: + // 03-12-07 returns 12/3/2007 12:00:00 AM -08:00 + // 15/09/07 08:45:00 +1:00 returns 9/15/2007 8:45:00 AM +01:00 + // mar. 1 janvier 2008 1:00:00 +1:00 returns 1/1/2008 1:00:00 AM +01:00 + // + } - private static void ParseOverload3() - { - // - string dateString; - DateTimeOffset offsetDate; + private static void ParseOverload3() + { + // + string dateString; + DateTimeOffset offsetDate; - dateString = "05/01/2008 6:00:00"; - // Assume time is local - offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AssumeLocal); - Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 6:00:00 AM -07:00 + dateString = "05/01/2008 6:00:00"; + // Assume time is local + offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AssumeLocal); + Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 6:00:00 AM -07:00 - // Assume time is UTC - offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AssumeUniversal); - Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 6:00:00 AM +00:00 + // Assume time is UTC + offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AssumeUniversal); + Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 6:00:00 AM +00:00 - // Parse and convert to UTC - dateString = "05/01/2008 6:00:00AM +5:00"; - offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AdjustToUniversal); - Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 1:00:00 AM +00:00 - // - } + // Parse and convert to UTC + dateString = "05/01/2008 6:00:00AM +5:00"; + offsetDate = DateTimeOffset.Parse(dateString, null, DateTimeStyles.AdjustToUniversal); + Console.WriteLine(offsetDate.ToString()); // Displays 5/1/2008 1:00:00 AM +00:00 + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/ParseExact/ParseExact.cs b/snippets/csharp/System/DateTimeOffset/ParseExact/ParseExact.cs index 62cd7322784..b0e5ffce965 100644 --- a/snippets/csharp/System/DateTimeOffset/ParseExact/ParseExact.cs +++ b/snippets/csharp/System/DateTimeOffset/ParseExact/ParseExact.cs @@ -4,163 +4,163 @@ public class Class1 { - public static void Main() - { - ParseExact1(); - Console.WriteLine(); - ParseExact2(); - Console.WriteLine(); - ParseExact3(); - } + public static void Main() + { + ParseExact1(); + Console.WriteLine(); + ParseExact2(); + Console.WriteLine(); + ParseExact3(); + } - private static void ParseExact1() - { - // - string dateString, format; - DateTimeOffset result; - CultureInfo provider = CultureInfo.InvariantCulture; + private static void ParseExact1() + { + // + string dateString, format; + DateTimeOffset result; + CultureInfo provider = CultureInfo.InvariantCulture; - // Parse date-only value with invariant culture. - dateString = "06/15/2008"; - format = "d"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date-only value with invariant culture. + dateString = "06/15/2008"; + format = "d"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date-only value without leading zero in month using "d" format. - // Should throw a FormatException because standard short date pattern of - // invariant culture requires two-digit month. - dateString = "6/15/2008"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date-only value without leading zero in month using "d" format. + // Should throw a FormatException because standard short date pattern of + // invariant culture requires two-digit month. + dateString = "6/15/2008"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date and time with custom specifier. - dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; - format = "ddd dd MMM yyyy h:mm tt zzz"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("{0} is not in the correct format.", dateString); - } + // Parse date and time with custom specifier. + dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; + format = "ddd dd MMM yyyy h:mm tt zzz"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } - // Parse date and time with offset without offset//s minutes. - // Should throw a FormatException because "zzz" specifier requires leading - // zero in hours. - dateString = "Sun 15 Jun 2008 8:30 AM -06"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider); - Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("{0} is not in the correct format.", dateString); - } - // The example displays the following output: - // 06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00. - // 6/15/2008 is not in the correct format. - // Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00. - // Sun 15 Jun 2008 8:30 AM -06 is not in the correct format. - // - } + // Parse date and time with offset without offset//s minutes. + // Should throw a FormatException because "zzz" specifier requires leading + // zero in hours. + dateString = "Sun 15 Jun 2008 8:30 AM -06"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider); + Console.WriteLine($"{dateString} converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"{dateString} is not in the correct format."); + } + // The example displays the following output: + // 06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00. + // 6/15/2008 is not in the correct format. + // Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00. + // Sun 15 Jun 2008 8:30 AM -06 is not in the correct format. + // + } - private static void ParseExact2() - { - // - string dateString, format; - DateTimeOffset result; - CultureInfo provider = CultureInfo.InvariantCulture; + private static void ParseExact2() + { + // + string dateString, format; + DateTimeOffset result; + CultureInfo provider = CultureInfo.InvariantCulture; - // Parse date-only value with invariant culture and assume time is UTC. - dateString = "06/15/2008"; - format = "d"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider, - DateTimeStyles.AssumeUniversal); - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("'{0}' is not in the correct format.", dateString); - } + // Parse date-only value with invariant culture and assume time is UTC. + dateString = "06/15/2008"; + format = "d"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider, + DateTimeStyles.AssumeUniversal); + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in the correct format."); + } - // Parse date-only value with leading white space. - // Should throw a FormatException because only trailing white space is - // specified in method call. - dateString = " 06/15/2008"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider, - DateTimeStyles.AllowTrailingWhite); - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("'{0}' is not in the correct format.", dateString); - } + // Parse date-only value with leading white space. + // Should throw a FormatException because only trailing white space is + // specified in method call. + dateString = " 06/15/2008"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider, + DateTimeStyles.AllowTrailingWhite); + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in the correct format."); + } - // Parse date and time value, and allow all white space. - dateString = " 06/15/ 2008 15:15 -05:00"; - format = "MM/dd/yyyy H:mm zzz"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider, - DateTimeStyles.AllowWhiteSpaces); - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("'{0}' is not in the correct format.", dateString); - } + // Parse date and time value, and allow all white space. + dateString = " 06/15/ 2008 15:15 -05:00"; + format = "MM/dd/yyyy H:mm zzz"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider, + DateTimeStyles.AllowWhiteSpaces); + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in the correct format."); + } - // Parse date and time and convert to UTC. - dateString = " 06/15/2008 15:15:30 -05:00"; - format = "MM/dd/yyyy H:mm:ss zzz"; - try - { - result = DateTimeOffset.ParseExact(dateString, format, provider, - DateTimeStyles.AllowWhiteSpaces | - DateTimeStyles.AdjustToUniversal); - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - } - catch (FormatException) - { - Console.WriteLine("'{0}' is not in the correct format.", dateString); - } - // The example displays the following output: - // '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00. - // ' 06/15/2008' is not in the correct format. - // ' 06/15/ 2008 15:15 -05:00' converts to 6/15/2008 3:15:00 PM -05:00. - // ' 06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00. - // - } + // Parse date and time and convert to UTC. + dateString = " 06/15/2008 15:15:30 -05:00"; + format = "MM/dd/yyyy H:mm:ss zzz"; + try + { + result = DateTimeOffset.ParseExact(dateString, format, provider, + DateTimeStyles.AllowWhiteSpaces | + DateTimeStyles.AdjustToUniversal); + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + } + catch (FormatException) + { + Console.WriteLine($"'{dateString}' is not in the correct format."); + } + // The example displays the following output: + // '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00. + // ' 06/15/2008' is not in the correct format. + // ' 06/15/ 2008 15:15 -05:00' converts to 6/15/2008 3:15:00 PM -05:00. + // ' 06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00. + // + } - private static void ParseExact3() - { - // - TextReader conIn = Console.In; - TextWriter conOut = Console.Out; - int tries = 0; - string input = String.Empty; - string[] formats = new string[] {@"@M/dd/yyyy HH:m zzz", @"MM/dd/yyyy HH:m zzz", + private static void ParseExact3() + { + // + TextReader conIn = Console.In; + TextWriter conOut = Console.Out; + int tries = 0; + string input = string.Empty; + string[] formats = new string[] {@"@M/dd/yyyy HH:m zzz", @"MM/dd/yyyy HH:m zzz", @"M/d/yyyy HH:m zzz", @"MM/d/yyyy HH:m zzz", @"M/dd/yy HH:m zzz", @"MM/dd/yy HH:m zzz", @"M/d/yy HH:m zzz", @"MM/d/yy HH:m zzz", @@ -176,45 +176,46 @@ private static void ParseExact3() @"M/d/yyyy H:mm zzz", @"MM/d/yyyy H:mm zzz", @"M/dd/yy H:mm zzz", @"MM/dd/yy H:mm zzz", @"M/d/yy H:mm zzz", @"MM/d/yy H:mm zzz"}; - IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat; - DateTimeOffset result = new DateTimeOffset(); + IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat; + DateTimeOffset result = new(); - do { - conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"); - conOut.Write("Then press Enter: "); - input = conIn.ReadLine(); - conOut.WriteLine(); - try - { - result = DateTimeOffset.ParseExact(input, formats, provider, - DateTimeStyles.AllowWhiteSpaces); - break; - } - catch (FormatException) - { - Console.WriteLine("Unable to parse {0}.", input); - tries++; - } - } while (tries < 3); - if (tries >= 3) - Console.WriteLine("Exiting application without parsing {0}", input); - else - Console.WriteLine("{0} was converted to {1}", input, result.ToString()); - // Some successful sample interactions with the user might appear as follows: - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/08/2007 6:54 -6:00 - // - // 12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00 - // - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/8/2007 06:54 -06:00 - // - // 12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00 - // - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/5/07 6:54 -6:00 - // - // 12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 - // - } + do + { + conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"); + conOut.Write("Then press Enter: "); + input = conIn.ReadLine(); + conOut.WriteLine(); + try + { + result = DateTimeOffset.ParseExact(input, formats, provider, + DateTimeStyles.AllowWhiteSpaces); + break; + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse {input}."); + tries++; + } + } while (tries < 3); + if (tries >= 3) + Console.WriteLine($"Exiting application without parsing {input}"); + else + Console.WriteLine($"{input} was converted to {result.ToString()}"); + // Some successful sample interactions with the user might appear as follows: + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/08/2007 6:54 -6:00 + // + // 12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00 + // + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/8/2007 06:54 -06:00 + // + // 12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00 + // + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/5/07 6:54 -6:00 + // + // 12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601-2.cs b/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601-2.cs index b2f740b69ba..c9ae9ec5b21 100644 --- a/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601-2.cs +++ b/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601-2.cs @@ -3,41 +3,43 @@ public class Example { - public static void Main() - { - string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", + public static void Main() + { + string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", "2018/08/18T12:45:16.0000000Z", "2018-18-08T12:45:16.0000000Z", - "2018-08-18T12:45:16.0000000", + "2018-08-18T12:45:16.0000000", " 2018-08-18T12:45:16.0000000Z ", "2018-08-18T12:45:16.0000000+02:00", - "2018-08-18T12:45:16.0000000-07:00" }; - - ParseWithISO8601(dateStrings, DateTimeStyles.None); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal); } + "2018-08-18T12:45:16.0000000-07:00" }; - private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles) - { - Console.WriteLine($"Parsing with {styles}:"); - foreach (var dateString in dateStrings) - { - try { - var date = DateTimeOffset.ParseExact(dateString, "O", null, styles); - Console.WriteLine($" {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); - } - catch (FormatException) - { - Console.WriteLine($" FormatException: Unable to convert '{dateString}'"); - } - } - } + ParseWithISO8601(dateStrings, DateTimeStyles.None); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal); + } + + private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles) + { + Console.WriteLine($"Parsing with {styles}:"); + foreach (string dateString in dateStrings) + { + try + { + var date = DateTimeOffset.ParseExact(dateString, "O", null, styles); + Console.WriteLine($" {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); + } + catch (FormatException) + { + Console.WriteLine($" FormatException: Unable to convert '{dateString}'"); + } + } + } } // The example displays the following output: // Parsing with None: @@ -91,4 +93,4 @@ private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles // 2018-08-18T12:45:16.0000000 --> 2018-08-18 12:45:16 +00:00 // FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z ' // 2018-08-18T12:45:16.0000000+02:00 --> 2018-08-18 12:45:16 +02:00 -// 2018-08-18T12:45:16.0000000-07:00 --> 2018-08-18 12:45:16 -07:00 \ No newline at end of file +// 2018-08-18T12:45:16.0000000-07:00 --> 2018-08-18 12:45:16 -07:00 diff --git a/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601.cs b/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601.cs index f01c899d5f8..1cb15029bb9 100644 --- a/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601.cs +++ b/snippets/csharp/System/DateTimeOffset/ParseExact/parseexact-iso8601.cs @@ -2,27 +2,28 @@ public class Example2 { - public static void Main() - { - string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", + public static void Main() + { + string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", "2018/08/18T12:45:16.0000000Z", "2018-18-08T12:45:16.0000000Z", " 2018-08-18T12:45:16.0000000Z ", "2018-08-18T12:45:16.0000000+02:00", - "2018-08-18T12:45:16.0000000-07:00" }; - - foreach (var dateString in dateStrings) - { - try { - var date = DateTimeOffset.ParseExact(dateString, "O", null); - Console.WriteLine($"{dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); - } - catch (FormatException) - { - Console.WriteLine($"FormatException: Unable to convert '{dateString}'"); - } - } - } + "2018-08-18T12:45:16.0000000-07:00" }; + + foreach (string dateString in dateStrings) + { + try + { + var date = DateTimeOffset.ParseExact(dateString, "O", null); + Console.WriteLine($"{dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); + } + catch (FormatException) + { + Console.WriteLine($"FormatException: Unable to convert '{dateString}'"); + } + } + } } // The example displays the following output: // 2018-08-18T12:45:16.0000000Z --> 2018-08-18 12:45:16 +00:00 diff --git a/snippets/csharp/System/DateTimeOffset/ToOffset/ToOffset.cs b/snippets/csharp/System/DateTimeOffset/ToOffset/ToOffset.cs index e5dfa5131ba..342f358562c 100644 --- a/snippets/csharp/System/DateTimeOffset/ToOffset/ToOffset.cs +++ b/snippets/csharp/System/DateTimeOffset/ToOffset/ToOffset.cs @@ -3,41 +3,38 @@ public class DateTimeOffsetConversion { - private static DateTimeOffset sourceTime; + private static DateTimeOffset sourceTime; - public static void Main() - { - DateTimeOffset targetTime; - sourceTime = new DateTimeOffset(2007, 9, 1, 9, 30, 0, - new TimeSpan(-5, 0, 0)); + public static void Main() + { + DateTimeOffset targetTime; + sourceTime = new(2007, 9, 1, 9, 30, 0, + new TimeSpan(-5, 0, 0)); - // Convert to same time (return sourceTime unchanged) - targetTime = sourceTime.ToOffset(new TimeSpan(-5, 0, 0)); - ShowDateAndTimeInfo(targetTime); + // Convert to same time (return sourceTime unchanged) + targetTime = sourceTime.ToOffset(new TimeSpan(-5, 0, 0)); + ShowDateAndTimeInfo(targetTime); - // Convert to UTC (0 offset) - targetTime = sourceTime.ToOffset(TimeSpan.Zero); - ShowDateAndTimeInfo(targetTime); + // Convert to UTC (0 offset) + targetTime = sourceTime.ToOffset(TimeSpan.Zero); + ShowDateAndTimeInfo(targetTime); - // Convert to 8 hours behind UTC - targetTime = sourceTime.ToOffset(new TimeSpan(-8, 0, 0)); - ShowDateAndTimeInfo(targetTime); + // Convert to 8 hours behind UTC + targetTime = sourceTime.ToOffset(new TimeSpan(-8, 0, 0)); + ShowDateAndTimeInfo(targetTime); - // Convert to 3 hours ahead of UTC - targetTime = sourceTime.ToOffset(new TimeSpan(3, 0, 0)); - ShowDateAndTimeInfo(targetTime); - } + // Convert to 3 hours ahead of UTC + targetTime = sourceTime.ToOffset(new TimeSpan(3, 0, 0)); + ShowDateAndTimeInfo(targetTime); + } - private static void ShowDateAndTimeInfo(DateTimeOffset newTime) - { - Console.WriteLine("{0} converts to {1}", sourceTime, newTime); - Console.WriteLine("{0} and {1} are equal: {2}", - sourceTime, newTime, sourceTime.Equals(newTime)); - Console.WriteLine("{0} and {1} are identical: {2}", - sourceTime, newTime, - sourceTime.EqualsExact(newTime)); - Console.WriteLine(); - } + private static void ShowDateAndTimeInfo(DateTimeOffset newTime) + { + Console.WriteLine($"{sourceTime} converts to {newTime}"); + Console.WriteLine($"{sourceTime} and {newTime} are equal: {sourceTime.Equals(newTime)}"); + Console.WriteLine($"{sourceTime} and {newTime} are identical: {sourceTime.EqualsExact(newTime)}"); + Console.WriteLine(); + } } // // The example displays the following output: diff --git a/snippets/csharp/System/DateTimeOffset/ToString/ToString.cs b/snippets/csharp/System/DateTimeOffset/ToString/ToString.cs index 0203a80bd92..bf56cb6f53c 100644 --- a/snippets/csharp/System/DateTimeOffset/ToString/ToString.cs +++ b/snippets/csharp/System/DateTimeOffset/ToString/ToString.cs @@ -3,160 +3,159 @@ public class Class1 { - public static void Main() - { - ToString1(); - Console.WriteLine(); - ToString2(); - Console.WriteLine(); - ToString3(); - Console.WriteLine(); - ToString4(); - } - - private static void ToString1() - { - // - DateTimeOffset thisDate; - - // Show output for UTC time - thisDate = DateTimeOffset.UtcNow; - Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 7:13:50 PM +00:00 - - // Show output for local time - thisDate = DateTimeOffset.Now; - Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 12:13:50 PM -07:00 - - // Show output for arbitrary time offset - thisDate = thisDate.ToOffset(new TimeSpan(-5, 0, 0)); - Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 2:13:50 PM -05:00 - // - } - - private static void ToString2() - { - // - CultureInfo[] cultures = new CultureInfo[] {CultureInfo.InvariantCulture, + public static void Main() + { + ToString1(); + Console.WriteLine(); + ToString2(); + Console.WriteLine(); + ToString3(); + Console.WriteLine(); + ToString4(); + } + + private static void ToString1() + { + // + DateTimeOffset thisDate; + + // Show output for UTC time + thisDate = DateTimeOffset.UtcNow; + Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 7:13:50 PM +00:00 + + // Show output for local time + thisDate = DateTimeOffset.Now; + Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 12:13:50 PM -07:00 + + // Show output for arbitrary time offset + thisDate = thisDate.ToOffset(new TimeSpan(-5, 0, 0)); + Console.WriteLine(thisDate.ToString()); // Displays 3/28/2007 2:13:50 PM -05:00 + // + } + + private static void ToString2() + { + // + CultureInfo[] cultures = new CultureInfo[] {CultureInfo.InvariantCulture, new CultureInfo("en-us"), new CultureInfo("fr-fr"), new CultureInfo("de-DE"), new CultureInfo("es-ES")}; - DateTimeOffset thisDate = new DateTimeOffset(2007, 5, 1, 9, 0, 0, - TimeSpan.Zero); - - foreach (CultureInfo culture in cultures) - { - string cultureName; - if (string.IsNullOrEmpty(culture.Name)) - cultureName = culture.NativeName; - else - cultureName = culture.Name; - - Console.WriteLine("In {0}, {1}", - cultureName, thisDate.ToString(culture)); - } - // The example produces the following output: - // In Invariant Language (Invariant Country), 05/01/2007 09:00:00 +00:00 - // In en-US, 5/1/2007 9:00:00 AM +00:00 - // In fr-FR, 01/05/2007 09:00:00 +00:00 - // In de-DE, 01.05.2007 09:00:00 +00:00 - // In es-ES, 01/05/2007 9:00:00 +00:00 - // - } - - private static void ToString3() - { - // - DateTimeOffset outputDate = new DateTimeOffset(2007, 10, 31, 21, 0, 0, - new TimeSpan(-8, 0, 0)); - string specifier; - - // Output date using each standard date/time format specifier - specifier = "d"; - // Displays d: 10/31/2007 - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "D"; - // Displays D: Wednesday, October 31, 2007 - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "t"; - // Displays t: 9:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "T"; - // Displays T: 9:00:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "f"; - // Displays f: Wednesday, October 31, 2007 9:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "F"; - // Displays F: Wednesday, October 31, 2007 9:00:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "g"; - // Displays g: 10/31/2007 9:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "G"; - // Displays G: 10/31/2007 9:00:00 PM - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "M"; // 'm' is identical - // Displays M: October 31 - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "R"; // 'r' is identical - // Displays R: Thu, 01 Nov 2007 05:00:00 GMT - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "s"; - // Displays s: 2007-10-31T21:00:00 - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - specifier = "u"; - // Displays u: 2007-11-01 05:00:00Z - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - - // Specifier is not supported - specifier = "U"; - try - { - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - } - catch (FormatException) - { - Console.WriteLine("{0}: Not supported.", specifier); - } - - specifier = "Y"; // 'y' is identical - // Displays Y: October, 2007 - Console.WriteLine("{0}: {1}", specifier, outputDate.ToString(specifier)); - // - } - - private static void ToString4() - { - // - DateTimeOffset outputDate = new DateTimeOffset(2007, 11, 1, 9, 0, 0, - new TimeSpan(-7, 0, 0)); - string format = "dddd, MMM dd yyyy HH:mm:ss zzz"; - - // Output date and time using custom format specification - Console.WriteLine(outputDate.ToString(format, null as DateTimeFormatInfo)); - Console.WriteLine(outputDate.ToString(format, CultureInfo.InvariantCulture)); - Console.WriteLine(outputDate.ToString(format, - new CultureInfo("fr-FR"))); - Console.WriteLine(outputDate.ToString(format, - new CultureInfo("es-ES"))); - // The example displays the following output to the console: - // Thursday, Nov 01 2007 09:00:00 -07:00 - // Thursday, Nov 01 2007 09:00:00 -07:00 - // jeudi, nov. 01 2007 09:00:00 -07:00 - // jueves, nov 01 2007 09:00:00 -07:00 - // - } + DateTimeOffset thisDate = new(2007, 5, 1, 9, 0, 0, + TimeSpan.Zero); + + foreach (CultureInfo culture in cultures) + { + string cultureName; + if (string.IsNullOrEmpty(culture.Name)) + cultureName = culture.NativeName; + else + cultureName = culture.Name; + + Console.WriteLine($"In {cultureName}, {thisDate.ToString(culture)}"); + } + // The example produces the following output: + // In Invariant Language (Invariant Country), 05/01/2007 09:00:00 +00:00 + // In en-US, 5/1/2007 9:00:00 AM +00:00 + // In fr-FR, 01/05/2007 09:00:00 +00:00 + // In de-DE, 01.05.2007 09:00:00 +00:00 + // In es-ES, 01/05/2007 9:00:00 +00:00 + // + } + + private static void ToString3() + { + // + DateTimeOffset outputDate = new(2007, 10, 31, 21, 0, 0, + new TimeSpan(-8, 0, 0)); + string specifier; + + // Output date using each standard date/time format specifier + specifier = "d"; + // Displays d: 10/31/2007 + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "D"; + // Displays D: Wednesday, October 31, 2007 + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "t"; + // Displays t: 9:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "T"; + // Displays T: 9:00:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "f"; + // Displays f: Wednesday, October 31, 2007 9:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "F"; + // Displays F: Wednesday, October 31, 2007 9:00:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "g"; + // Displays g: 10/31/2007 9:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "G"; + // Displays G: 10/31/2007 9:00:00 PM + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "M"; // 'm' is identical + // Displays M: October 31 + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "R"; // 'r' is identical + // Displays R: Thu, 01 Nov 2007 05:00:00 GMT + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "s"; + // Displays s: 2007-10-31T21:00:00 + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + specifier = "u"; + // Displays u: 2007-11-01 05:00:00Z + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + + // Specifier is not supported + specifier = "U"; + try + { + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + } + catch (FormatException) + { + Console.WriteLine($"{specifier}: Not supported."); + } + + specifier = "Y"; // 'y' is identical + // Displays Y: October, 2007 + Console.WriteLine($"{specifier}: {outputDate.ToString(specifier)}"); + // + } + + private static void ToString4() + { + // + DateTimeOffset outputDate = new(2007, 11, 1, 9, 0, 0, + new TimeSpan(-7, 0, 0)); + string format = "dddd, MMM dd yyyy HH:mm:ss zzz"; + + // Output date and time using custom format specification + Console.WriteLine(outputDate.ToString(format, null as DateTimeFormatInfo)); + Console.WriteLine(outputDate.ToString(format, CultureInfo.InvariantCulture)); + Console.WriteLine(outputDate.ToString(format, + new CultureInfo("fr-FR"))); + Console.WriteLine(outputDate.ToString(format, + new CultureInfo("es-ES"))); + // The example displays the following output to the console: + // Thursday, Nov 01 2007 09:00:00 -07:00 + // Thursday, Nov 01 2007 09:00:00 -07:00 + // jeudi, nov. 01 2007 09:00:00 -07:00 + // jueves, nov 01 2007 09:00:00 -07:00 + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception1.cs b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception1.cs index 4a2c50ffe04..68f6cfa0ed9 100644 --- a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception1.cs +++ b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception1.cs @@ -4,23 +4,22 @@ public class Example { - public static void Main() - { - CultureInfo jaJP = new CultureInfo("ja-JP"); - jaJP.DateTimeFormat.Calendar = new JapaneseCalendar(); - DateTimeOffset date1 = new DateTimeOffset(new DateTime(1867, 1, 1), - TimeSpan.Zero); + public static void Main() + { + CultureInfo jaJP = new("ja-JP"); + jaJP.DateTimeFormat.Calendar = new JapaneseCalendar(); + DateTimeOffset date1 = new(new DateTime(1867, 1, 1), + TimeSpan.Zero); - try { - Console.WriteLine(date1.ToString(jaJP)); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", - date1, - jaJP.DateTimeFormat.Calendar.MinSupportedDateTime, - jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime); - } - } + try + { + Console.WriteLine(date1.ToString(jaJP)); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"{date1:d} is earlier than {jaJP.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"); + } + } } // The example displays the following output: // 1/1/1867 is earlier than 9/8/1868 or later than 12/31/9999 diff --git a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception2.cs b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception2.cs index b1b8ea6caee..24ef2a4551d 100644 --- a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception2.cs +++ b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception2.cs @@ -5,32 +5,31 @@ public class Example { - public static void Main() - { - DateTimeOffset date1 = new DateTimeOffset(new DateTime(550, 1, 1), - TimeSpan.Zero); - CultureInfo dft; - CultureInfo arSY = new CultureInfo("ar-SY"); - arSY.DateTimeFormat.Calendar = new HijriCalendar(); + public static void Main() + { + DateTimeOffset date1 = new(new DateTime(550, 1, 1), + TimeSpan.Zero); + CultureInfo dft; + CultureInfo arSY = new("ar-SY"); + arSY.DateTimeFormat.Calendar = new HijriCalendar(); - // Change current culture to ar-SY. - dft = Thread.CurrentThread.CurrentCulture; - Thread.CurrentThread.CurrentCulture = arSY; + // Change current culture to ar-SY. + dft = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = arSY; - // Display the date using the current culture's calendar. - try { - Console.WriteLine(date1.ToString()); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0} is earlier than {1} or later than {2}", - date1.ToString("d", CultureInfo.InvariantCulture), - arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture), - arSY.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)); - } + // Display the date using the current culture's calendar. + try + { + Console.WriteLine(date1.ToString()); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {arSY.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {arSY.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)}"); + } - // Restore the default culture. - Thread.CurrentThread.CurrentCulture = dft; - } + // Restore the default culture. + Thread.CurrentThread.CurrentCulture = dft; + } } // The example displays the following output: // 01/01/0550 is earlier than 07/18/0622 or later than 12/31/9999 diff --git a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception3.cs b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception3.cs index d80460f90ff..8d741785af4 100644 --- a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception3.cs +++ b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception3.cs @@ -5,32 +5,31 @@ public class Example { - public static void Main() - { - DateTimeOffset date1 = new DateTimeOffset(new DateTime(1550, 7, 21), - TimeSpan.Zero); - CultureInfo dft; - CultureInfo heIL = new CultureInfo("he-IL"); - heIL.DateTimeFormat.Calendar = new HebrewCalendar(); + public static void Main() + { + DateTimeOffset date1 = new(new DateTime(1550, 7, 21), + TimeSpan.Zero); + CultureInfo dft; + CultureInfo heIL = new("he-IL"); + heIL.DateTimeFormat.Calendar = new HebrewCalendar(); - // Change current culture to he-IL. - dft = Thread.CurrentThread.CurrentCulture; - Thread.CurrentThread.CurrentCulture = heIL; + // Change current culture to he-IL. + dft = Thread.CurrentThread.CurrentCulture; + Thread.CurrentThread.CurrentCulture = heIL; - // Display the date using the current culture's calendar. - try { - Console.WriteLine(date1.ToString("G")); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0} is earlier than {1} or later than {2}", - date1.ToString("d", CultureInfo.InvariantCulture), - heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture), - heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)); - } + // Display the date using the current culture's calendar. + try + { + Console.WriteLine(date1.ToString("G")); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"{date1.ToString("d", CultureInfo.InvariantCulture)} is earlier than {heIL.DateTimeFormat.Calendar.MinSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)} or later than {heIL.DateTimeFormat.Calendar.MaxSupportedDateTime.ToString("d", CultureInfo.InvariantCulture)}"); + } - // Restore the default culture. - Thread.CurrentThread.CurrentCulture = dft; - } + // Restore the default culture. + Thread.CurrentThread.CurrentCulture = dft; + } } // The example displays the following output: // 07/21/1550 is earlier than 01/01/1583 or later than 09/29/2239 diff --git a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception4.cs b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception4.cs index cb9ac2cbb2c..e471a4642d9 100644 --- a/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception4.cs +++ b/snippets/csharp/System/DateTimeOffset/ToString/datetimeoffset.tostring.argumentoutofrangeexception4.cs @@ -4,23 +4,22 @@ public class Example { - public static void Main() - { - CultureInfo arSA = new CultureInfo("ar-SA"); - arSA.DateTimeFormat.Calendar = new UmAlQuraCalendar(); - DateTimeOffset date1 = new DateTimeOffset(new DateTime(1890, 9, 10), - TimeSpan.Zero); + public static void Main() + { + CultureInfo arSA = new("ar-SA"); + arSA.DateTimeFormat.Calendar = new UmAlQuraCalendar(); + DateTimeOffset date1 = new(new DateTime(1890, 9, 10), + TimeSpan.Zero); - try { - Console.WriteLine(date1.ToString("d", arSA)); - } - catch (ArgumentOutOfRangeException) { - Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}", - date1, - arSA.DateTimeFormat.Calendar.MinSupportedDateTime, - arSA.DateTimeFormat.Calendar.MaxSupportedDateTime); - } - } + try + { + Console.WriteLine(date1.ToString("d", arSA)); + } + catch (ArgumentOutOfRangeException) + { + Console.WriteLine($"{date1:d} is earlier than {arSA.DateTimeFormat.Calendar.MinSupportedDateTime:d} or later than {arSA.DateTimeFormat.Calendar.MaxSupportedDateTime:d}"); + } + } } // The example displays the following output: // 9/10/1890 is earlier than 4/30/1900 or later than 5/13/2029 diff --git a/snippets/csharp/System/DateTimeOffset/ToUnixTimeSeconds/tounixtimeseconds1.cs b/snippets/csharp/System/DateTimeOffset/ToUnixTimeSeconds/tounixtimeseconds1.cs index a176165d292..a849a1914c2 100644 --- a/snippets/csharp/System/DateTimeOffset/ToUnixTimeSeconds/tounixtimeseconds1.cs +++ b/snippets/csharp/System/DateTimeOffset/ToUnixTimeSeconds/tounixtimeseconds1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); - Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds()); + public static void Main() + { + DateTimeOffset dto = new(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); + Console.WriteLine($"{dto} --> Unix Seconds: {dto.ToUnixTimeSeconds()}"); - dto = new DateTimeOffset(1969, 12, 31, 23, 59, 0, TimeSpan.Zero); - Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds()); + dto = new(1969, 12, 31, 23, 59, 0, TimeSpan.Zero); + Console.WriteLine($"{dto} --> Unix Seconds: {dto.ToUnixTimeSeconds()}"); - dto = new DateTimeOffset(1970, 1, 1, 0, 1, 0, TimeSpan.Zero); - Console.WriteLine("{0} --> Unix Seconds: {1}", dto, dto.ToUnixTimeSeconds()); - } + dto = new(1970, 1, 1, 0, 1, 0, TimeSpan.Zero); + Console.WriteLine($"{dto} --> Unix Seconds: {dto.ToUnixTimeSeconds()}"); + } } // The example displays the following output: // 1/1/1970 12:00:00 AM +00:00 --> Unix Seconds: 0 @@ -23,46 +23,44 @@ public static void Main() public class DateTimeOffset2 { - // Number of days in a non-leap year - private const int DaysPerYear = 365; - // Number of days in 4 years - private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 - // Number of days in 100 years - private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 - // Number of days in 400 years - private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097 - // Number of days from 1/1/0001 to 12/31/1969 - internal const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162 + // Number of days in a non-leap year + private const int DaysPerYear = 365; + // Number of days in 4 years + private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 + // Number of days in 100 years + private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 + // Number of days in 400 years + private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097 + // Number of days from 1/1/0001 to 12/31/1969 + internal const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162 - private const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970; // 621,355,968,000,000,000 - private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 - private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 + private const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970; // 621,355,968,000,000,000 + private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 + private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 - private DateTimeOffset dto; + private DateTimeOffset dto; - public DateTimeOffset2(DateTimeOffset dto) - { - this.dto = dto; - } + public DateTimeOffset2(DateTimeOffset dto) => this.dto = dto; - public long ToUnixTimeSeconds() { - // Truncate sub-second precision before offsetting by the Unix Epoch to avoid - // the last digit being off by one for dates that result in negative Unix times. - // - // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 - // ticks = 621355967990010000 - // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 - // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 - // - // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, - // whereas we actually always want to round *down* when converting to Unix time. This happens - // automatically for positive Unix time values. Now the example becomes: - // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 - // secondsFromEpoch = seconds - UnixEpochSeconds = -1 - // - // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, - // rather than toward the Unix Epoch (1/1/1970 00:00:00). - long seconds = dto.UtcDateTime.Ticks / TimeSpan.TicksPerSecond; - return seconds - UnixEpochSeconds; - } + public long ToUnixTimeSeconds() + { + // Truncate sub-second precision before offsetting by the Unix Epoch to avoid + // the last digit being off by one for dates that result in negative Unix times. + // + // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 + // ticks = 621355967990010000 + // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 + // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 + // + // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, + // whereas we actually always want to round *down* when converting to Unix time. This happens + // automatically for positive Unix time values. Now the example becomes: + // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 + // secondsFromEpoch = seconds - UnixEpochSeconds = -1 + // + // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, + // rather than toward the Unix Epoch (1/1/1970 00:00:00). + long seconds = dto.UtcDateTime.Ticks / TimeSpan.TicksPerSecond; + return seconds - UnixEpochSeconds; + } } diff --git a/snippets/csharp/System/DateTimeOffset/TryParse/TryParse.cs b/snippets/csharp/System/DateTimeOffset/TryParse/TryParse.cs index 98904c295c2..50291ba3059 100644 --- a/snippets/csharp/System/DateTimeOffset/TryParse/TryParse.cs +++ b/snippets/csharp/System/DateTimeOffset/TryParse/TryParse.cs @@ -3,96 +3,88 @@ public class Class1 { - public static void Main() - { - TryParse1(); - Console.WriteLine(); - TryParse2(); - } + public static void Main() + { + TryParse1(); + Console.WriteLine(); + TryParse2(); + } - private static void TryParse1() - { - // - DateTimeOffset parsedDate; - string dateString; + private static void TryParse1() + { + // + DateTimeOffset parsedDate; + string dateString; - // String with date only - dateString = "05/01/2008"; - if (DateTimeOffset.TryParse(dateString, out parsedDate)) - Console.WriteLine("{0} was converted to {1}.", - dateString, parsedDate); + // String with date only + dateString = "05/01/2008"; + if (DateTimeOffset.TryParse(dateString, out parsedDate)) + Console.WriteLine($"{dateString} was converted to {parsedDate}."); - // String with time only - dateString = "11:36 PM"; - if (DateTimeOffset.TryParse(dateString, out parsedDate)) - Console.WriteLine("{0} was converted to {1}.", - dateString, parsedDate); + // String with time only + dateString = "11:36 PM"; + if (DateTimeOffset.TryParse(dateString, out parsedDate)) + Console.WriteLine($"{dateString} was converted to {parsedDate}."); - // String with date and offset - dateString = "05/01/2008 +7:00"; - if (DateTimeOffset.TryParse(dateString, out parsedDate)) - Console.WriteLine("{0} was converted to {1}.", - dateString, parsedDate); + // String with date and offset + dateString = "05/01/2008 +7:00"; + if (DateTimeOffset.TryParse(dateString, out parsedDate)) + Console.WriteLine($"{dateString} was converted to {parsedDate}."); - // String with day abbreviation - dateString = "Thu May 01, 2008"; - if (DateTimeOffset.TryParse(dateString, out parsedDate)) - Console.WriteLine("{0} was converted to {1}.", - dateString, parsedDate); + // String with day abbreviation + dateString = "Thu May 01, 2008"; + if (DateTimeOffset.TryParse(dateString, out parsedDate)) + Console.WriteLine($"{dateString} was converted to {parsedDate}."); - // String with date, time with AM/PM designator, and offset - dateString = "5/1/2008 10:00 AM -07:00"; - if (DateTimeOffset.TryParse(dateString, out parsedDate)) - Console.WriteLine("{0} was converted to {1}.", - dateString, parsedDate); - // if (run on 3/29/07, the example displays the following output - // to the console: - // 05/01/2008 was converted to 5/1/2008 12:00:00 AM -07:00. - // 11:36 PM was converted to 3/29/2007 11:36:00 PM -07:00. - // 05/01/2008 +7:00 was converted to 5/1/2008 12:00:00 AM +07:00. - // Thu May 01, 2008 was converted to 5/1/2008 12:00:00 AM -07:00. - // 5/1/2008 10:00 AM -07:00 was converted to 5/1/2008 10:00:00 AM -07:00. - // - } + // String with date, time with AM/PM designator, and offset + dateString = "5/1/2008 10:00 AM -07:00"; + if (DateTimeOffset.TryParse(dateString, out parsedDate)) + Console.WriteLine($"{dateString} was converted to {parsedDate}."); + // if (run on 3/29/07, the example displays the following output + // to the console: + // 05/01/2008 was converted to 5/1/2008 12:00:00 AM -07:00. + // 11:36 PM was converted to 3/29/2007 11:36:00 PM -07:00. + // 05/01/2008 +7:00 was converted to 5/1/2008 12:00:00 AM +07:00. + // Thu May 01, 2008 was converted to 5/1/2008 12:00:00 AM -07:00. + // 5/1/2008 10:00 AM -07:00 was converted to 5/1/2008 10:00:00 AM -07:00. + // + } - private static void TryParse2() - { - // - string dateString; - DateTimeOffset parsedDate; + private static void TryParse2() + { + // + string dateString; + DateTimeOffset parsedDate; - dateString = "05/01/2008 6:00:00"; - // Assume time is local - if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, - DateTimeStyles.AssumeLocal, - out parsedDate)) - Console.WriteLine("'{0}' was converted to {1}.", - dateString, parsedDate.ToString()); - else - Console.WriteLine("Unable to parse '{0}'.", dateString); + dateString = "05/01/2008 6:00:00"; + // Assume time is local + if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, + DateTimeStyles.AssumeLocal, + out parsedDate)) + Console.WriteLine($"'{dateString}' was converted to {parsedDate.ToString()}."); + else + Console.WriteLine($"Unable to parse '{dateString}'."); - // Assume time is UTC - if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, - DateTimeStyles.AssumeUniversal, - out parsedDate)) - Console.WriteLine("'{0}' was converted to {1}.", - dateString, parsedDate.ToString()); - else - Console.WriteLine("Unable to parse '{0}'.", dateString); + // Assume time is UTC + if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, + DateTimeStyles.AssumeUniversal, + out parsedDate)) + Console.WriteLine($"'{dateString}' was converted to {parsedDate.ToString()}."); + else + Console.WriteLine($"Unable to parse '{dateString}'."); - // Parse and convert to UTC - dateString = "05/01/2008 6:00:00AM +5:00"; - if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, - DateTimeStyles.AdjustToUniversal, - out parsedDate)) - Console.WriteLine("'{0}' was converted to {1}.", - dateString, parsedDate.ToString()); - else - Console.WriteLine("Unable to parse '{0}'.", dateString); - // The example displays the following output to the console: - // '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM -07:00. - // '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM +00:00. - // '05/01/2008 6:00:00AM +5:00' was converted to 5/1/2008 1:00:00 AM +00:00. - // - } + // Parse and convert to UTC + dateString = "05/01/2008 6:00:00AM +5:00"; + if (DateTimeOffset.TryParse(dateString, null as IFormatProvider, + DateTimeStyles.AdjustToUniversal, + out parsedDate)) + Console.WriteLine($"'{dateString}' was converted to {parsedDate.ToString()}."); + else + Console.WriteLine($"Unable to parse '{dateString}'."); + // The example displays the following output to the console: + // '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM -07:00. + // '05/01/2008 6:00:00' was converted to 5/1/2008 6:00:00 AM +00:00. + // '05/01/2008 6:00:00AM +5:00' was converted to 5/1/2008 1:00:00 AM +00:00. + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/TryParseExact/TryParseExact.cs b/snippets/csharp/System/DateTimeOffset/TryParseExact/TryParseExact.cs index d7788163220..e6c0d33abcf 100644 --- a/snippets/csharp/System/DateTimeOffset/TryParseExact/TryParseExact.cs +++ b/snippets/csharp/System/DateTimeOffset/TryParseExact/TryParseExact.cs @@ -4,78 +4,78 @@ public class Class1 { - public static void Main() - { - TryParseExact1(); - Console.WriteLine(); - TryParseExact2(); - } + public static void Main() + { + TryParseExact1(); + Console.WriteLine(); + TryParseExact2(); + } - private static void TryParseExact1() - { - // - string dateString, format; - DateTimeOffset result; - IFormatProvider provider = CultureInfo.InvariantCulture; + private static void TryParseExact1() + { + // + string dateString, format; + DateTimeOffset result; + IFormatProvider provider = CultureInfo.InvariantCulture; - // Parse date-only value with invariant culture and assume time is UTC. - dateString = "06/15/2008"; - format = "d"; - if (DateTimeOffset.TryParseExact(dateString, format, provider, - DateTimeStyles.AssumeUniversal, - out result)) - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - else - Console.WriteLine("'{0}' is not in the correct format.", dateString); + // Parse date-only value with invariant culture and assume time is UTC. + dateString = "06/15/2008"; + format = "d"; + if (DateTimeOffset.TryParseExact(dateString, format, provider, + DateTimeStyles.AssumeUniversal, + out result)) + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + else + Console.WriteLine($"'{dateString}' is not in the correct format."); - // Parse date-only value with leading white space. - // Should return False because only trailing white space is - // specified in method call. - dateString = " 06/15/2008"; - if (DateTimeOffset.TryParseExact(dateString, format, provider, - DateTimeStyles.AllowTrailingWhite, - out result)) - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - else - Console.WriteLine("'{0}' is not in the correct format.", dateString); + // Parse date-only value with leading white space. + // Should return False because only trailing white space is + // specified in method call. + dateString = " 06/15/2008"; + if (DateTimeOffset.TryParseExact(dateString, format, provider, + DateTimeStyles.AllowTrailingWhite, + out result)) + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + else + Console.WriteLine($"'{dateString}' is not in the correct format."); - // Parse date and time value, and allow all white space. - dateString = " 06/15/ 2008 15:15 -05:00"; - format = "MM/dd/yyyy H:mm zzz"; - if (DateTimeOffset.TryParseExact(dateString, format, provider, - DateTimeStyles.AllowWhiteSpaces, - out result)) - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - else - Console.WriteLine("'{0}' is not in the correct format.", dateString); + // Parse date and time value, and allow all white space. + dateString = " 06/15/ 2008 15:15 -05:00"; + format = "MM/dd/yyyy H:mm zzz"; + if (DateTimeOffset.TryParseExact(dateString, format, provider, + DateTimeStyles.AllowWhiteSpaces, + out result)) + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + else + Console.WriteLine($"'{dateString}' is not in the correct format."); - // Parse date and time and convert to UTC. - dateString = " 06/15/2008 15:15:30 -05:00"; - format = "MM/dd/yyyy H:mm:ss zzz"; - if (DateTimeOffset.TryParseExact(dateString, format, provider, - DateTimeStyles.AllowWhiteSpaces | - DateTimeStyles.AdjustToUniversal, - out result)) - Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString()); - else - Console.WriteLine("'{0}' is not in the correct format.", dateString); - // The example displays the following output: - // '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00. - // ' 06/15/2008' is not in the correct format. - // ' 06/15/ 2008 15:15 -05:00' converts to 6/15/2008 3:15:00 PM -05:00. - // ' 06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00. - // - } + // Parse date and time and convert to UTC. + dateString = " 06/15/2008 15:15:30 -05:00"; + format = "MM/dd/yyyy H:mm:ss zzz"; + if (DateTimeOffset.TryParseExact(dateString, format, provider, + DateTimeStyles.AllowWhiteSpaces | + DateTimeStyles.AdjustToUniversal, + out result)) + Console.WriteLine($"'{dateString}' converts to {result.ToString()}."); + else + Console.WriteLine($"'{dateString}' is not in the correct format."); + // The example displays the following output: + // '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00. + // ' 06/15/2008' is not in the correct format. + // ' 06/15/ 2008 15:15 -05:00' converts to 6/15/2008 3:15:00 PM -05:00. + // ' 06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00. + // + } - private static void TryParseExact2() - { - // - TextReader conIn = Console.In; - TextWriter conOut = Console.Out; - int tries = 0; - string input = String.Empty; + private static void TryParseExact2() + { + // + TextReader conIn = Console.In; + TextWriter conOut = Console.Out; + int tries = 0; + string input = string.Empty; - string[] formats = new string[] {"M/dd/yyyy HH:m zzz", "MM/dd/yyyy HH:m zzz", + string[] formats = new string[] {"M/dd/yyyy HH:m zzz", "MM/dd/yyyy HH:m zzz", "M/d/yyyy HH:m zzz", "MM/d/yyyy HH:m zzz", "M/dd/yy HH:m zzz", "MM/dd/yy HH:m zzz", "M/d/yy HH:m zzz", "MM/d/yy HH:m zzz", @@ -91,45 +91,46 @@ private static void TryParseExact2() "M/d/yyyy H:mm zzz", "MM/d/yyyy H:mm zzz", "M/dd/yy H:mm zzz", "MM/dd/yy H:mm zzz", "M/d/yy H:mm zzz", "MM/d/yy H:mm zzz"}; - IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat; - DateTimeOffset result; + IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat; + DateTimeOffset result; - do { - conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"); - conOut.Write("Then press Enter: "); - input = conIn.ReadLine(); - conOut.WriteLine(); - if (DateTimeOffset.TryParseExact(input, formats, provider, - DateTimeStyles.AllowWhiteSpaces, - out result)) - { - break; - } - else - { - Console.WriteLine("Unable to parse {0}.", input); - tries++; - } - } while (tries < 3); - if (tries >= 3) - Console.WriteLine("Exiting application without parsing {0}", input); - else - Console.WriteLine("{0} was converted to {1}", input, result.ToString()); - // Some successful sample interactions with the user might appear as follows: - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/08/2007 6:54 -6:00 - // - // 12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00 - // - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/8/2007 06:54 -06:00 - // - // 12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00 - // - // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), - // Then press Enter: 12/5/07 6:54 -6:00 - // - // 12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 - // - } + do + { + conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"); + conOut.Write("Then press Enter: "); + input = conIn.ReadLine(); + conOut.WriteLine(); + if (DateTimeOffset.TryParseExact(input, formats, provider, + DateTimeStyles.AllowWhiteSpaces, + out result)) + { + break; + } + else + { + Console.WriteLine($"Unable to parse {input}."); + tries++; + } + } while (tries < 3); + if (tries >= 3) + Console.WriteLine($"Exiting application without parsing {input}"); + else + Console.WriteLine($"{input} was converted to {result.ToString()}"); + // Some successful sample interactions with the user might appear as follows: + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/08/2007 6:54 -6:00 + // + // 12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00 + // + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/8/2007 06:54 -06:00 + // + // 12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00 + // + // Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM), + // Then press Enter: 12/5/07 6:54 -6:00 + // + // 12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00 + // + } } diff --git a/snippets/csharp/System/DateTimeOffset/TryParseExact/tryparseexacto8601-2.cs b/snippets/csharp/System/DateTimeOffset/TryParseExact/tryparseexacto8601-2.cs index 2f6671d703f..ddf340a3fb2 100644 --- a/snippets/csharp/System/DateTimeOffset/TryParseExact/tryparseexacto8601-2.cs +++ b/snippets/csharp/System/DateTimeOffset/TryParseExact/tryparseexacto8601-2.cs @@ -3,42 +3,43 @@ public class Example { - public static void Main() - { - string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", + public static void Main() + { + string[] dateStrings = { "2018-08-18T12:45:16.0000000Z", "2018/08/18T12:45:16.0000000Z", "2018-18-08T12:45:16.0000000Z", - "2018-08-18T12:45:16.0000000", + "2018-08-18T12:45:16.0000000", " 2018-08-18T12:45:16.0000000Z ", "2018-08-18T12:45:16.0000000+02:00", - "2018-08-18T12:45:16.0000000-07:00" }; - - ParseWithISO8601(dateStrings, DateTimeStyles.None); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal); - Console.WriteLine("\n-----\n"); - ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal); } + "2018-08-18T12:45:16.0000000-07:00" }; - private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles) - { - Console.WriteLine($"Parsing with {styles}:"); - DateTimeOffset date; - foreach (var dateString in dateStrings) - { - if (DateTimeOffset.TryParseExact(dateString, "O", null, styles, out date)) - { - Console.WriteLine($" {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); - } - else - { - Console.WriteLine($" Unable to convert '{dateString}'"); - } - } - } + ParseWithISO8601(dateStrings, DateTimeStyles.None); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal); + Console.WriteLine("\n-----\n"); + ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal); + } + + private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles) + { + Console.WriteLine($"Parsing with {styles}:"); + DateTimeOffset date; + foreach (string dateString in dateStrings) + { + if (DateTimeOffset.TryParseExact(dateString, "O", null, styles, out date)) + { + Console.WriteLine($" {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}"); + } + else + { + Console.WriteLine($" Unable to convert '{dateString}'"); + } + } + } } // The example displays the following output: // Parsing with None: diff --git a/snippets/csharp/System/DateTimeOffset/op_Addition/Operators.cs b/snippets/csharp/System/DateTimeOffset/op_Addition/Operators.cs index 83a83e69ca0..d4f2a4b4425 100644 --- a/snippets/csharp/System/DateTimeOffset/op_Addition/Operators.cs +++ b/snippets/csharp/System/DateTimeOffset/op_Addition/Operators.cs @@ -2,197 +2,187 @@ public class Class1 { - public static void Main() - { - ShowAddition(); - ShowEquality(); - ShowGreaterThan(); - ShowGreaterThanOrEqualTo(); - ShowImplicitConversions(); - ShowInequality(); - ShowLessThan(); - ShowLessThanOrEqualTo(); - ShowSubtraction1(); - ShowSubtraction2(); - } - - private static void ShowAddition() - { - // - DateTimeOffset date1 = new DateTimeOffset(2008, 1, 1, 13, 32, 45, - new TimeSpan(-5, 0, 0)); - TimeSpan interval1 = new TimeSpan(202, 3, 30, 0); - TimeSpan interval2 = new TimeSpan(5, 0, 0, 0); - DateTimeOffset date2; - - Console.WriteLine(date1); // Displays 1/1/2008 1:32:45 PM -05:00 - date2 = date1 + interval1; - Console.WriteLine(date2); // Displays 7/21/2008 5:02:45 PM -05:00 - date2 += interval2; - Console.WriteLine(date2); // Displays 7/26/2008 5:02:45 PM -05:00 - // - } - - private static void ShowEquality() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-6, 0, 0)); - Console.WriteLine(date1 == date2); // Displays True - Console.WriteLine(date1 == date3); // Displays False - // - } - - private static void ShowGreaterThan() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-6, 0, 0)); - Console.WriteLine(date1 > date2); // Displays False - Console.WriteLine(date1 > date3); // Displays True - // - } - - private static void ShowGreaterThanOrEqualTo() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date4 = date1; - Console.WriteLine(date1 >= date2); // Displays False - Console.WriteLine(date1 >= date3); // Displays True - Console.WriteLine(date1 >= date4); // Displays True - // - } - - private static void ShowImplicitConversions() - { - // - DateTimeOffset timeWithOffset; - timeWithOffset = new DateTime(2008, 7, 3, 18, 45, 0); - Console.WriteLine(timeWithOffset.ToString()); - - timeWithOffset = DateTime.UtcNow; - Console.WriteLine(timeWithOffset.ToString()); - - timeWithOffset = DateTime.SpecifyKind(DateTime.Now, - DateTimeKind.Unspecified); - Console.WriteLine(timeWithOffset.ToString()); - - timeWithOffset = new DateTime(2008, 7, 1, 2, 30, 0) + - new TimeSpan(1, 0, 0, 0); - Console.WriteLine(timeWithOffset.ToString()); - - timeWithOffset = new DateTime(2008, 1, 1, 2, 30, 0); - Console.WriteLine(timeWithOffset.ToString()); - // The example produces the following output if run on 3/20/2007 - // at 6:25 PM on a computer in the U.S. Pacific Daylight Time zone: - // 7/3/2008 6:45:00 PM -07:00 - // 3/21/2007 1:25:52 AM +00:00 - // 3/20/2007 6:25:52 PM -07:00 - // 7/2/2008 2:30:00 AM -07:00 - // 1/1/2008 2:30:00 AM -08:00 - // - // The last example shows automatic adaption to the U.S. Pacific Time - // for winter dates. - // - } - - private static void ShowInequality() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-6, 0, 0)); - Console.WriteLine(date1 != date2); // Displays False - Console.WriteLine(date1 != date3); // Displays True - // - } - - private static void ShowLessThan() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-8, 0, 0)); - Console.WriteLine(date1 < date2); // Displays False - Console.WriteLine(date1 < date3); // Displays True - // - } - - private static void ShowLessThanOrEqualTo() - { - // - DateTimeOffset date1 = new DateTimeOffset(2007, 6, 3, 14, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date2 = new DateTimeOffset(2007, 6, 3, 15, 45, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset date3 = new DateTimeOffset(date1.DateTime, - new TimeSpan(-6, 0, 0)); - DateTimeOffset date4 = date1; - Console.WriteLine(date1 <= date2); // Displays True - Console.WriteLine(date1 <= date3); // Displays False - Console.WriteLine(date1 <= date4); // Displays True - // - } - - private static void ShowSubtraction1() - { - // - DateTimeOffset firstDate = new DateTimeOffset(2008, 3, 25, 18, 0, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset secondDate = new DateTimeOffset(2008, 3, 25, 18, 0, 0, - new TimeSpan(-5, 0, 0)); - DateTimeOffset thirdDate = new DateTimeOffset(2008, 2, 28, 9, 0, 0, - new TimeSpan(-7, 0, 0)); - TimeSpan difference; - - difference = firstDate - secondDate; - Console.WriteLine("({0}) - ({1}): {2} days, {3}:{4:d2}", - firstDate.ToString(), - secondDate.ToString(), - difference.Days, - difference.Hours, - difference.Minutes); - - difference = firstDate - thirdDate; - Console.WriteLine("({0}) - ({1}): {2} days, {3}:{4:d2}", - firstDate.ToString(), - thirdDate.ToString(), - difference.Days, - difference.Hours, - difference.Minutes); - // The example produces the following output: - // (3/25/2008 6:00:00 PM -07:00) - (3/25/2008 6:00:00 PM -05:00): 0 days, 2:00 - // (3/25/2008 6:00:00 PM -07:00) - (2/28/2008 9:00:00 AM -07:00): 26 days, 9:00 - // - } - - private static void ShowSubtraction2() - { - // - 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 - duration); // Displays 11/25/2007 5:30:00 PM -08:00 - // - } + public static void Main() + { + ShowAddition(); + ShowEquality(); + ShowGreaterThan(); + ShowGreaterThanOrEqualTo(); + ShowImplicitConversions(); + ShowInequality(); + ShowLessThan(); + ShowLessThanOrEqualTo(); + ShowSubtraction1(); + ShowSubtraction2(); + } + + private static void ShowAddition() + { + // + DateTimeOffset date1 = new(2008, 1, 1, 13, 32, 45, + new TimeSpan(-5, 0, 0)); + TimeSpan interval1 = new(202, 3, 30, 0); + TimeSpan interval2 = new(5, 0, 0, 0); + DateTimeOffset date2; + + Console.WriteLine(date1); // Displays 1/1/2008 1:32:45 PM -05:00 + date2 = date1 + interval1; + Console.WriteLine(date2); // Displays 7/21/2008 5:02:45 PM -05:00 + date2 += interval2; + Console.WriteLine(date2); // Displays 7/26/2008 5:02:45 PM -05:00 + // + } + + private static void ShowEquality() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-6, 0, 0)); + Console.WriteLine(date1 == date2); // Displays True + Console.WriteLine(date1 == date3); // Displays False + // + } + + private static void ShowGreaterThan() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-6, 0, 0)); + Console.WriteLine(date1 > date2); // Displays False + Console.WriteLine(date1 > date3); // Displays True + // + } + + private static void ShowGreaterThanOrEqualTo() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date4 = date1; + Console.WriteLine(date1 >= date2); // Displays False + Console.WriteLine(date1 >= date3); // Displays True + Console.WriteLine(date1 >= date4); // Displays True + // + } + + private static void ShowImplicitConversions() + { + // + DateTimeOffset timeWithOffset; + timeWithOffset = new DateTime(2008, 7, 3, 18, 45, 0); + Console.WriteLine(timeWithOffset.ToString()); + + timeWithOffset = DateTime.UtcNow; + Console.WriteLine(timeWithOffset.ToString()); + + timeWithOffset = DateTime.SpecifyKind(DateTime.Now, + DateTimeKind.Unspecified); + Console.WriteLine(timeWithOffset.ToString()); + + timeWithOffset = new DateTime(2008, 7, 1, 2, 30, 0) + + new TimeSpan(1, 0, 0, 0); + Console.WriteLine(timeWithOffset.ToString()); + + timeWithOffset = new DateTime(2008, 1, 1, 2, 30, 0); + Console.WriteLine(timeWithOffset.ToString()); + // The example produces the following output if run on 3/20/2007 + // at 6:25 PM on a computer in the U.S. Pacific Daylight Time zone: + // 7/3/2008 6:45:00 PM -07:00 + // 3/21/2007 1:25:52 AM +00:00 + // 3/20/2007 6:25:52 PM -07:00 + // 7/2/2008 2:30:00 AM -07:00 + // 1/1/2008 2:30:00 AM -08:00 + // + // The last example shows automatic adaption to the U.S. Pacific Time + // for winter dates. + // + } + + private static void ShowInequality() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-6, 0, 0)); + Console.WriteLine(date1 != date2); // Displays False + Console.WriteLine(date1 != date3); // Displays True + // + } + + private static void ShowLessThan() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-8, 0, 0)); + Console.WriteLine(date1 < date2); // Displays False + Console.WriteLine(date1 < date3); // Displays True + // + } + + private static void ShowLessThanOrEqualTo() + { + // + DateTimeOffset date1 = new(2007, 6, 3, 14, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date2 = new(2007, 6, 3, 15, 45, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset date3 = new(date1.DateTime, + new TimeSpan(-6, 0, 0)); + DateTimeOffset date4 = date1; + Console.WriteLine(date1 <= date2); // Displays True + Console.WriteLine(date1 <= date3); // Displays False + Console.WriteLine(date1 <= date4); // Displays True + // + } + + private static void ShowSubtraction1() + { + // + DateTimeOffset firstDate = new(2008, 3, 25, 18, 0, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset secondDate = new(2008, 3, 25, 18, 0, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset thirdDate = new(2008, 2, 28, 9, 0, 0, + new TimeSpan(-7, 0, 0)); + TimeSpan difference; + + difference = firstDate - secondDate; + Console.WriteLine($"({firstDate.ToString()}) - ({secondDate.ToString()}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + + difference = firstDate - thirdDate; + Console.WriteLine($"({firstDate.ToString()}) - ({thirdDate.ToString()}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + // The example produces the following output: + // (3/25/2008 6:00:00 PM -07:00) - (3/25/2008 6:00:00 PM -05:00): 0 days, 2:00 + // (3/25/2008 6:00:00 PM -07:00) - (2/28/2008 9:00:00 AM -07:00): 26 days, 9:00 + // + } + + private static void ShowSubtraction2() + { + // + DateTimeOffset offsetDate = new(2007, 12, 3, 11, 30, 0, + new TimeSpan(-8, 0, 0)); + TimeSpan duration = new(7, 18, 0, 0); + Console.WriteLine(offsetDate - duration); // Displays 11/25/2007 5:30:00 PM -08:00 + // + } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctor2a.cs b/snippets/csharp/System/Decimal/.ctor/ctor2a.cs index adfe65b8362..0198976d61a 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctor2a.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctor2a.cs @@ -3,20 +3,21 @@ public class Example { - public static void Main() - { - Decimal[] values = { 1234.96m, -1234.96m }; - foreach (var value in values) { - int[] parts = Decimal.GetBits(value); - bool sign = (parts[3] & 0x80000000) != 0; + public static void Main() + { + decimal[] values = { 1234.96m, -1234.96m }; + foreach (decimal value in values) + { + int[] parts = decimal.GetBits(value); + bool sign = (parts[3] & 0x80000000) != 0; - byte scale = (byte) ((parts[3] >> 16) & 0x7F); - Decimal newValue = new Decimal(parts[0], parts[1], parts[2], sign, scale); - Console.WriteLine("{0} --> {1}", value, newValue); - } - } + byte scale = (byte)((parts[3] >> 16) & 0x7F); + decimal newValue = new(parts[0], parts[1], parts[2], sign, scale); + Console.WriteLine($"{value} --> {newValue}"); + } + } } // The example displays the following output: // 1234.96 --> 1234.96 // -1234.96 --> -1234.96 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Decimal/.ctor/ctordo.cs b/snippets/csharp/System/Decimal/.ctor/ctordo.cs index 18e4b009c1a..d4538b001a6 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctordo.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctordo.cs @@ -5,58 +5,55 @@ class DecimalCtorDoDemo { // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' )+1 ); + exceptionType.LastIndexOf('.') + 1); } // Create a decimal object and display its value. - public static void CreateDecimal( double value, string valToStr ) + public static void CreateDecimal(double value, string valToStr) { // Format and display the constructor. - Console.Write( "{0,-34}", - String.Format( "decimal( {0} )", valToStr ) ); + Console.Write($"{string.Format("decimal( {0} )", valToStr),-34}"); try { // Construct the decimal value. - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Display the value if it was created successfully. - Console.WriteLine( "{0,31}", decimalNum ); + Console.WriteLine($"{decimalNum,31}"); } - catch( Exception ex ) + catch (Exception ex) { // Display the exception type if an exception was thrown. - Console.WriteLine( "{0,31}", GetExceptionType( ex ) ); + Console.WriteLine($"{GetExceptionType(ex),31}"); } } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( double ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-34}{1,31}", "Constructor", - "Value or Exception" ); - Console.WriteLine( "{0,-34}{1,31}", "-----------", - "------------------" ); + Console.WriteLine("This example of the decimal( double ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-34}{"Value or Exception",31}"); + Console.WriteLine($"{"-----------",-34}{"------------------",31}"); // Construct decimal objects from double values. - CreateDecimal( 1.23456789E+5, "1.23456789E+5" ); - CreateDecimal( 1.234567890123E+15, "1.234567890123E+15" ); - CreateDecimal( 1.2345678901234567E+25, - "1.2345678901234567E+25" ); - CreateDecimal( 1.2345678901234567E+35, - "1.2345678901234567E+35" ); - CreateDecimal( 1.23456789E-5, "1.23456789E-5" ); - CreateDecimal( 1.234567890123E-15, "1.234567890123E-15" ); - CreateDecimal( 1.2345678901234567E-25, - "1.2345678901234567E-25" ); - CreateDecimal( 1.2345678901234567E-35, - "1.2345678901234567E-35" ); - CreateDecimal( 1.0 / 7.0, "1.0 / 7.0" ); + CreateDecimal(1.23456789E+5, "1.23456789E+5"); + CreateDecimal(1.234567890123E+15, "1.234567890123E+15"); + CreateDecimal(1.2345678901234567E+25, + "1.2345678901234567E+25"); + CreateDecimal(1.2345678901234567E+35, + "1.2345678901234567E+35"); + CreateDecimal(1.23456789E-5, "1.23456789E-5"); + CreateDecimal(1.234567890123E-15, "1.234567890123E-15"); + CreateDecimal(1.2345678901234567E-25, + "1.2345678901234567E-25"); + CreateDecimal(1.2345678901234567E-35, + "1.2345678901234567E-35"); + CreateDecimal(1.0 / 7.0, "1.0 / 7.0"); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctori.cs b/snippets/csharp/System/Decimal/.ctor/ctori.cs index 3220dbbaac9..814c4e52f63 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctori.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctori.cs @@ -5,32 +5,32 @@ class DecimalCtorIDemo { // Create a decimal object and display its value. - public static void CreateDecimal( int value, string valToStr ) + public static void CreateDecimal(int value, string valToStr) { - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Format the constructor for display. - string ctor = String.Format( "decimal( {0} )", valToStr ); + string ctor = $"decimal( {valToStr} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-30}{1,16}", ctor, decimalNum ); + Console.WriteLine($"{ctor,-30}{decimalNum,16}"); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( int ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-30}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-30}{1,16}", "-----------", "-----" ); + Console.WriteLine("This example of the decimal( int ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-30}{"Value",16}"); + Console.WriteLine($"{"-----------",-30}{"-----",16}"); // Construct decimal objects from int values. - CreateDecimal( int.MinValue, "int.MinValue" ); - CreateDecimal( int.MaxValue, "int.MaxValue" ); - CreateDecimal( 0, "0" ); - CreateDecimal( 999999999, "999999999" ); - CreateDecimal( 0x40000000, "0x40000000" ); - CreateDecimal( unchecked( (int)0xC0000000 ), - "(int)0xC0000000" ); + CreateDecimal(int.MinValue, "int.MinValue"); + CreateDecimal(int.MaxValue, "int.MaxValue"); + CreateDecimal(0, "0"); + CreateDecimal(999999999, "999999999"); + CreateDecimal(0x40000000, "0x40000000"); + CreateDecimal(unchecked((int)0xC0000000), + "(int)0xC0000000"); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctoriarr.cs b/snippets/csharp/System/Decimal/.ctor/ctoriarr.cs index 46b6fce8a50..5607512e5b4 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctoriarr.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctoriarr.cs @@ -5,82 +5,78 @@ class DecimalCtorIArrDemo { // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Create a decimal object and display its value. - public static void CreateDecimal( int[ ] bits ) + public static void CreateDecimal(int[] bits) { // Format the constructor for display. - string ctor = String.Format( - "decimal( {{ 0x{0:X}", bits[ 0 ] ); + string ctor = $"decimal( {{ 0x{bits[0]:X}"; string valOrExc; - for( int index = 1; index < bits.Length; index++ ) - ctor += String.Format( ", 0x{0:X}", bits[ index ] ); + for (int index = 1; index < bits.Length; index++) + ctor += $", 0x{bits[index]:X}"; ctor += " } )"; try { // Construct the decimal value. - decimal decimalNum = new decimal( bits ); + decimal decimalNum = new(bits); // Format the decimal value for display. - valOrExc = decimalNum.ToString( ); + valOrExc = decimalNum.ToString(); } - catch( Exception ex ) + catch (Exception ex) { // Save the exception type if an exception was thrown. - valOrExc = GetExceptionType( ex ); + valOrExc = GetExceptionType(ex); } // Display the constructor and decimal value or exception. int ctorLen = 76 - valOrExc.Length; // Display the data on one line if it will fit. - if( ctorLen > ctor.Length ) - Console.WriteLine( "{0}{1}", ctor.PadRight( ctorLen ), - valOrExc ); + if (ctorLen > ctor.Length) + Console.WriteLine($"{ctor.PadRight(ctorLen)}{valOrExc}"); // Otherwise, display the data on two lines. else { - Console.WriteLine( "{0}", ctor ); - Console.WriteLine( "{0,76}", valOrExc ); + Console.WriteLine($"{ctor}"); + Console.WriteLine($"{valOrExc,76}"); } } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the decimal( int[ ] ) constructor " + - "\ngenerates the following output.\n" ); - Console.WriteLine( "{0,-38}{1,38}", "Constructor", - "Value or Exception" ); - Console.WriteLine( "{0,-38}{1,38}", "-----------", - "------------------" ); + "\ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-38}{"Value or Exception",38}"); + Console.WriteLine($"{"-----------",-38}{"------------------",38}"); // Construct decimal objects from integer arrays. - CreateDecimal( new int[ ] { 0, 0, 0, 0 } ); - CreateDecimal( new int[ ] { 0, 0, 0 } ); - CreateDecimal( new int[ ] { 0, 0, 0, 0, 0 } ); - CreateDecimal( new int[ ] { 1000000000, 0, 0, 0 } ); - CreateDecimal( new int[ ] { 0, 1000000000, 0, 0 } ); - CreateDecimal( new int[ ] { 0, 0, 1000000000, 0 } ); - CreateDecimal( new int[ ] { 0, 0, 0, 1000000000 } ); - CreateDecimal( new int[ ] { -1, -1, -1, 0 } ); - CreateDecimal( new int[ ] - { -1, -1, -1, unchecked( (int)0x80000000 ) } ); - CreateDecimal( new int[ ] { -1, 0, 0, 0x100000 } ); - CreateDecimal( new int[ ] { -1, 0, 0, 0x1C0000 } ); - CreateDecimal( new int[ ] { -1, 0, 0, 0x1D0000 } ); - CreateDecimal( new int[ ] { -1, 0, 0, 0x1C0001 } ); - CreateDecimal( new int[ ] - { 0xF0000, 0xF0000, 0xF0000, 0xF0000 } ); + CreateDecimal(new int[] { 0, 0, 0, 0 }); + CreateDecimal(new int[] { 0, 0, 0 }); + CreateDecimal(new int[] { 0, 0, 0, 0, 0 }); + CreateDecimal(new int[] { 1000000000, 0, 0, 0 }); + CreateDecimal(new int[] { 0, 1000000000, 0, 0 }); + CreateDecimal(new int[] { 0, 0, 1000000000, 0 }); + CreateDecimal(new int[] { 0, 0, 0, 1000000000 }); + CreateDecimal(new int[] { -1, -1, -1, 0 }); + CreateDecimal(new int[] + { -1, -1, -1, unchecked( (int)0x80000000 ) }); + CreateDecimal(new int[] { -1, 0, 0, 0x100000 }); + CreateDecimal(new int[] { -1, 0, 0, 0x1C0000 }); + CreateDecimal(new int[] { -1, 0, 0, 0x1D0000 }); + CreateDecimal(new int[] { -1, 0, 0, 0x1C0001 }); + CreateDecimal(new int[] + { 0xF0000, 0xF0000, 0xF0000, 0xF0000 }); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctoriiibby.cs b/snippets/csharp/System/Decimal/.ctor/ctoriiibby.cs index 45c1baf0a7b..c44bba36b75 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctoriiibby.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctoriiibby.cs @@ -5,81 +5,76 @@ class DecimalCtorIIIBByDemo { // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Create a decimal object and display its value. - public static void CreateDecimal( int low, int mid, int high, - bool isNeg, byte scale ) + public static void CreateDecimal(int low, int mid, int high, + bool isNeg, byte scale) { // Format the constructor for display. - string ctor = String.Format( - "decimal( {0}, {1}, {2}, {3}, {4} )", - low, mid, high, isNeg, scale ); + string ctor = $"decimal( {low}, {mid}, {high}, {isNeg}, {scale} )"; string valOrExc; try { // Construct the decimal value. - decimal decimalNum = new decimal( - low, mid, high, isNeg, scale ); + decimal decimalNum = new( + low, mid, high, isNeg, scale); // Format and save the decimal value. - valOrExc = decimalNum.ToString( ); + valOrExc = decimalNum.ToString(); } - catch( Exception ex ) + catch (Exception ex) { // Save the exception type if an exception was thrown. - valOrExc = GetExceptionType( ex ); + valOrExc = GetExceptionType(ex); } // Display the constructor and decimal value or exception. int ctorLen = 76 - valOrExc.Length; // Display the data on one line if it will fit. - if ( ctorLen > ctor.Length ) - Console.WriteLine( "{0}{1}", ctor.PadRight( ctorLen ), - valOrExc ); + if (ctorLen > ctor.Length) + Console.WriteLine($"{ctor.PadRight(ctorLen)}{valOrExc}"); // Otherwise, display the data on two lines. else { - Console.WriteLine( "{0}", ctor ); - Console.WriteLine( "{0,76}", valOrExc ); + Console.WriteLine($"{ctor}"); + Console.WriteLine($"{valOrExc,76}"); } } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( int, int, " + + Console.WriteLine("This example of the decimal( int, int, " + "int, bool, byte ) \nconstructor " + - "generates the following output.\n" ); - Console.WriteLine( "{0,-38}{1,38}", "Constructor", - "Value or Exception" ); - Console.WriteLine( "{0,-38}{1,38}", "-----------", - "------------------" ); + "generates the following output.\n"); + Console.WriteLine($"{"Constructor",-38}{"Value or Exception",38}"); + Console.WriteLine($"{"-----------",-38}{"------------------",38}"); // Construct decimal objects from the component fields. - CreateDecimal( 0, 0, 0, false, 0 ); - CreateDecimal( 0, 0, 0, false, 27 ); - CreateDecimal( 0, 0, 0, true, 0 ); - CreateDecimal( 1000000000, 0, 0, false, 0 ); - CreateDecimal( 0, 1000000000, 0, false, 0 ); - CreateDecimal( 0, 0, 1000000000, false, 0 ); - CreateDecimal( 1000000000, 1000000000, 1000000000, false, 0 ); - CreateDecimal( -1, -1, -1, false, 0 ); - CreateDecimal( -1, -1, -1, true, 0 ); - CreateDecimal( -1, -1, -1, false, 15 ); - CreateDecimal( -1, -1, -1, false, 28 ); - CreateDecimal( -1, -1, -1, false, 29 ); - CreateDecimal( int.MaxValue, 0, 0, false, 18 ); - CreateDecimal( int.MaxValue, 0, 0, false, 28 ); - CreateDecimal( int.MaxValue, 0, 0, true, 28 ); + CreateDecimal(0, 0, 0, false, 0); + CreateDecimal(0, 0, 0, false, 27); + CreateDecimal(0, 0, 0, true, 0); + CreateDecimal(1000000000, 0, 0, false, 0); + CreateDecimal(0, 1000000000, 0, false, 0); + CreateDecimal(0, 0, 1000000000, false, 0); + CreateDecimal(1000000000, 1000000000, 1000000000, false, 0); + CreateDecimal(-1, -1, -1, false, 0); + CreateDecimal(-1, -1, -1, true, 0); + CreateDecimal(-1, -1, -1, false, 15); + CreateDecimal(-1, -1, -1, false, 28); + CreateDecimal(-1, -1, -1, false, 29); + CreateDecimal(int.MaxValue, 0, 0, false, 18); + CreateDecimal(int.MaxValue, 0, 0, false, 28); + CreateDecimal(int.MaxValue, 0, 0, true, 28); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctorl.cs b/snippets/csharp/System/Decimal/.ctor/ctorl.cs index b53fc04ec0f..ed57bd1ec6c 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctorl.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctorl.cs @@ -5,32 +5,32 @@ class DecimalCtorLDemo { // Create a decimal object and display its value. - public static void CreateDecimal( long value, string valToStr ) + public static void CreateDecimal(long value, string valToStr) { - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Format the constructor for display. - string ctor = String.Format( "decimal( {0} )", valToStr ); + string ctor = $"decimal( {valToStr} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-35}{1,22}", ctor, decimalNum ); + Console.WriteLine($"{ctor,-35}{decimalNum,22}"); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( long ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-35}{1,22}", "Constructor", "Value" ); - Console.WriteLine( "{0,-35}{1,22}", "-----------", "-----" ); + Console.WriteLine("This example of the decimal( long ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-35}{"Value",22}"); + Console.WriteLine($"{"-----------",-35}{"-----",22}"); // Construct decimal objects from long values. - CreateDecimal( long.MinValue, "long.MinValue" ); - CreateDecimal( long.MaxValue, "long.MaxValue" ); - CreateDecimal( 0L, "0L" ); - CreateDecimal( 999999999999999999, "999999999999999999" ); - CreateDecimal( 0x2000000000000000, "0x2000000000000000" ); - CreateDecimal( unchecked( (long)0xE000000000000000 ), - "(long)0xE000000000000000" ); + CreateDecimal(long.MinValue, "long.MinValue"); + CreateDecimal(long.MaxValue, "long.MaxValue"); + CreateDecimal(0L, "0L"); + CreateDecimal(999999999999999999, "999999999999999999"); + CreateDecimal(0x2000000000000000, "0x2000000000000000"); + CreateDecimal(unchecked((long)0xE000000000000000), + "(long)0xE000000000000000"); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctors.cs b/snippets/csharp/System/Decimal/.ctor/ctors.cs index 9a81577492d..108aeb48f2c 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctors.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctors.cs @@ -5,55 +5,52 @@ class DecimalCtorSDemo { // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Create a decimal object and display its value. - public static void CreateDecimal( float value, string valToStr ) + public static void CreateDecimal(float value, string valToStr) { // Format and display the constructor. - Console.Write( "{0,-27}", - String.Format( "decimal( {0} )", valToStr ) ); + Console.Write($"{string.Format("decimal( {0} )", valToStr),-27}"); try { // Construct the decimal value. - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Display the value if it was created successfully. - Console.WriteLine( "{0,31}", decimalNum ); + Console.WriteLine($"{decimalNum,31}"); } - catch( Exception ex ) + catch (Exception ex) { // Display the exception type if an exception was thrown. - Console.WriteLine( "{0,31}", GetExceptionType( ex ) ); + Console.WriteLine($"{GetExceptionType(ex),31}"); } } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( float ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-27}{1,31}", "Constructor", - "Value or Exception" ); - Console.WriteLine( "{0,-27}{1,31}", "-----------", - "------------------" ); + Console.WriteLine("This example of the decimal( float ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-27}{"Value or Exception",31}"); + Console.WriteLine($"{"-----------",-27}{"------------------",31}"); // Construct decimal objects from float values. - CreateDecimal( 1.2345E+5F, "1.2345E+5F" ); - CreateDecimal( 1.234567E+15F, "1.234567E+15F" ); - CreateDecimal( 1.23456789E+25F, "1.23456789E+25F" ); - CreateDecimal( 1.23456789E+35F, "1.23456789E+35F" ); - CreateDecimal( 1.2345E-5F, "1.2345E-5F" ); - CreateDecimal( 1.234567E-15F, "1.234567E-15F" ); - CreateDecimal( 1.23456789E-25F, "1.23456789E-25F" ); - CreateDecimal( 1.23456789E-35F, "1.23456789E-35F" ); - CreateDecimal( 1.0F / 7.0F, "1.0F / 7.0F" ); + CreateDecimal(1.2345E+5F, "1.2345E+5F"); + CreateDecimal(1.234567E+15F, "1.234567E+15F"); + CreateDecimal(1.23456789E+25F, "1.23456789E+25F"); + CreateDecimal(1.23456789E+35F, "1.23456789E+35F"); + CreateDecimal(1.2345E-5F, "1.2345E-5F"); + CreateDecimal(1.234567E-15F, "1.234567E-15F"); + CreateDecimal(1.23456789E-25F, "1.23456789E-25F"); + CreateDecimal(1.23456789E-35F, "1.23456789E-35F"); + CreateDecimal(1.0F / 7.0F, "1.0F / 7.0F"); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctorui.cs b/snippets/csharp/System/Decimal/.ctor/ctorui.cs index 5e26b4ef0da..d88d26323af 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctorui.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctorui.cs @@ -5,31 +5,31 @@ class DecimalCtorUIDemo { // Create a decimal object and display its value. - public static void CreateDecimal( uint value, string valToStr ) + public static void CreateDecimal(uint value, string valToStr) { - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Format the constructor for display. - string ctor = String.Format( "decimal( {0} )", valToStr ); + string ctor = $"decimal( {valToStr} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-33}{1,16}", ctor, decimalNum ); + Console.WriteLine($"{ctor,-33}{decimalNum,16}"); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( uint ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-33}{1,16}", "Constructor", "Value" ); - Console.WriteLine( "{0,-33}{1,16}", "-----------", "-----" ); + Console.WriteLine("This example of the decimal( uint ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-33}{"Value",16}"); + Console.WriteLine($"{"-----------",-33}{"-----",16}"); // Construct decimal objects from uint values. - CreateDecimal( uint.MinValue, "uint.MinValue" ); - CreateDecimal( uint.MaxValue, "uint.MaxValue" ); - CreateDecimal( (uint)int.MaxValue, "(uint)int.MaxValue" ); - CreateDecimal( 999999999U, "999999999U" ); - CreateDecimal( 0x40000000U, "0x40000000U" ); - CreateDecimal( 0xC0000000, "0xC0000000" ); + CreateDecimal(uint.MinValue, "uint.MinValue"); + CreateDecimal(uint.MaxValue, "uint.MaxValue"); + CreateDecimal((uint)int.MaxValue, "(uint)int.MaxValue"); + CreateDecimal(999999999U, "999999999U"); + CreateDecimal(0x40000000U, "0x40000000U"); + CreateDecimal(0xC0000000, "0xC0000000"); } } diff --git a/snippets/csharp/System/Decimal/.ctor/ctorul.cs b/snippets/csharp/System/Decimal/.ctor/ctorul.cs index b0910811c46..d9358682a0c 100644 --- a/snippets/csharp/System/Decimal/.ctor/ctorul.cs +++ b/snippets/csharp/System/Decimal/.ctor/ctorul.cs @@ -5,31 +5,31 @@ class DecimalCtorLDemo { // Create a decimal object and display its value. - public static void CreateDecimal( ulong value, string valToStr ) + public static void CreateDecimal(ulong value, string valToStr) { - decimal decimalNum = new decimal( value ); + decimal decimalNum = new(value); // Format the constructor for display. - string ctor = String.Format( "decimal( {0} )", valToStr ); + string ctor = $"decimal( {valToStr} )"; // Display the constructor and its value. - Console.WriteLine( "{0,-35}{1,22}", ctor, decimalNum ); + Console.WriteLine($"{ctor,-35}{decimalNum,22}"); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the decimal( ulong ) " + - "constructor \ngenerates the following output.\n" ); - Console.WriteLine( "{0,-35}{1,22}", "Constructor", "Value" ); - Console.WriteLine( "{0,-35}{1,22}", "-----------", "-----" ); + Console.WriteLine("This example of the decimal( ulong ) " + + "constructor \ngenerates the following output.\n"); + Console.WriteLine($"{"Constructor",-35}{"Value",22}"); + Console.WriteLine($"{"-----------",-35}{"-----",22}"); // Construct decimal objects from ulong values. - CreateDecimal( ulong.MinValue, "ulong.MinValue" ); - CreateDecimal( ulong.MaxValue, "ulong.MaxValue" ); - CreateDecimal( long.MaxValue, "long.MaxValue" ); - CreateDecimal( 999999999999999999, "999999999999999999" ); - CreateDecimal( 0x2000000000000000, "0x2000000000000000" ); - CreateDecimal( 0xE000000000000000, "0xE000000000000000" ); + CreateDecimal(ulong.MinValue, "ulong.MinValue"); + CreateDecimal(ulong.MaxValue, "ulong.MaxValue"); + CreateDecimal(long.MaxValue, "long.MaxValue"); + CreateDecimal(999999999999999999, "999999999999999999"); + CreateDecimal(0x2000000000000000, "0x2000000000000000"); + CreateDecimal(0xE000000000000000, "0xE000000000000000"); } } diff --git a/snippets/csharp/System/Decimal/Ceiling/ceiling1.cs b/snippets/csharp/System/Decimal/Ceiling/ceiling1.cs index b0f8b973d80..548fd35098a 100644 --- a/snippets/csharp/System/Decimal/Ceiling/ceiling1.cs +++ b/snippets/csharp/System/Decimal/Ceiling/ceiling1.cs @@ -3,16 +3,14 @@ public class Example { - public static void Main() - { - decimal[] values = {12.6m, 12.1m, 9.5m, 8.16m, .1m, -.1m, -1.1m, + public static void Main() + { + decimal[] values = {12.6m, 12.1m, 9.5m, 8.16m, .1m, -.1m, -1.1m, -1.9m, -3.9m}; - Console.WriteLine("{0,-8} {1,10} {2,10}\n", - "Value", "Ceiling", "Floor"); - foreach (decimal value in values) - Console.WriteLine("{0,-8} {1,10} {2,10}", value, - Decimal.Ceiling(value), Decimal.Floor(value)); - } + Console.WriteLine($"{"Value",-8} {"Ceiling",10} {"Floor",10}\n"); + foreach (decimal value in values) + Console.WriteLine($"{value,-8} {decimal.Ceiling(value),10} {decimal.Floor(value),10}"); + } } // The example displays the following output: // Value Ceiling Floor diff --git a/snippets/csharp/System/Decimal/Compare/Compare1.cs b/snippets/csharp/System/Decimal/Compare/Compare1.cs index 2161ce7a08d..eb41e1ac199 100644 --- a/snippets/csharp/System/Decimal/Compare/Compare1.cs +++ b/snippets/csharp/System/Decimal/Compare/Compare1.cs @@ -2,27 +2,27 @@ using System; public enum Relationship -{ LessThan = -1, Equals = 0, GreaterThan = 1 } +{ LessThan = -1, Equals = 0, GreaterThan = 1 } public class Example { - public static void Main() - { - decimal value1 = Decimal.MaxValue; - decimal value2 = value1 - .01m; - Console.WriteLine("{0} {2} {1}", value1, value2, - (Relationship) Decimal.Compare(value1, value2)); + public static void Main() + { + decimal value1 = decimal.MaxValue; + decimal value2 = value1 - .01m; + Console.WriteLine("{0} {2} {1}", value1, value2, + (Relationship)decimal.Compare(value1, value2)); - value2 = value1 / 12m - .1m; - value1 = value1 / 12m; - Console.WriteLine("{0} {2} {1}", value1, value2, - (Relationship) Decimal.Compare(value1, value2)); + value2 = value1 / 12m - .1m; + value1 = value1 / 12m; + Console.WriteLine("{0} {2} {1}", value1, value2, + (Relationship)decimal.Compare(value1, value2)); - value1 = value1 - .2m; - value2 = value2 + .1m; - Console.WriteLine("{0} {2} {1}", value1, value2, - (Relationship) Decimal.Compare(value1, value2)); - } + value1 = value1 - .2m; + value2 = value2 + .1m; + Console.WriteLine("{0} {2} {1}", value1, value2, + (Relationship)decimal.Compare(value1, value2)); + } } // The example displays the following output: // 79228162514264337593543950335 Equals 79228162514264337593543950335 diff --git a/snippets/csharp/System/Decimal/CompareTo/comp_equal.cs b/snippets/csharp/System/Decimal/CompareTo/comp_equal.cs index 9094b319193..4683a46c019 100644 --- a/snippets/csharp/System/Decimal/CompareTo/comp_equal.cs +++ b/snippets/csharp/System/Decimal/CompareTo/comp_equal.cs @@ -7,41 +7,41 @@ class DecCompareEqualsDemo const string dataFmt = "{0,-45}{1}"; // Compare decimal parameters, and display them with the results. - public static void CompareDecimals( decimal Left, decimal Right, - string RightText ) + public static void CompareDecimals(decimal Left, decimal Right, + string RightText) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "Right: "+RightText, Right ); - Console.WriteLine( dataFmt, "decimal.Equals( Left, Right )", - Decimal.Equals( Left, Right ) ); - Console.WriteLine( dataFmt, "decimal.Compare( Left, Right )", - Decimal.Compare( Left, Right ) ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "Right: " + RightText, Right); + Console.WriteLine(dataFmt, "decimal.Equals( Left, Right )", + decimal.Equals(Left, Right)); + Console.WriteLine(dataFmt, "decimal.Compare( Left, Right )", + decimal.Compare(Left, Right)); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.Equals( decimal, decimal ) and \n" + "decimal.Compare( decimal, decimal ) methods " + "generates the \nfollowing output. It creates several " + "different decimal \nvalues and compares them with " + - "the following reference value.\n" ); + "the following reference value.\n"); // Create a reference decimal value. - decimal Left = new decimal( 123.456 ); + decimal Left = new(123.456); - Console.WriteLine( dataFmt, "Left: decimal( 123.456 )", - Left ); + Console.WriteLine(dataFmt, "Left: decimal( 123.456 )", + Left); // Create decimal values to compare with the reference. - CompareDecimals( Left, new decimal( 1.2345600E+2 ), - "decimal( 1.2345600E+2 )" ); - CompareDecimals( Left, 123.4561M, "123.4561M" ); - CompareDecimals( Left, 123.4559M, "123.4559M" ); - CompareDecimals( Left, 123.456000M, "123.456000M" ); - CompareDecimals( Left, - new decimal( 123456000, 0, 0, false, 6 ), - "decimal( 123456000, 0, 0, false, 6 )" ); + CompareDecimals(Left, new decimal(1.2345600E+2), + "decimal( 1.2345600E+2 )"); + CompareDecimals(Left, 123.4561M, "123.4561M"); + CompareDecimals(Left, 123.4559M, "123.4559M"); + CompareDecimals(Left, 123.456000M, "123.456000M"); + CompareDecimals(Left, + new decimal(123456000, 0, 0, false, 6), + "decimal( 123456000, 0, 0, false, 6 )"); } } diff --git a/snippets/csharp/System/Decimal/CompareTo/cto_eq_obj.cs b/snippets/csharp/System/Decimal/CompareTo/cto_eq_obj.cs index 1c2bbb72df9..46a1e566454 100644 --- a/snippets/csharp/System/Decimal/CompareTo/cto_eq_obj.cs +++ b/snippets/csharp/System/Decimal/CompareTo/cto_eq_obj.cs @@ -6,62 +6,59 @@ class DecCompToEqualsObjDemo { // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Compare the decimal to the object parameters, // and display the object parameters with the results. - public static void CompDecimalToObject( decimal Left, - object Right, string RightText ) + public static void CompDecimalToObject(decimal Left, + object Right, string RightText) { - Console.WriteLine( "{0,-46}{1}", "object: "+RightText, - Right ); - Console.WriteLine( "{0,-46}{1}", "Left.Equals( object )", - Left.Equals( Right ) ); - Console.Write( "{0,-46}", "Left.CompareTo( object )" ); + Console.WriteLine($"{"object: " + RightText,-46}{Right}"); + Console.WriteLine($"{"Left.Equals( object )",-46}{Left.Equals(Right)}"); + Console.Write($"{"Left.CompareTo( object )",-46}"); try { // Catch the exception if CompareTo( ) throws one. - Console.WriteLine( "{0}\n", Left.CompareTo( Right ) ); + Console.WriteLine($"{Left.CompareTo(Right)}\n"); } - catch( Exception ex ) + catch (Exception ex) { - Console.WriteLine( "{0}\n", GetExceptionType( ex ) ); + Console.WriteLine($"{GetExceptionType(ex)}\n"); } } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the decimal.Equals( object ) and \n" + "decimal.CompareTo( object ) methods generates the \n" + "following output. It creates several different " + "decimal \nvalues and compares them with the following " + - "reference value.\n" ); + "reference value.\n"); // Create a reference decimal value. - decimal Left = new decimal( 987.654 ); + decimal Left = new(987.654); - Console.WriteLine( "{0,-46}{1}\n", - "Left: decimal( 987.654 )", Left ); + Console.WriteLine($"{"Left: decimal( 987.654 )",-46}{Left}\n"); // Create objects to compare with the reference. - CompDecimalToObject( Left, new decimal( 9.8765400E+2 ), - "decimal( 9.8765400E+2 )" ); - CompDecimalToObject( Left, 987.6541M, "987.6541D" ); - CompDecimalToObject( Left, 987.6539M, "987.6539D" ); - CompDecimalToObject( Left, - new decimal( 987654000, 0, 0, false, 6 ), - "decimal( 987654000, 0, 0, false, 6 )" ); - CompDecimalToObject( Left, 9.8765400E+2, - "Double 9.8765400E+2" ); - CompDecimalToObject( Left, "987.654", "String \"987.654\"" ); + CompDecimalToObject(Left, new decimal(9.8765400E+2), + "decimal( 9.8765400E+2 )"); + CompDecimalToObject(Left, 987.6541M, "987.6541D"); + CompDecimalToObject(Left, 987.6539M, "987.6539D"); + CompDecimalToObject(Left, + new decimal(987654000, 0, 0, false, 6), + "decimal( 987654000, 0, 0, false, 6 )"); + CompDecimalToObject(Left, 9.8765400E+2, + "Double 9.8765400E+2"); + CompDecimalToObject(Left, "987.654", "String \"987.654\""); } } diff --git a/snippets/csharp/System/Decimal/Divide/Divide1.cs b/snippets/csharp/System/Decimal/Divide/Divide1.cs index dd71569893b..2d6a1ce7211 100644 --- a/snippets/csharp/System/Decimal/Divide/Divide1.cs +++ b/snippets/csharp/System/Decimal/Divide/Divide1.cs @@ -3,17 +3,17 @@ public class Example { - public static void Main() - { - // Divide a series of numbers by 22.1 - Decimal dividend = 1230.0m; - Decimal divisor = 22.1m; - for (int ctr = 0; ctr <= 10; ctr++) { - Console.WriteLine("{0:N1} / {1:N1} = {2:N4}", dividend, divisor, - Decimal.Divide(dividend, divisor)); - dividend += .1m; - } - } + public static void Main() + { + // Divide a series of numbers by 22.1 + decimal dividend = 1230.0m; + decimal divisor = 22.1m; + for (int ctr = 0; ctr <= 10; ctr++) + { + Console.WriteLine($"{dividend:N1} / {divisor:N1} = {decimal.Divide(dividend, divisor):N4}"); + dividend += .1m; + } + } } // The example displays the following output: // 1,230.0 / 22.1 = 55.6561 diff --git a/snippets/csharp/System/Decimal/Equals/equalsoverl.cs b/snippets/csharp/System/Decimal/Equals/equalsoverl.cs index d2dbb12265c..7afa6be18b2 100644 --- a/snippets/csharp/System/Decimal/Equals/equalsoverl.cs +++ b/snippets/csharp/System/Decimal/Equals/equalsoverl.cs @@ -3,58 +3,52 @@ public class Example { - static decimal value = 112m; + static decimal value = 112m; - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,17}", value.Equals(byte1)); - TestObjectForEquality(byte1); + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),17}"); + TestObjectForEquality(byte1); - short short1 = 112; - Console.WriteLine("value = short1: {0,17}", value.Equals(short1)); - TestObjectForEquality(short1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),17}"); + TestObjectForEquality(short1); - int int1 = 112; - Console.WriteLine("value = int1: {0,19}", value.Equals(int1)); - TestObjectForEquality(int1); + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),19}"); + TestObjectForEquality(int1); - long long1 = 112; - Console.WriteLine("value = long1: {0,18}", value.Equals(long1)); - TestObjectForEquality(long1); + long long1 = 112; + Console.WriteLine($"value = long1: {value.Equals(long1),18}"); + TestObjectForEquality(long1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,17}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),17}"); + TestObjectForEquality(sbyte1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,17}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),17}"); + TestObjectForEquality(ushort1); - uint uint1 = 112; - Console.WriteLine("value = uint1: {0,19}", value.Equals(uint1)); - TestObjectForEquality(uint1); + uint uint1 = 112; + Console.WriteLine($"value = uint1: {value.Equals(uint1),19}"); + TestObjectForEquality(uint1); - ulong ulong1 = 112; - Console.WriteLine("value = ulong1: {0,18}", value.Equals(ulong1)); - TestObjectForEquality(ulong1); + ulong ulong1 = 112; + Console.WriteLine($"value = ulong1: {value.Equals(ulong1),18}"); + TestObjectForEquality(ulong1); - float sng1 = 112; - Console.WriteLine("value = sng1: {0,21}", value.Equals(sng1)); - TestObjectForEquality(sng1); + float sng1 = 112; + Console.WriteLine($"value = sng1: {value.Equals(sng1),21}"); + TestObjectForEquality(sng1); - double dbl1 = 112; - Console.WriteLine("value = dbl1: {0,21}", value.Equals(dbl1)); - TestObjectForEquality(dbl1); - } + double dbl1 = 112; + Console.WriteLine($"value = dbl1: {value.Equals(dbl1),21}"); + TestObjectForEquality(dbl1); + } - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/Decimal/FromOACurrency/fromoacurrency.cs b/snippets/csharp/System/Decimal/FromOACurrency/fromoacurrency.cs index cc6e03b09a5..d92858d8618 100644 --- a/snippets/csharp/System/Decimal/FromOACurrency/fromoacurrency.cs +++ b/snippets/csharp/System/Decimal/FromOACurrency/fromoacurrency.cs @@ -7,36 +7,36 @@ class DecimalFromOACurrencyDemo const string dataFmt = "{0,21}{1,25}"; // Display the decimal.FromOACurrency parameter and decimal result. - public static void ShowDecimalFromOACurrency( long Argument ) + public static void ShowDecimalFromOACurrency(long Argument) { - decimal decCurrency = decimal.FromOACurrency( Argument ); + decimal decCurrency = decimal.FromOACurrency(Argument); - Console.WriteLine( dataFmt, Argument, decCurrency ); + Console.WriteLine(dataFmt, Argument, decCurrency); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.FromOACurrency( ) method generates \nthe " + "following output. It displays the OLE Automation " + "Currency \nvalue as a long and the result as a " + - "decimal.\n" ); - Console.WriteLine( dataFmt, "OA Currency", "Decimal Value" ); - Console.WriteLine( dataFmt, "-----------", "-------------" ); + "decimal.\n"); + Console.WriteLine(dataFmt, "OA Currency", "Decimal Value"); + Console.WriteLine(dataFmt, "-----------", "-------------"); // Convert OLE Automation Currency values to decimal objects. - ShowDecimalFromOACurrency( 0L ); - ShowDecimalFromOACurrency( 1L ); - ShowDecimalFromOACurrency( 100000L ); - ShowDecimalFromOACurrency( 100000000000L ); - ShowDecimalFromOACurrency( 1000000000000000000L ); - ShowDecimalFromOACurrency( 1000000000000000001L ); - ShowDecimalFromOACurrency( long.MaxValue ); - ShowDecimalFromOACurrency( long.MinValue ); - ShowDecimalFromOACurrency( 123456789L ); - ShowDecimalFromOACurrency( 1234567890000L ); - ShowDecimalFromOACurrency( 1234567890987654321 ); - ShowDecimalFromOACurrency( 4294967295L ); + ShowDecimalFromOACurrency(0L); + ShowDecimalFromOACurrency(1L); + ShowDecimalFromOACurrency(100000L); + ShowDecimalFromOACurrency(100000000000L); + ShowDecimalFromOACurrency(1000000000000000000L); + ShowDecimalFromOACurrency(1000000000000000001L); + ShowDecimalFromOACurrency(long.MaxValue); + ShowDecimalFromOACurrency(long.MinValue); + ShowDecimalFromOACurrency(123456789L); + ShowDecimalFromOACurrency(1234567890000L); + ShowDecimalFromOACurrency(1234567890987654321); + ShowDecimalFromOACurrency(4294967295L); } } diff --git a/snippets/csharp/System/Decimal/FromOACurrency/tooacurrency.cs b/snippets/csharp/System/Decimal/FromOACurrency/tooacurrency.cs index 90224d1f982..751c880c455 100644 --- a/snippets/csharp/System/Decimal/FromOACurrency/tooacurrency.cs +++ b/snippets/csharp/System/Decimal/FromOACurrency/tooacurrency.cs @@ -7,57 +7,57 @@ class DecimalToOACurrencyDemo const string dataFmt = "{0,31}{1,27}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Display the decimal.ToOACurrency parameter and the result // or exception. - public static void ShowDecimalToOACurrency( decimal Argument ) + public static void ShowDecimalToOACurrency(decimal Argument) { // Catch the exception if ToOACurrency( ) throws one. try { - long oaCurrency = decimal.ToOACurrency( Argument ); - Console.WriteLine( dataFmt, Argument, oaCurrency ); + long oaCurrency = decimal.ToOACurrency(Argument); + Console.WriteLine(dataFmt, Argument, oaCurrency); } - catch( Exception ex ) + catch (Exception ex) { - Console.WriteLine( dataFmt, Argument, - GetExceptionType( ex ) ); + Console.WriteLine(dataFmt, Argument, + GetExceptionType(ex)); } } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.ToOACurrency( ) method generates \nthe " + "following output. It displays the argument as a " + "decimal \nand the OLE Automation Currency value " + - "as a long.\n" ); - Console.WriteLine( dataFmt, "Argument", - "OA Currency or Exception" ); - Console.WriteLine( dataFmt, "--------", - "------------------------" ); + "as a long.\n"); + Console.WriteLine(dataFmt, "Argument", + "OA Currency or Exception"); + Console.WriteLine(dataFmt, "--------", + "------------------------"); // Convert decimal values to OLE Automation Currency values. - ShowDecimalToOACurrency( 0M ); - ShowDecimalToOACurrency( 1M ); - ShowDecimalToOACurrency( 1.0000000000000000000000000000M ); - ShowDecimalToOACurrency( 100000000000000M ); - ShowDecimalToOACurrency( 100000000000000.00000000000000M ); - ShowDecimalToOACurrency( 10000000000000000000000000000M ); - ShowDecimalToOACurrency( 0.000000000123456789M ); - ShowDecimalToOACurrency( 0.123456789M ); - ShowDecimalToOACurrency( 123456789M ); - ShowDecimalToOACurrency( 123456789000000000M ); - ShowDecimalToOACurrency( 4294967295M ); - ShowDecimalToOACurrency( 18446744073709551615M ); - ShowDecimalToOACurrency( -79.228162514264337593543950335M ); - ShowDecimalToOACurrency( -79228162514264.337593543950335M ); + ShowDecimalToOACurrency(0M); + ShowDecimalToOACurrency(1M); + ShowDecimalToOACurrency(1.0000000000000000000000000000M); + ShowDecimalToOACurrency(100000000000000M); + ShowDecimalToOACurrency(100000000000000.00000000000000M); + ShowDecimalToOACurrency(10000000000000000000000000000M); + ShowDecimalToOACurrency(0.000000000123456789M); + ShowDecimalToOACurrency(0.123456789M); + ShowDecimalToOACurrency(123456789M); + ShowDecimalToOACurrency(123456789000000000M); + ShowDecimalToOACurrency(4294967295M); + ShowDecimalToOACurrency(18446744073709551615M); + ShowDecimalToOACurrency(-79.228162514264337593543950335M); + ShowDecimalToOACurrency(-79228162514264.337593543950335M); } } diff --git a/snippets/csharp/System/Decimal/GetBits/getbits.cs b/snippets/csharp/System/Decimal/GetBits/getbits.cs index cddf05694d5..e8d8ccd030d 100644 --- a/snippets/csharp/System/Decimal/GetBits/getbits.cs +++ b/snippets/csharp/System/Decimal/GetBits/getbits.cs @@ -3,30 +3,26 @@ class Example { - public static void Main() - { - // Define an array of Decimal values. - Decimal[] values = { 1M, 100000000000000M, 10000000000000000000000000000M, + public static void Main() + { + // Define an array of Decimal values. + decimal[] values = { 1M, 100000000000000M, 10000000000000000000000000000M, 100000000000000.00000000000000M, 1.0000000000000000000000000000M, 123456789M, 0.123456789M, 0.000000000123456789M, 0.000000000000000000123456789M, 4294967295M, - 18446744073709551615M, Decimal.MaxValue, - Decimal.MinValue, -7.9228162514264337593543950335M }; + 18446744073709551615M, decimal.MaxValue, + decimal.MinValue, -7.9228162514264337593543950335M }; - Console.WriteLine("{0,31} {1,10:X8}{2,10:X8}{3,10:X8}{4,10:X8}", - "Argument", "Bits[3]", "Bits[2]", "Bits[1]", - "Bits[0]" ); - Console.WriteLine( "{0,31} {1,10:X8}{2,10:X8}{3,10:X8}{4,10:X8}", - "--------", "-------", "-------", "-------", - "-------" ); + Console.WriteLine($"{"Argument",31} {"Bits[3]",10:X8}{"Bits[2]",10:X8}{"Bits[1]",10:X8}{"Bits[0]",10:X8}"); + Console.WriteLine($"{"--------",31} {"-------",10:X8}{"-------",10:X8}{"-------",10:X8}{"-------",10:X8}"); - // Iterate each element and display its binary representation - foreach (var value in values) { - int[] bits = decimal.GetBits(value); - Console.WriteLine("{0,31} {1,10:X8}{2,10:X8}{3,10:X8}{4,10:X8}", - value, bits[3], bits[2], bits[1], bits[0]); - } - } + // Iterate each element and display its binary representation + foreach (decimal value in values) + { + int[] bits = decimal.GetBits(value); + Console.WriteLine($"{value,31} {bits[3],10:X8}{bits[2],10:X8}{bits[1],10:X8}{bits[0],10:X8}"); + } + } } // The example displays the following output: // Argument Bits[3] Bits[2] Bits[1] Bits[0] diff --git a/snippets/csharp/System/Decimal/GetBits/gethashcode.cs b/snippets/csharp/System/Decimal/GetBits/gethashcode.cs index d1e678e7a40..81307bded84 100644 --- a/snippets/csharp/System/Decimal/GetBits/gethashcode.cs +++ b/snippets/csharp/System/Decimal/GetBits/gethashcode.cs @@ -5,41 +5,41 @@ class DecimalGetHashCodeDemo { // Display the decimal.GetHashCode argument and the result array. - public static void ShowDecimalGetHashCode( decimal Argument ) + public static void ShowDecimalGetHashCode(decimal Argument) { - int hashCode = Argument.GetHashCode( ); + int hashCode = Argument.GetHashCode(); - Console.WriteLine( "{0,31}{1,14} 0x{1:X8}", - Argument, hashCode ); + Console.WriteLine("{0,31}{1,14} 0x{1:X8}", + Argument, hashCode); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.GetHashCode( ) method generates \nthe " + "following output. It displays the hash code of the \n" + - "decimal argument in decimal and hexadecimal.\n" ); - Console.WriteLine( "{0,31}{1,14}", "Argument", "Hash Code" ); - Console.WriteLine( "{0,31}{1,14}", "--------", "---------" ); + "decimal argument in decimal and hexadecimal.\n"); + Console.WriteLine($"{"Argument",31}{"Hash Code",14}"); + Console.WriteLine($"{"--------",31}{"---------",14}"); // Generate hash codes for decimal objects. - ShowDecimalGetHashCode( 0M ); - ShowDecimalGetHashCode( 1M ); - ShowDecimalGetHashCode( 1.0000000000000000000000000000M ); - ShowDecimalGetHashCode( 100000000000000M ); - ShowDecimalGetHashCode( 100000000000000.00000000000000M ); - ShowDecimalGetHashCode( 10000000000000000000000000000M ); - ShowDecimalGetHashCode( 10000000000000000000000009999M ); - ShowDecimalGetHashCode( 10000000000000000004294967295M ); - ShowDecimalGetHashCode( 123456789M ); - ShowDecimalGetHashCode( 0.123456789M ); - ShowDecimalGetHashCode( 0.000000000123456789M ); - ShowDecimalGetHashCode( 0.000000000000000000123456789M ); - ShowDecimalGetHashCode( 4294967295M ); - ShowDecimalGetHashCode( 18446744073709551615M ); - ShowDecimalGetHashCode( decimal.MaxValue ); - ShowDecimalGetHashCode( decimal.MinValue ); - ShowDecimalGetHashCode( -7.9228162514264337593543950335M ); + ShowDecimalGetHashCode(0M); + ShowDecimalGetHashCode(1M); + ShowDecimalGetHashCode(1.0000000000000000000000000000M); + ShowDecimalGetHashCode(100000000000000M); + ShowDecimalGetHashCode(100000000000000.00000000000000M); + ShowDecimalGetHashCode(10000000000000000000000000000M); + ShowDecimalGetHashCode(10000000000000000000000009999M); + ShowDecimalGetHashCode(10000000000000000004294967295M); + ShowDecimalGetHashCode(123456789M); + ShowDecimalGetHashCode(0.123456789M); + ShowDecimalGetHashCode(0.000000000123456789M); + ShowDecimalGetHashCode(0.000000000000000000123456789M); + ShowDecimalGetHashCode(4294967295M); + ShowDecimalGetHashCode(18446744073709551615M); + ShowDecimalGetHashCode(decimal.MaxValue); + ShowDecimalGetHashCode(decimal.MinValue); + ShowDecimalGetHashCode(-7.9228162514264337593543950335M); } } diff --git a/snippets/csharp/System/Decimal/GetBits/gettypecode.cs b/snippets/csharp/System/Decimal/GetBits/gettypecode.cs index fecbcf71339..9dd44c47e42 100644 --- a/snippets/csharp/System/Decimal/GetBits/gettypecode.cs +++ b/snippets/csharp/System/Decimal/GetBits/gettypecode.cs @@ -4,18 +4,18 @@ class DecimalGetTypeCodeDemo { - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.GetTypeCode( ) \nmethod " + - "generates the following output.\n" ); + "generates the following output.\n"); // Create a decimal object and get its type code. - decimal aDecimal = new decimal( 1.0 ); - TypeCode typCode = aDecimal.GetTypeCode( ); + decimal aDecimal = new(1.0); + TypeCode typCode = aDecimal.GetTypeCode(); - Console.WriteLine( "Type Code: \"{0}\"", typCode ); - Console.WriteLine( "Numeric value: {0}", (int)typCode ); + Console.WriteLine($"Type Code: \"{typCode}\""); + Console.WriteLine($"Numeric value: {(int)typCode}"); } } diff --git a/snippets/csharp/System/Decimal/MinusOne/fields.cs b/snippets/csharp/System/Decimal/MinusOne/fields.cs index d6584911e90..2e508292fb3 100644 --- a/snippets/csharp/System/Decimal/MinusOne/fields.cs +++ b/snippets/csharp/System/Decimal/MinusOne/fields.cs @@ -4,41 +4,39 @@ class DecimalFieldsDemo { - public static void Main( ) + public static void Main() { const string numberFmt = "{0,-25}{1,45:N0}"; const string exprFmt = "{0,-55}{1,15}"; Console.WriteLine( "This example of the fields of the Decimal structure " + - "\ngenerates the following output.\n" ); - Console.WriteLine( numberFmt, "Field or Expression", "Value" ); - Console.WriteLine( numberFmt, "-------------------", "-----" ); + "\ngenerates the following output.\n"); + Console.WriteLine(numberFmt, "Field or Expression", "Value"); + Console.WriteLine(numberFmt, "-------------------", "-----"); // Display the values of the Decimal fields. - Console.WriteLine( numberFmt, "Decimal.MaxValue", - Decimal.MaxValue ); - Console.WriteLine( numberFmt, "Decimal.MinValue", - Decimal.MinValue ); - Console.WriteLine( numberFmt, "Decimal.MinusOne", - Decimal.MinusOne ); - Console.WriteLine( numberFmt, "Decimal.One", Decimal.One ); - Console.WriteLine( numberFmt, "Decimal.Zero", Decimal.Zero ); - Console.WriteLine( ); + Console.WriteLine(numberFmt, "Decimal.MaxValue", + decimal.MaxValue); + Console.WriteLine(numberFmt, "Decimal.MinValue", + decimal.MinValue); + Console.WriteLine(numberFmt, "Decimal.MinusOne", + decimal.MinusOne); + Console.WriteLine(numberFmt, "Decimal.One", decimal.One); + Console.WriteLine(numberFmt, "Decimal.Zero", decimal.Zero); + Console.WriteLine(); // Display the values of expressions of the Decimal fields. - Console.WriteLine( exprFmt, + Console.WriteLine(exprFmt, "( Decimal.MinusOne + Decimal.One ) == Decimal.Zero", - (Decimal.MinusOne + Decimal.One ) == Decimal.Zero ); - Console.WriteLine( exprFmt, + (decimal.MinusOne + decimal.One) == decimal.Zero); + Console.WriteLine(exprFmt, "Decimal.MaxValue + Decimal.MinValue", - Decimal.MaxValue + Decimal.MinValue ); - Console.WriteLine( exprFmt, + decimal.MaxValue + decimal.MinValue); + Console.WriteLine(exprFmt, "Decimal.MinValue / Decimal.MaxValue", - Decimal.MinValue / Decimal.MaxValue ); - Console.WriteLine( "{0,-40}{1,30}", - "100000000000000M / Decimal.MaxValue", - 100000000000000M / Decimal.MaxValue ); + decimal.MinValue / decimal.MaxValue); + Console.WriteLine($"{"100000000000000M / Decimal.MaxValue",-40}{100000000000000M / decimal.MaxValue,30}"); } } diff --git a/snippets/csharp/System/Decimal/Multiply/mul_div_rem.cs b/snippets/csharp/System/Decimal/Multiply/mul_div_rem.cs index 4acee6ffdc8..1b11ef64c06 100644 --- a/snippets/csharp/System/Decimal/Multiply/mul_div_rem.cs +++ b/snippets/csharp/System/Decimal/Multiply/mul_div_rem.cs @@ -2,7 +2,7 @@ // Example of the decimal.Multiply, decimal.Divide, and // decimal.Remainder methods. using System; -using Microsoft.VisualBasic; + class DecimalMulDivRemDemo { @@ -10,38 +10,38 @@ class DecimalMulDivRemDemo // Display decimal parameters and their product, quotient, and // remainder. - public static void ShowDecimalProQuoRem( decimal Left, decimal Right ) + public static void ShowDecimalProQuoRem(decimal Left, decimal Right) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "decimal Left", Left ); - Console.WriteLine( dataFmt, "decimal Right", Right ); - Console.WriteLine( dataFmt, "decimal.Multiply( Left, Right )", - decimal.Multiply( Left, Right ) ); - Console.WriteLine( dataFmt, "decimal.Divide( Left, Right )", - decimal.Divide( Left, Right ) ); - Console.WriteLine( dataFmt, "decimal.Remainder( Left, Right )", - decimal.Remainder( Left, Right ) ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "decimal Left", Left); + Console.WriteLine(dataFmt, "decimal Right", Right); + Console.WriteLine(dataFmt, "decimal.Multiply( Left, Right )", + decimal.Multiply(Left, Right)); + Console.WriteLine(dataFmt, "decimal.Divide( Left, Right )", + decimal.Divide(Left, Right)); + Console.WriteLine(dataFmt, "decimal.Remainder( Left, Right )", + decimal.Remainder(Left, Right)); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.Multiply( decimal, decimal ), \n" + " decimal.Divide( decimal, decimal ), and \n" + " decimal.Remainder( decimal, decimal ) \n" + "methods generates the following output. It displays " + "the product, \nquotient, and remainder of several " + - "pairs of decimal objects." ); + "pairs of decimal objects."); // Create pairs of decimal objects. - ShowDecimalProQuoRem( 1000M, 7M ); - ShowDecimalProQuoRem( -1000M, 7M ); + ShowDecimalProQuoRem(1000M, 7M); + ShowDecimalProQuoRem(-1000M, 7M); ShowDecimalProQuoRem( - new decimal( 1230000000, 0, 0, false, 7 ), 0.0012300M ); - ShowDecimalProQuoRem( 12345678900000000M, - 0.0000000012345678M ); - ShowDecimalProQuoRem( 123456789.0123456789M, - 123456789.1123456789M ); + new decimal(1230000000, 0, 0, false, 7), 0.0012300M); + ShowDecimalProQuoRem(12345678900000000M, + 0.0000000012345678M); + ShowDecimalProQuoRem(123456789.0123456789M, + 123456789.1123456789M); } } diff --git a/snippets/csharp/System/Decimal/Multiply/mul_div_rem_ops.cs b/snippets/csharp/System/Decimal/Multiply/mul_div_rem_ops.cs index 75af0656e84..df8abac8b5d 100644 --- a/snippets/csharp/System/Decimal/Multiply/mul_div_rem_ops.cs +++ b/snippets/csharp/System/Decimal/Multiply/mul_div_rem_ops.cs @@ -9,33 +9,33 @@ class DecimalMulDivRemOpsDemo // Display decimal parameters and their product, quotient, and // remainder. - public static void ShowDecimalProQuoRem( decimal Left, decimal Right ) + public static void ShowDecimalProQuoRem(decimal Left, decimal Right) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "decimal Left", Left ); - Console.WriteLine( dataFmt, "decimal Right", Right ); - Console.WriteLine( dataFmt, "Left * Right", Left * Right ); - Console.WriteLine( dataFmt, "Left / Right", Left / Right ); - Console.WriteLine( dataFmt, "Left % Right", Left % Right ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "decimal Left", Left); + Console.WriteLine(dataFmt, "decimal Right", Right); + Console.WriteLine(dataFmt, "Left * Right", Left * Right); + Console.WriteLine(dataFmt, "Left / Right", Left / Right); + Console.WriteLine(dataFmt, "Left % Right", Left % Right); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the decimal multiplication, division, " + "and modulus \noperators generates the following " + "output. It displays the product, \nquotient, and " + - "remainder of several pairs of decimal objects." ); + "remainder of several pairs of decimal objects."); // Create pairs of decimal objects. - ShowDecimalProQuoRem( 1000M, 7M ); - ShowDecimalProQuoRem( -1000M, 7M ); + ShowDecimalProQuoRem(1000M, 7M); + ShowDecimalProQuoRem(-1000M, 7M); ShowDecimalProQuoRem( - new decimal( 1230000000, 0, 0, false, 7 ), 0.0012300M ); - ShowDecimalProQuoRem( 12345678900000000M, - 0.0000000012345678M ); - ShowDecimalProQuoRem( 123456789.0123456789M, - 123456789.1123456789M ); + new decimal(1230000000, 0, 0, false, 7), 0.0012300M); + ShowDecimalProQuoRem(12345678900000000M, + 0.0000000012345678M); + ShowDecimalProQuoRem(123456789.0123456789M, + 123456789.1123456789M); } } diff --git a/snippets/csharp/System/Decimal/Negate/floor_neg_trunc.cs b/snippets/csharp/System/Decimal/Negate/floor_neg_trunc.cs index 090ad8a1ba6..e16745baf32 100644 --- a/snippets/csharp/System/Decimal/Negate/floor_neg_trunc.cs +++ b/snippets/csharp/System/Decimal/Negate/floor_neg_trunc.cs @@ -8,33 +8,33 @@ class DecimalFloorNegTruncDemo const string dataFmt = "{0,-30}{1,26}"; // Display decimal parameters and the method results. - public static void ShowDecimalFloorNegTrunc( decimal Argument ) + public static void ShowDecimalFloorNegTrunc(decimal Argument) { - Console.WriteLine( ); - Console.WriteLine( dataFmt, "decimal Argument", Argument ); - Console.WriteLine( dataFmt, "decimal.Negate( Argument )", - decimal.Negate( Argument ) ); - Console.WriteLine( dataFmt, "decimal.Floor( Argument )", - decimal.Floor( Argument ) ); - Console.WriteLine( dataFmt, "decimal.Truncate( Argument )", - decimal.Truncate( Argument ) ); + Console.WriteLine(); + Console.WriteLine(dataFmt, "decimal Argument", Argument); + Console.WriteLine(dataFmt, "decimal.Negate( Argument )", + decimal.Negate(Argument)); + Console.WriteLine(dataFmt, "decimal.Floor( Argument )", + decimal.Floor(Argument)); + Console.WriteLine(dataFmt, "decimal.Truncate( Argument )", + decimal.Truncate(Argument)); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.Negate( decimal ), \n" + " decimal.Floor( decimal ), and \n" + " decimal.Truncate( decimal ) \n" + - "methods generates the following output." ); + "methods generates the following output."); // Create pairs of decimal objects. - ShowDecimalFloorNegTrunc( 0M ); - ShowDecimalFloorNegTrunc( 123.456M ); - ShowDecimalFloorNegTrunc( -123.456M ); + ShowDecimalFloorNegTrunc(0M); + ShowDecimalFloorNegTrunc(123.456M); + ShowDecimalFloorNegTrunc(-123.456M); ShowDecimalFloorNegTrunc( - new decimal( 1230000000, 0, 0, true, 7 ) ); - ShowDecimalFloorNegTrunc( -9999999999.9999999999M ); + new decimal(1230000000, 0, 0, true, 7)); + ShowDecimalFloorNegTrunc(-9999999999.9999999999M); } } diff --git a/snippets/csharp/System/Decimal/Negate/round.cs b/snippets/csharp/System/Decimal/Negate/round.cs index f7dc6710e22..198bc32d5a5 100644 --- a/snippets/csharp/System/Decimal/Negate/round.cs +++ b/snippets/csharp/System/Decimal/Negate/round.cs @@ -7,34 +7,34 @@ class DecimalRoundDemo const string dataFmt = "{0,26}{1,8}{2,26}"; // Display decimal.Round parameters and the result. - public static void ShowDecimalRound( decimal Argument, int Digits ) + public static void ShowDecimalRound(decimal Argument, int Digits) { - decimal rounded = decimal.Round( Argument, Digits ); + decimal rounded = decimal.Round(Argument, Digits); - Console.WriteLine( dataFmt, Argument, Digits, rounded ); + Console.WriteLine(dataFmt, Argument, Digits, rounded); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the " + + Console.WriteLine("This example of the " + "decimal.Round( decimal, Integer ) \n" + - "method generates the following output.\n" ); - Console.WriteLine( dataFmt, "Argument", "Digits", "Result" ); - Console.WriteLine( dataFmt, "--------", "------", "------" ); + "method generates the following output.\n"); + Console.WriteLine(dataFmt, "Argument", "Digits", "Result"); + Console.WriteLine(dataFmt, "--------", "------", "------"); // Create pairs of decimal objects. - ShowDecimalRound( 1.45M, 1 ); - ShowDecimalRound( 1.55M, 1 ); - ShowDecimalRound( 123.456789M, 4 ); - ShowDecimalRound( 123.456789M, 6 ); - ShowDecimalRound( 123.456789M, 8 ); - ShowDecimalRound( -123.456M, 0 ); + ShowDecimalRound(1.45M, 1); + ShowDecimalRound(1.55M, 1); + ShowDecimalRound(123.456789M, 4); + ShowDecimalRound(123.456789M, 6); + ShowDecimalRound(123.456789M, 8); + ShowDecimalRound(-123.456M, 0); ShowDecimalRound( - new decimal( 1230000000, 0, 0, true, 7 ), 3 ); + new decimal(1230000000, 0, 0, true, 7), 3); ShowDecimalRound( - new decimal( 1230000000, 0, 0, true, 7 ), 11 ); - ShowDecimalRound( -9999999999.9999999999M, 9 ); - ShowDecimalRound( -9999999999.9999999999M, 10 ); + new decimal(1230000000, 0, 0, true, 7), 11); + ShowDecimalRound(-9999999999.9999999999M, 9); + ShowDecimalRound(-9999999999.9999999999M, 10); } } diff --git a/snippets/csharp/System/Decimal/Overview/DecimalDivision_46630_1.cs b/snippets/csharp/System/Decimal/Overview/DecimalDivision_46630_1.cs index e3fa0a83ba8..0ac95f20670 100644 --- a/snippets/csharp/System/Decimal/Overview/DecimalDivision_46630_1.cs +++ b/snippets/csharp/System/Decimal/Overview/DecimalDivision_46630_1.cs @@ -2,31 +2,31 @@ public class Class1 { - public static void Main() - { - DivideWithoutRounding(); - DivideWithRounding(); - } + public static void Main() + { + DivideWithoutRounding(); + DivideWithRounding(); + } - private static void DivideWithoutRounding() - { - Console.WriteLine("DivideWithoutRounding"); - // - decimal dividend = Decimal.One; - decimal divisor = 3; - // The following displays 0.9999999999999999999999999999 to the console - Console.WriteLine(dividend/divisor * divisor); - // - } + private static void DivideWithoutRounding() + { + Console.WriteLine("DivideWithoutRounding"); + // + decimal dividend = decimal.One; + decimal divisor = 3; + // The following displays 0.9999999999999999999999999999 to the console + Console.WriteLine(dividend / divisor * divisor); + // + } - private static void DivideWithRounding() - { - Console.WriteLine("DivideWithRounding"); - // - decimal dividend = Decimal.One; - decimal divisor = 3; - // The following displays 1.00 to the console - Console.WriteLine(Math.Round(dividend/divisor * divisor, 2)); - // - } + private static void DivideWithRounding() + { + Console.WriteLine("DivideWithRounding"); + // + decimal dividend = decimal.One; + decimal divisor = 3; + // The following displays 1.00 to the console + Console.WriteLine(Math.Round(dividend / divisor * divisor, 2)); + // + } } diff --git a/snippets/csharp/System/Decimal/Overview/source.cs b/snippets/csharp/System/Decimal/Overview/source.cs index f8ff53bea39..f08ee72b733 100644 --- a/snippets/csharp/System/Decimal/Overview/source.cs +++ b/snippets/csharp/System/Decimal/Overview/source.cs @@ -2,123 +2,96 @@ namespace Snippets { - class Launcher { - static void Main(string[] args) - { - PiggyBank pb = new PiggyBank(); - - for(int i=0; i<378; i++) { - pb.AddPenny(); - } - - Console.WriteLine(pb); - - Console.ReadLine(); - } - } - - // - /// - /// Keeping my fortune in Decimals to avoid the round-off errors. - /// - class PiggyBank { - protected decimal MyFortune; - - public void AddPenny() { - MyFortune = Decimal.Add(MyFortune, .01m); - } - - public decimal Capacity { - get { - return Decimal.MaxValue; - } - } - - public decimal Dollars { - get { - return Decimal.Floor(MyFortune); - } - } - - public decimal Cents { - get { - return Decimal.Subtract(MyFortune, Decimal.Floor(MyFortune)); - } - } - - public override string ToString() { - return MyFortune.ToString("C")+" in piggy bank"; - } - } - // + class Launcher + { + static void Main(string[] args) + { + PiggyBank pb = new(); + + for (int i = 0; i < 378; i++) + { + pb.AddPenny(); + } + + Console.WriteLine(pb); + + Console.ReadLine(); + } + } + + // + /// + /// Keeping my fortune in Decimals to avoid the round-off errors. + /// + class PiggyBank + { + protected decimal MyFortune; + + public void AddPenny() => MyFortune = decimal.Add(MyFortune, .01m); + + public decimal Capacity => decimal.MaxValue; + + public decimal Dollars => decimal.Floor(MyFortune); + + public decimal Cents => decimal.Subtract(MyFortune, decimal.Floor(MyFortune)); + + public override string ToString() => MyFortune.ToString("C") + " in piggy bank"; + } + // } -namespace Snippets2 { - // - class PiggyBank { - public decimal Capacity { - get { - return Decimal.MaxValue; - } - } - - protected decimal MyFortune; - - public void AddPenny() { - MyFortune += .01m; - } - } - // +namespace Snippets2 +{ + // + class PiggyBank + { + public decimal Capacity => decimal.MaxValue; + + protected decimal MyFortune; + + public void AddPenny() => MyFortune += .01m; + } + // } -namespace Snippets3 { - // - class PiggyBank { - public decimal Dollars { - get { - return Decimal.Floor(MyFortune); - } - } - - protected decimal MyFortune; - - public void AddPenny() { - MyFortune += .01m; - } - } - // +namespace Snippets3 +{ + // + class PiggyBank + { + public decimal Dollars => decimal.Floor(MyFortune); + + protected decimal MyFortune; + + public void AddPenny() => MyFortune += .01m; + } + // } -namespace Snippets4 { - // - class PiggyBank { - public decimal Cents { - get { - return Decimal.Subtract(MyFortune, Decimal.Floor(MyFortune)); - } - } - - protected decimal MyFortune; - - public void AddPenny() { - MyFortune += .01m; - } - } - // +namespace Snippets4 +{ + // + class PiggyBank + { + public decimal Cents => decimal.Subtract(MyFortune, decimal.Floor(MyFortune)); + + protected decimal MyFortune; + + public void AddPenny() => MyFortune += .01m; + } + // } -namespace Snippets5 { - // - class PiggyBank { - public void AddPenny() { - MyFortune = Decimal.Add(MyFortune, .01m); - } - - public override string ToString() { - return MyFortune.ToString("C")+" in piggy bank"; - } - - protected decimal MyFortune; - } - // -} \ No newline at end of file +namespace Snippets5 +{ + // + class PiggyBank + { + public void AddPenny() => MyFortune = decimal.Add(MyFortune, .01m); + + public override string ToString() => MyFortune.ToString("C") + " in piggy bank"; + + protected decimal MyFortune; + } + // +} diff --git a/snippets/csharp/System/Decimal/Parse/Default.aspx.cs b/snippets/csharp/System/Decimal/Parse/Default.aspx.cs index 8cc7d6ecd98..b0be639d652 100644 --- a/snippets/csharp/System/Decimal/Parse/Default.aspx.cs +++ b/snippets/csharp/System/Decimal/Parse/Default.aspx.cs @@ -5,12 +5,12 @@ public partial class Default2 { private sealed class TextBox { - public string Text { get; set; } = String.Empty; + public string Text { get; set; } = string.Empty; } private sealed class Label { - public string Text { get; set; } = String.Empty; + public string Text { get; set; } = string.Empty; } private sealed class RequestContext @@ -30,23 +30,23 @@ protected void OkToSingle_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = Single.Parse(this.inputNumber.Text, culture.NumberFormat); + number = float.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -69,23 +69,23 @@ protected void OkToDouble_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = Double.Parse(this.inputNumber.Text, culture.NumberFormat); + number = double.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -108,23 +108,23 @@ protected void OkToDecimal_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = Decimal.Parse(this.inputNumber.Text, culture.NumberFormat); + number = decimal.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -147,23 +147,23 @@ protected void OkToInteger_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = Int32.Parse(this.inputNumber.Text, culture.NumberFormat); + number = int.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -186,23 +186,23 @@ protected void OkToLong_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = Int64.Parse(this.inputNumber.Text, culture.NumberFormat); + number = long.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -225,23 +225,23 @@ protected void OkToUInteger_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = UInt32.Parse(this.inputNumber.Text, culture.NumberFormat); + number = uint.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { @@ -264,23 +264,23 @@ protected void OkToULong_Click(object sender, EventArgs e) CultureInfo culture; // Return if string is empty - if (String.IsNullOrEmpty(this.inputNumber.Text)) + if (string.IsNullOrEmpty(this.inputNumber.Text)) return; // Get locale of web request to determine possible format of number if (Request.UserLanguages.Length == 0) return; locale = Request.UserLanguages[0]; - if (String.IsNullOrEmpty(locale)) + if (string.IsNullOrEmpty(locale)) return; // Instantiate CultureInfo object for the user's locale - culture = new CultureInfo(locale); + culture = new(locale); // Convert user input from a string to a number try { - number = UInt64.Parse(this.inputNumber.Text, culture.NumberFormat); + number = ulong.Parse(this.inputNumber.Text, culture.NumberFormat); } catch (FormatException) { diff --git a/snippets/csharp/System/Decimal/Parse/parse.cs b/snippets/csharp/System/Decimal/Parse/parse.cs index 4dc60a62237..e39b8ae9cdf 100644 --- a/snippets/csharp/System/Decimal/Parse/parse.cs +++ b/snippets/csharp/System/Decimal/Parse/parse.cs @@ -3,166 +3,166 @@ public class Class1 { - public static void Main() - { - CallParse(); - Console.WriteLine("-----"); - CallParseWithStyles(); - Console.WriteLine("-----"); - CallParseWithStylesAndProvider(); - } - - private static void CallParse() - { - // - string value; - decimal number; - // Parse an integer with thousands separators. - value = "16,523,421"; - number = Decimal.Parse(value); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '16,523,421' converted to 16523421. - - // Parse a floating point value with thousands separators - value = "25,162.1378"; - number = Decimal.Parse(value); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '25,162.1378' converted to 25162.1378. - - // Parse a floating point number with US currency symbol. - value = "$16,321,421.75"; - try - { - number = Decimal.Parse(value); - Console.WriteLine("'{0}' converted to {1}.", value, number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", value); - } - // Displays: - // Unable to parse '$16,321,421.75'. - - // Parse a number in exponential notation - value = "1.62345e-02"; - try - { - number = Decimal.Parse(value); - Console.WriteLine("'{0}' converted to {1}.", value, number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", value); - } - // Displays: - // Unable to parse '1.62345e-02'. - // - } - - private static void CallParseWithStyles() - { - // - string value; - decimal number; - NumberStyles style; - - // Parse string with a floating point value using NumberStyles.None. - value = "8694.12"; - style = NumberStyles.None; - try - { - number = Decimal.Parse(value, style); - Console.WriteLine("'{0}' converted to {1}.", value, number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", value); - } - // Displays: - // Unable to parse '8694.12'. - - // Parse string with a floating point value and allow decimal point. - style = NumberStyles.AllowDecimalPoint; - number = Decimal.Parse(value, style); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '8694.12' converted to 8694.12. - - // Parse string with negative value in parentheses - value = "(1,789.34)"; - style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | - NumberStyles.AllowParentheses; - number = Decimal.Parse(value, style); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '(1,789.34)' converted to -1789.34. - - // Parse string using Number style - value = " -17,623.49 "; - style = NumberStyles.Number; - number = Decimal.Parse(value, style); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // ' -17,623.49 ' converted to -17623.49. - // - } - - private static void CallParseWithStylesAndProvider() - { - // - string value; - decimal number; - NumberStyles style; - CultureInfo provider; - - // Parse string using " " as the thousands separator - // and "," as the decimal separator for fr-FR culture. - value = "892 694,12"; - style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; - provider = new CultureInfo("fr-FR"); - - number = Decimal.Parse(value, style, provider); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '892 694,12' converted to 892694.12. - - try - { - number = Decimal.Parse(value, style, CultureInfo.InvariantCulture); - Console.WriteLine("'{0}' converted to {1}.", value, number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", value); - } - // Displays: - // Unable to parse '892 694,12'. - - // Parse string using "$" as the currency symbol for en-GB and - // en-US cultures. - value = "$6,032.51"; - style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; - provider = new CultureInfo("en-GB"); - - try - { - number = Decimal.Parse(value, style, provider); - Console.WriteLine("'{0}' converted to {1}.", value, number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}'.", value); - } - // Displays: - // Unable to parse '$6,032.51'. - - provider = new CultureInfo("en-US"); - number = Decimal.Parse(value, style, provider); - Console.WriteLine("'{0}' converted to {1}.", value, number); - // Displays: - // '$6,032.51' converted to 6032.51. - // - } + public static void Main() + { + CallParse(); + Console.WriteLine("-----"); + CallParseWithStyles(); + Console.WriteLine("-----"); + CallParseWithStylesAndProvider(); + } + + private static void CallParse() + { + // + string value; + decimal number; + // Parse an integer with thousands separators. + value = "16,523,421"; + number = decimal.Parse(value); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '16,523,421' converted to 16523421. + + // Parse a floating point value with thousands separators + value = "25,162.1378"; + number = decimal.Parse(value); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '25,162.1378' converted to 25162.1378. + + // Parse a floating point number with US currency symbol. + value = "$16,321,421.75"; + try + { + number = decimal.Parse(value); + Console.WriteLine($"'{value}' converted to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } + // Displays: + // Unable to parse '$16,321,421.75'. + + // Parse a number in exponential notation + value = "1.62345e-02"; + try + { + number = decimal.Parse(value); + Console.WriteLine($"'{value}' converted to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } + // Displays: + // Unable to parse '1.62345e-02'. + // + } + + private static void CallParseWithStyles() + { + // + string value; + decimal number; + NumberStyles style; + + // Parse string with a floating point value using NumberStyles.None. + value = "8694.12"; + style = NumberStyles.None; + try + { + number = decimal.Parse(value, style); + Console.WriteLine($"'{value}' converted to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } + // Displays: + // Unable to parse '8694.12'. + + // Parse string with a floating point value and allow decimal point. + style = NumberStyles.AllowDecimalPoint; + number = decimal.Parse(value, style); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '8694.12' converted to 8694.12. + + // Parse string with negative value in parentheses + value = "(1,789.34)"; + style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | + NumberStyles.AllowParentheses; + number = decimal.Parse(value, style); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '(1,789.34)' converted to -1789.34. + + // Parse string using Number style + value = " -17,623.49 "; + style = NumberStyles.Number; + number = decimal.Parse(value, style); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // ' -17,623.49 ' converted to -17623.49. + // + } + + private static void CallParseWithStylesAndProvider() + { + // + string value; + decimal number; + NumberStyles style; + CultureInfo provider; + + // Parse string using " " as the thousands separator + // and "," as the decimal separator for fr-FR culture. + value = "892 694,12"; + style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; + provider = new("fr-FR"); + + number = decimal.Parse(value, style, provider); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '892 694,12' converted to 892694.12. + + try + { + number = decimal.Parse(value, style, CultureInfo.InvariantCulture); + Console.WriteLine($"'{value}' converted to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } + // Displays: + // Unable to parse '892 694,12'. + + // Parse string using "$" as the currency symbol for en-GB and + // en-US cultures. + value = "$6,032.51"; + style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; + provider = new("en-GB"); + + try + { + number = decimal.Parse(value, style, provider); + Console.WriteLine($"'{value}' converted to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}'."); + } + // Displays: + // Unable to parse '$6,032.51'. + + provider = new("en-US"); + number = decimal.Parse(value, style, provider); + Console.WriteLine($"'{value}' converted to {number}."); + // Displays: + // '$6,032.51' converted to 6032.51. + // + } } diff --git a/snippets/csharp/System/Decimal/Remainder/remainder.cs b/snippets/csharp/System/Decimal/Remainder/remainder.cs index 9e7f412eabb..1923d636316 100644 --- a/snippets/csharp/System/Decimal/Remainder/remainder.cs +++ b/snippets/csharp/System/Decimal/Remainder/remainder.cs @@ -6,17 +6,15 @@ public class Example public static void Main() { // Create parallel arrays of Decimals to use as the dividend and divisor. - Decimal[] dividends = { 79m, 1000m, -1000m, 123m, 1234567800000m, + decimal[] dividends = { 79m, 1000m, -1000m, 123m, 1234567800000m, 1234.0123m }; - Decimal[] divisors = { 11m, 7m, 7m, .00123m, 0.12345678m, 1234.5678m }; + decimal[] divisors = { 11m, 7m, 7m, .00123m, 0.12345678m, 1234.5678m }; for (int ctr = 0; ctr < dividends.Length; ctr++) { - Decimal dividend = dividends[ctr]; - Decimal divisor = divisors[ctr]; - Console.WriteLine("{0:N3} / {1:N3} = {2:N3} Remainder {3:N3}", dividend, - divisor, Decimal.Divide(dividend, divisor), - Decimal.Remainder(dividend, divisor)); + decimal dividend = dividends[ctr]; + decimal divisor = divisors[ctr]; + Console.WriteLine($"{dividend:N3} / {divisor:N3} = {decimal.Divide(dividend, divisor):N3} Remainder {decimal.Remainder(dividend, divisor):N3}"); } } } diff --git a/snippets/csharp/System/Decimal/Round/Program.cs b/snippets/csharp/System/Decimal/Round/Program.cs index 257d07d87f9..436a4a0eb5d 100644 --- a/snippets/csharp/System/Decimal/Round/Program.cs +++ b/snippets/csharp/System/Decimal/Round/Program.cs @@ -1,12 +1,9 @@ -using System; + namespace Rounding { class Program { - static void Main(string[] args) - { - MPR.DecimalExample(); - } + static void Main(string[] args) => MPR.DecimalExample(); } } diff --git a/snippets/csharp/System/Decimal/Round/Round1.cs b/snippets/csharp/System/Decimal/Round/Round1.cs index 6bbecf042ba..9e5e7c08fff 100644 --- a/snippets/csharp/System/Decimal/Round/Round1.cs +++ b/snippets/csharp/System/Decimal/Round/Round1.cs @@ -3,11 +3,11 @@ public class Example { - public static void Main() - { - for (decimal value = 100m; value <= 102m; value += .1m) - Console.WriteLine("{0} --> {1}", value, Decimal.Round(value)); - } + public static void Main() + { + for (decimal value = 100m; value <= 102m; value += .1m) + Console.WriteLine($"{value} --> {decimal.Round(value)}"); + } } // The example displays the following output: // 100 --> 100 diff --git a/snippets/csharp/System/Decimal/Round/Round12.cs b/snippets/csharp/System/Decimal/Round/Round12.cs index 8b48ea08a46..28ac83f0d38 100644 --- a/snippets/csharp/System/Decimal/Round/Round12.cs +++ b/snippets/csharp/System/Decimal/Round/Round12.cs @@ -3,26 +3,22 @@ class Example12 { - public static void Main() - { - // Define a set of Decimal values. - decimal[] values = { 1.45m, 1.55m, 123.456789m, 123.456789m, + public static void Main() + { + // Define a set of Decimal values. + decimal[] values = { 1.45m, 1.55m, 123.456789m, 123.456789m, 123.456789m, -123.456m, - new Decimal(1230000000, 0, 0, true, 7 ), - new Decimal(1230000000, 0, 0, true, 7 ), + new decimal(1230000000, 0, 0, true, 7 ), + new decimal(1230000000, 0, 0, true, 7 ), -9999999999.9999999999m, -9999999999.9999999999m }; - // Define a set of integers to for decimals argument. - int[] decimals = { 1, 1, 4, 6, 8, 0, 3, 11, 9, 10}; + // Define a set of integers to for decimals argument. + int[] decimals = { 1, 1, 4, 6, 8, 0, 3, 11, 9, 10 }; - Console.WriteLine("{0,26}{1,8}{2,26}", - "Argument", "Digits", "Result" ); - Console.WriteLine("{0,26}{1,8}{2,26}", - "--------", "------", "------" ); - for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0,26}{1,8}{2,26}", - values[ctr], decimals[ctr], - Decimal.Round(values[ctr], decimals[ctr])); + Console.WriteLine($"{"Argument",26}{"Digits",8}{"Result",26}"); + Console.WriteLine($"{"--------",26}{"------",8}{"------",26}"); + for (int ctr = 0; ctr < values.Length; ctr++) + Console.WriteLine($"{values[ctr],26}{decimals[ctr],8}{decimal.Round(values[ctr], decimals[ctr]),26}"); } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/Round/Round2.cs b/snippets/csharp/System/Decimal/Round/Round2.cs index 2d7edaca25f..f2f6845af14 100644 --- a/snippets/csharp/System/Decimal/Round/Round2.cs +++ b/snippets/csharp/System/Decimal/Round/Round2.cs @@ -3,26 +3,22 @@ class Example2 { - public static void Main() - { - // Define a set of Decimal values. - decimal[] values = { 1.45m, 1.55m, 123.456789m, 123.456789m, + public static void Main() + { + // Define a set of Decimal values. + decimal[] values = { 1.45m, 1.55m, 123.456789m, 123.456789m, 123.456789m, -123.456m, - new Decimal(1230000000, 0, 0, true, 7 ), - new Decimal(1230000000, 0, 0, true, 7 ), + new decimal(1230000000, 0, 0, true, 7 ), + new decimal(1230000000, 0, 0, true, 7 ), -9999999999.9999999999m, -9999999999.9999999999m }; - // Define a set of integers to for decimals argument. - int[] decimals = { 1, 1, 4, 6, 8, 0, 3, 11, 9, 10}; + // Define a set of integers to for decimals argument. + int[] decimals = { 1, 1, 4, 6, 8, 0, 3, 11, 9, 10 }; - Console.WriteLine("{0,26}{1,8}{2,26}", - "Argument", "Digits", "Result" ); - Console.WriteLine("{0,26}{1,8}{2,26}", - "--------", "------", "------" ); - for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0,26}{1,8}{2,26}", - values[ctr], decimals[ctr], - Decimal.Round(values[ctr], decimals[ctr])); + Console.WriteLine($"{"Argument",26}{"Digits",8}{"Result",26}"); + Console.WriteLine($"{"--------",26}{"------",8}{"------",26}"); + for (int ctr = 0; ctr < values.Length; ctr++) + Console.WriteLine($"{values[ctr],26}{decimals[ctr],8}{decimal.Round(values[ctr], decimals[ctr]),26}"); } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/Round/mean1.cs b/snippets/csharp/System/Decimal/Round/mean1.cs index a552a4b1a8c..30c7ca091aa 100644 --- a/snippets/csharp/System/Decimal/Round/mean1.cs +++ b/snippets/csharp/System/Decimal/Round/mean1.cs @@ -9,24 +9,24 @@ public static void Example1() decimal sum = 0; // Calculate true mean. - foreach (var value in values) + foreach (decimal value in values) sum += value; - Console.WriteLine("True mean: {0:N2}", sum / values.Length); + Console.WriteLine($"True mean: {sum / values.Length:N2}"); // Calculate mean with rounding away from zero. sum = 0; - foreach (var value in values) + foreach (decimal value in values) sum += Math.Round(value, 1, MidpointRounding.AwayFromZero); - Console.WriteLine("AwayFromZero: {0:N2}", sum / values.Length); + Console.WriteLine($"AwayFromZero: {sum / values.Length:N2}"); // Calculate mean with rounding to nearest. sum = 0; - foreach (var value in values) + foreach (decimal value in values) sum += Math.Round(value, 1, MidpointRounding.ToEven); - Console.WriteLine("ToEven: {0:N2}", sum / values.Length); + Console.WriteLine($"ToEven: {sum / values.Length:N2}"); // The example displays the following output: // True mean: 1.40 diff --git a/snippets/csharp/System/Decimal/Round/midpoint2.cs b/snippets/csharp/System/Decimal/Round/midpoint2.cs index 8b8a2b5d587..f4505a0aefe 100644 --- a/snippets/csharp/System/Decimal/Round/midpoint2.cs +++ b/snippets/csharp/System/Decimal/Round/midpoint2.cs @@ -5,11 +5,11 @@ public partial class Midpoint public static void Example2() { // - Double[] values = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, + double[] values = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7, 12.8, 12.9, 13.0 }; Console.WriteLine($"{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}"); - foreach (var value in values) + foreach (double value in values) Console.WriteLine($"{value,-10:R} {Math.Round(value),-10} " + $"{Math.Round(value, MidpointRounding.ToEven),-10} " + $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " + diff --git a/snippets/csharp/System/Decimal/Round/precision1.cs b/snippets/csharp/System/Decimal/Round/precision1.cs index 41ff90c6649..061d0f2b372 100644 --- a/snippets/csharp/System/Decimal/Round/precision1.cs +++ b/snippets/csharp/System/Decimal/Round/precision1.cs @@ -5,9 +5,7 @@ public class Precision1 // public static void Example() { - Console.WriteLine("{0,5} {1,20:R} {2,12} {3,15}\n", - "Value", "Full Precision", "ToEven", - "AwayFromZero"); + Console.WriteLine($"{"Value",5} {"Full Precision",20:R} {"ToEven",12} {"AwayFromZero",15}\n"); double value = 11.1; for (int ctr = 0; ctr <= 5; ctr++) value = RoundValueAndAdd(value); diff --git a/snippets/csharp/System/Decimal/Round/precision2.cs b/snippets/csharp/System/Decimal/Round/precision2.cs index 5adea943309..98b74b8d5ae 100644 --- a/snippets/csharp/System/Decimal/Round/precision2.cs +++ b/snippets/csharp/System/Decimal/Round/precision2.cs @@ -5,9 +5,7 @@ public class Precision2 // public static void Example() { - Console.WriteLine("{0,5} {1,20:R} {2,12} {3,15}\n", - "Value", "Full Precision", "ToEven", - "AwayFromZero"); + Console.WriteLine($"{"Value",5} {"Full Precision",20:R} {"ToEven",12} {"AwayFromZero",15}\n"); double value = 11.1; for (int ctr = 0; ctr <= 5; ctr++) value = RoundValueAndAdd(value); @@ -45,10 +43,10 @@ private static double RoundApproximate(double dbl, int digits, double margin, if (mode == MidpointRounding.AwayFromZero) return (value + 1) / Math.Pow(10, digits); else - if (value % 2 != 0) - return (value + 1) / Math.Pow(10, digits); - else - return value / Math.Pow(10, digits); + if (value % 2 != 0) + return (value + 1) / Math.Pow(10, digits); + else + return value / Math.Pow(10, digits); } // Any remaining fractional value greater than .5 is not a midpoint value. if (fraction > .5) diff --git a/snippets/csharp/System/Decimal/Round/single1.cs b/snippets/csharp/System/Decimal/Round/single1.cs index 4a0308b29d4..f5fc2ade7c1 100644 --- a/snippets/csharp/System/Decimal/Round/single1.cs +++ b/snippets/csharp/System/Decimal/Round/single1.cs @@ -5,18 +5,14 @@ public class SingleExample public static void Example() { // - Single value = 16.325f; - Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", - value, value.GetType().Name, (double)value, - ((double)(value)).GetType().Name); + float value = 16.325f; + Console.WriteLine($"Widening Conversion of {value:R} (type {value.GetType().Name}) to {(double)value:R} (type {((double)(value)).GetType().Name}): "); Console.WriteLine(Math.Round(value, 2)); Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero)); Console.WriteLine(); - Decimal decValue = (decimal)value; - Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", - value, value.GetType().Name, decValue, - decValue.GetType().Name); + decimal decValue = (decimal)value; + Console.WriteLine($"Cast of {value:R} (type {value.GetType().Name}) to {decValue} (type {decValue.GetType().Name}): "); Console.WriteLine(Math.Round(decValue, 2)); Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero)); diff --git a/snippets/csharp/System/Decimal/ToByte/tobyte_1.cs b/snippets/csharp/System/Decimal/ToByte/tobyte_1.cs index dc9b8d6a498..96e3ad652f3 100644 --- a/snippets/csharp/System/Decimal/ToByte/tobyte_1.cs +++ b/snippets/csharp/System/Decimal/ToByte/tobyte_1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(78000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(78000, 0, 0, false, 3), 78.999m, 255.999m, 256m, 127.999m, 128m, -0.999m, -1m, -128.999m, -129m }; - foreach (var value in values) { - try { - byte number = Decimal.ToByte(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + byte number = decimal.ToByte(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 78 --> 78 diff --git a/snippets/csharp/System/Decimal/ToDouble/tos_byte.cs b/snippets/csharp/System/Decimal/ToDouble/tos_byte.cs index f497cf13d58..b568f63151a 100644 --- a/snippets/csharp/System/Decimal/ToDouble/tos_byte.cs +++ b/snippets/csharp/System/Decimal/ToDouble/tos_byte.cs @@ -7,15 +7,15 @@ class DecimalToS_ByteDemo const string formatter = "{0,16}{1,19}{2,19}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToS_Byte( decimal argument ) + public static void DecimalToS_Byte(decimal argument) { object SByteValue; object ByteValue; @@ -23,51 +23,51 @@ public static void DecimalToS_Byte( decimal argument ) // Convert the argument to an sbyte value. try { - SByteValue = decimal.ToSByte( argument ); + SByteValue = decimal.ToSByte(argument); } - catch( Exception ex ) + catch (Exception ex) { - SByteValue = GetExceptionType( ex ); + SByteValue = GetExceptionType(ex); } // Convert the argument to a byte value. try { - ByteValue = decimal.ToByte( argument ); + ByteValue = decimal.ToByte(argument); } - catch( Exception ex ) + catch (Exception ex) { - ByteValue = GetExceptionType( ex ); + ByteValue = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - SByteValue, ByteValue ); + Console.WriteLine(formatter, argument, + SByteValue, ByteValue); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.ToSByte( decimal ) and \n" + " decimal.ToByte( decimal ) \nmethods " + "generates the following output. It \ndisplays " + - "several converted decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "sbyte/exception", "byte/exception" ); - Console.WriteLine( formatter, "----------------", - "---------------", "--------------" ); + "several converted decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "sbyte/exception", "byte/exception"); + Console.WriteLine(formatter, "----------------", + "---------------", "--------------"); // Convert decimal values and display the results. - DecimalToS_Byte( 78M ); - DecimalToS_Byte( new decimal( 78000, 0, 0, false, 3 ) ); - DecimalToS_Byte( 78.999M ); - DecimalToS_Byte( 255.999M ); - DecimalToS_Byte( 256M ); - DecimalToS_Byte( 127.999M ); - DecimalToS_Byte( 128M ); - DecimalToS_Byte( -0.999M ); - DecimalToS_Byte( -1M ); - DecimalToS_Byte( -128.999M ); - DecimalToS_Byte( -129M ); + DecimalToS_Byte(78M); + DecimalToS_Byte(new decimal(78000, 0, 0, false, 3)); + DecimalToS_Byte(78.999M); + DecimalToS_Byte(255.999M); + DecimalToS_Byte(256M); + DecimalToS_Byte(127.999M); + DecimalToS_Byte(128M); + DecimalToS_Byte(-0.999M); + DecimalToS_Byte(-1M); + DecimalToS_Byte(-128.999M); + DecimalToS_Byte(-129M); } } diff --git a/snippets/csharp/System/Decimal/ToDouble/tosgl_dbl.cs b/snippets/csharp/System/Decimal/ToDouble/tosgl_dbl.cs index ff56084931d..582dfbcdc4c 100644 --- a/snippets/csharp/System/Decimal/ToDouble/tosgl_dbl.cs +++ b/snippets/csharp/System/Decimal/ToDouble/tosgl_dbl.cs @@ -7,42 +7,42 @@ class DecimalToSgl_DblDemo static string formatter = "{0,30}{1,17}{2,23}"; // Convert the decimal argument; no exceptions are thrown. - public static void DecimalToSgl_Dbl( decimal argument ) + public static void DecimalToSgl_Dbl(decimal argument) { object SingleValue; object DoubleValue; // Convert the argument to a float value. - SingleValue = decimal.ToSingle( argument ); + SingleValue = decimal.ToSingle(argument); // Convert the argument to a double value. - DoubleValue = decimal.ToDouble( argument ); + DoubleValue = decimal.ToDouble(argument); - Console.WriteLine( formatter, argument, - SingleValue, DoubleValue ); + Console.WriteLine(formatter, argument, + SingleValue, DoubleValue); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.ToSingle( decimal ) and \n" + " decimal.ToDouble( decimal ) \nmethods " + "generates the following output. It \ndisplays " + - "several converted decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "float", "double" ); - Console.WriteLine( formatter, "----------------", - "-----", "------" ); + "several converted decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "float", "double"); + Console.WriteLine(formatter, "----------------", + "-----", "------"); // Convert decimal values and display the results. - DecimalToSgl_Dbl( 0.0000000000000000000000000001M ); - DecimalToSgl_Dbl( 0.0000000000123456789123456789M ); - DecimalToSgl_Dbl( 123M ); - DecimalToSgl_Dbl( new decimal( 123000000, 0, 0, false, 6 ) ); - DecimalToSgl_Dbl( 123456789.123456789M ); - DecimalToSgl_Dbl( 123456789123456789123456789M ); - DecimalToSgl_Dbl( decimal.MinValue ); - DecimalToSgl_Dbl( decimal.MaxValue ); + DecimalToSgl_Dbl(0.0000000000000000000000000001M); + DecimalToSgl_Dbl(0.0000000000123456789123456789M); + DecimalToSgl_Dbl(123M); + DecimalToSgl_Dbl(new decimal(123000000, 0, 0, false, 6)); + DecimalToSgl_Dbl(123456789.123456789M); + DecimalToSgl_Dbl(123456789123456789123456789M); + DecimalToSgl_Dbl(decimal.MinValue); + DecimalToSgl_Dbl(decimal.MaxValue); } } diff --git a/snippets/csharp/System/Decimal/ToDouble/tou_int16.cs b/snippets/csharp/System/Decimal/ToDouble/tou_int16.cs index f387843ebd9..855a45faf3d 100644 --- a/snippets/csharp/System/Decimal/ToDouble/tou_int16.cs +++ b/snippets/csharp/System/Decimal/ToDouble/tou_int16.cs @@ -7,15 +7,15 @@ class DecimalToU_Int16Demo const string formatter = "{0,16}{1,19}{2,19}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int16( decimal argument ) + public static void DecimalToU_Int16(decimal argument) { object Int16Value; object UInt16Value; @@ -23,51 +23,51 @@ public static void DecimalToU_Int16( decimal argument ) // Convert the argument to a short value. try { - Int16Value = decimal.ToInt16( argument ); + Int16Value = decimal.ToInt16(argument); } - catch( Exception ex ) + catch (Exception ex) { - Int16Value = GetExceptionType( ex ); + Int16Value = GetExceptionType(ex); } // Convert the argument to a ushort value. try { - UInt16Value = decimal.ToUInt16( argument ); + UInt16Value = decimal.ToUInt16(argument); } - catch( Exception ex ) + catch (Exception ex) { - UInt16Value = GetExceptionType( ex ); + UInt16Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int16Value, UInt16Value ); + Console.WriteLine(formatter, argument, + Int16Value, UInt16Value); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.ToInt16( decimal ) and \n" + " decimal.ToUInt16( decimal ) \nmethods " + "generates the following output. It \ndisplays " + - "several converted decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "short/exception", "ushort/exception" ); - Console.WriteLine( formatter, "----------------", - "---------------", "----------------" ); + "several converted decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "short/exception", "ushort/exception"); + Console.WriteLine(formatter, "----------------", + "---------------", "----------------"); // Convert decimal values and display the results. - DecimalToU_Int16( 123M ); - DecimalToU_Int16( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int16( 123.999M ); - DecimalToU_Int16( 65535.999M ); - DecimalToU_Int16( 65536M ); - DecimalToU_Int16( 32767.999M ); - DecimalToU_Int16( 32768M ); - DecimalToU_Int16( - 0.999M ); - DecimalToU_Int16( - 1M ); - DecimalToU_Int16( - 32768.999M ); - DecimalToU_Int16( - 32769M ); + DecimalToU_Int16(123M); + DecimalToU_Int16(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int16(123.999M); + DecimalToU_Int16(65535.999M); + DecimalToU_Int16(65536M); + DecimalToU_Int16(32767.999M); + DecimalToU_Int16(32768M); + DecimalToU_Int16(-0.999M); + DecimalToU_Int16(-1M); + DecimalToU_Int16(-32768.999M); + DecimalToU_Int16(-32769M); } } diff --git a/snippets/csharp/System/Decimal/ToDouble/tou_int32.cs b/snippets/csharp/System/Decimal/ToDouble/tou_int32.cs index 7d3f93f15c6..c75b64cca1e 100644 --- a/snippets/csharp/System/Decimal/ToDouble/tou_int32.cs +++ b/snippets/csharp/System/Decimal/ToDouble/tou_int32.cs @@ -7,15 +7,15 @@ class DecimalToU_Int32Demo const string formatter = "{0,17}{1,19}{2,19}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int32( decimal argument ) + public static void DecimalToU_Int32(decimal argument) { object Int32Value; object UInt32Value; @@ -23,51 +23,51 @@ public static void DecimalToU_Int32( decimal argument ) // Convert the argument to an int value. try { - Int32Value = decimal.ToInt32( argument ); + Int32Value = decimal.ToInt32(argument); } - catch( Exception ex ) + catch (Exception ex) { - Int32Value = GetExceptionType( ex ); + Int32Value = GetExceptionType(ex); } // Convert the argument to a uint value. try { - UInt32Value = decimal.ToUInt32( argument ); + UInt32Value = decimal.ToUInt32(argument); } - catch( Exception ex ) + catch (Exception ex) { - UInt32Value = GetExceptionType( ex ); + UInt32Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int32Value, UInt32Value ); + Console.WriteLine(formatter, argument, + Int32Value, UInt32Value); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.ToInt32( decimal ) and \n" + " decimal.ToUInt32( decimal ) \nmethods " + "generates the following output. It \ndisplays " + - "several converted decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "int/exception", "uint/exception" ); - Console.WriteLine( formatter, "----------------", - "-------------", "--------------" ); + "several converted decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "int/exception", "uint/exception"); + Console.WriteLine(formatter, "----------------", + "-------------", "--------------"); // Convert decimal values and display the results. - DecimalToU_Int32( 123M ); - DecimalToU_Int32( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int32( 123.999M ); - DecimalToU_Int32( 4294967295.999M ); - DecimalToU_Int32( 4294967296M ); - DecimalToU_Int32( 2147483647.999M ); - DecimalToU_Int32( 2147483648M ); - DecimalToU_Int32( - 0.999M ); - DecimalToU_Int32( - 1M ); - DecimalToU_Int32( - 2147483648.999M ); - DecimalToU_Int32( - 2147483649M ); + DecimalToU_Int32(123M); + DecimalToU_Int32(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int32(123.999M); + DecimalToU_Int32(4294967295.999M); + DecimalToU_Int32(4294967296M); + DecimalToU_Int32(2147483647.999M); + DecimalToU_Int32(2147483648M); + DecimalToU_Int32(-0.999M); + DecimalToU_Int32(-1M); + DecimalToU_Int32(-2147483648.999M); + DecimalToU_Int32(-2147483649M); } } diff --git a/snippets/csharp/System/Decimal/ToDouble/tou_int64.cs b/snippets/csharp/System/Decimal/ToDouble/tou_int64.cs index c68d4e93d80..7ddab1eedc5 100644 --- a/snippets/csharp/System/Decimal/ToDouble/tou_int64.cs +++ b/snippets/csharp/System/Decimal/ToDouble/tou_int64.cs @@ -7,15 +7,15 @@ class DecimalToU_Int64Demo const string formatter = "{0,25}{1,22}{2,22}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int64( decimal argument ) + public static void DecimalToU_Int64(decimal argument) { object Int64Value; object UInt64Value; @@ -23,51 +23,51 @@ public static void DecimalToU_Int64( decimal argument ) // Convert the argument to a long value. try { - Int64Value = decimal.ToInt64( argument ); + Int64Value = decimal.ToInt64(argument); } - catch( Exception ex ) + catch (Exception ex) { - Int64Value = GetExceptionType( ex ); + Int64Value = GetExceptionType(ex); } // Convert the argument to a ulong value. try { - UInt64Value = decimal.ToUInt64( argument ); + UInt64Value = decimal.ToUInt64(argument); } - catch( Exception ex ) + catch (Exception ex) { - UInt64Value = GetExceptionType( ex ); + UInt64Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int64Value, UInt64Value ); + Console.WriteLine(formatter, argument, + Int64Value, UInt64Value); } - public static void Main( ) + public static void Main() { - Console.WriteLine( "This example of the \n" + + Console.WriteLine("This example of the \n" + " decimal.ToInt64( decimal ) and \n" + " decimal.ToUInt64( decimal ) \nmethods " + "generates the following output. It \ndisplays " + - "several converted decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "long/exception", "ulong/exception" ); - Console.WriteLine( formatter, "----------------", - "--------------", "---------------" ); + "several converted decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "long/exception", "ulong/exception"); + Console.WriteLine(formatter, "----------------", + "--------------", "---------------"); // Convert decimal values and display the results. - DecimalToU_Int64( 123M ); - DecimalToU_Int64( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int64( 123.999M ); - DecimalToU_Int64( 18446744073709551615.999M ); - DecimalToU_Int64( 18446744073709551616M ); - DecimalToU_Int64( 9223372036854775807.999M ); - DecimalToU_Int64( 9223372036854775808M ); - DecimalToU_Int64( - 0.999M ); - DecimalToU_Int64( - 1M ); - DecimalToU_Int64( - 9223372036854775808.999M ); - DecimalToU_Int64( - 9223372036854775809M ); + DecimalToU_Int64(123M); + DecimalToU_Int64(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int64(123.999M); + DecimalToU_Int64(18446744073709551615.999M); + DecimalToU_Int64(18446744073709551616M); + DecimalToU_Int64(9223372036854775807.999M); + DecimalToU_Int64(9223372036854775808M); + DecimalToU_Int64(-0.999M); + DecimalToU_Int64(-1M); + DecimalToU_Int64(-9223372036854775808.999M); + DecimalToU_Int64(-9223372036854775809M); } } diff --git a/snippets/csharp/System/Decimal/ToInt16/toint16_1.cs b/snippets/csharp/System/Decimal/ToInt16/toint16_1.cs index 4c09ba47a7a..4e97ca68e4e 100644 --- a/snippets/csharp/System/Decimal/ToInt16/toint16_1.cs +++ b/snippets/csharp/System/Decimal/ToInt16/toint16_1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 65535.999m, 65536m, 32767.999m, 32768m, -0.999m, -1m, -32768.999m, -32769m }; - foreach (var value in values) { - try { - short number = Decimal.ToInt16(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + short number = decimal.ToInt16(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 diff --git a/snippets/csharp/System/Decimal/ToInt32/toint32_1.cs b/snippets/csharp/System/Decimal/ToInt32/toint32_1.cs index efa1f418ca6..df545884fa0 100644 --- a/snippets/csharp/System/Decimal/ToInt32/toint32_1.cs +++ b/snippets/csharp/System/Decimal/ToInt32/toint32_1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 4294967295.999m, 4294967296m, 4294967296m, 2147483647.999m, 2147483648m, -0.999m, -1m, -2147483648.999m, -2147483649m }; - foreach (var value in values) { - try { - int number = Decimal.ToInt32(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + int number = decimal.ToInt32(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 diff --git a/snippets/csharp/System/Decimal/ToInt64/toint64_1.cs b/snippets/csharp/System/Decimal/ToInt64/toint64_1.cs index 225802424ea..66b0445274e 100644 --- a/snippets/csharp/System/Decimal/ToInt64/toint64_1.cs +++ b/snippets/csharp/System/Decimal/ToInt64/toint64_1.cs @@ -3,26 +3,28 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 18446744073709551615.999m, 18446744073709551616m, 9223372036854775807.999m, 9223372036854775808m, -0.999m, -1m, -9223372036854775808.999m, -9223372036854775809m }; - foreach (var value in values) { - try { - long number = Decimal.ToInt64(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + long number = decimal.ToInt64(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 diff --git a/snippets/csharp/System/Decimal/ToSByte/tosbyte1.cs b/snippets/csharp/System/Decimal/ToSByte/tosbyte1.cs index 3fddd400556..6b5650d072a 100644 --- a/snippets/csharp/System/Decimal/ToSByte/tosbyte1.cs +++ b/snippets/csharp/System/Decimal/ToSByte/tosbyte1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(78000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(78000, 0, 0, false, 3), 78.999m, 255.999m, 256m, 127.999m, 128m, -0.999m, -1m, -128.999m, -129m }; - foreach (var value in values) { - try { - sbyte number = Decimal.ToSByte(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + sbyte number = decimal.ToSByte(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 78 --> 78 diff --git a/snippets/csharp/System/Decimal/ToString/ToString2.cs b/snippets/csharp/System/Decimal/ToString/ToString2.cs index 03b60e4bd66..be4fb19ed0f 100644 --- a/snippets/csharp/System/Decimal/ToString/ToString2.cs +++ b/snippets/csharp/System/Decimal/ToString/ToString2.cs @@ -3,137 +3,137 @@ public class Class1 { - public static void Main() - { - CallDefaultToString(); - Console.WriteLine("-----"); - CallToStringWithSpecificCultures(); - Console.WriteLine("-----"); - CallWithSpecificSpecifiers(); - Console.WriteLine("-----"); - CallWithSpecificSpecifiersAndCultures(); - } + public static void Main() + { + CallDefaultToString(); + Console.WriteLine("-----"); + CallToStringWithSpecificCultures(); + Console.WriteLine("-----"); + CallWithSpecificSpecifiers(); + Console.WriteLine("-----"); + CallWithSpecificSpecifiersAndCultures(); + } - private static void CallDefaultToString() - { - // - decimal value = -16325.62m; - // Display value using default ToString method. - Console.WriteLine(value.ToString()); // Displays -16325.62 - // Display value using some standard format specifiers. - Console.WriteLine(value.ToString("G")); // Displays -16325.62 - Console.WriteLine(value.ToString("C")); // Displays ($16,325.62) - Console.WriteLine(value.ToString("F")); // Displays -16325.62 - // - } + private static void CallDefaultToString() + { + // + decimal value = -16325.62m; + // Display value using default ToString method. + Console.WriteLine(value.ToString()); // Displays -16325.62 + // Display value using some standard format specifiers. + Console.WriteLine(value.ToString("G")); // Displays -16325.62 + Console.WriteLine(value.ToString("C")); // Displays ($16,325.62) + Console.WriteLine(value.ToString("F")); // Displays -16325.62 + // + } - private static void CallToStringWithSpecificCultures() - { - // - decimal value = -16325.62m; - // Display value using the invariant culture. - Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); - // Display value using the en-GB culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); - // Display value using the de-DE culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); - // This example displays the following output to the console: - // -16325.62 - // -16325.62 - // -16325,62 - // - } + private static void CallToStringWithSpecificCultures() + { + // + decimal value = -16325.62m; + // Display value using the invariant culture. + Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); + // Display value using the en-GB culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); + // Display value using the de-DE culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); + // This example displays the following output to the console: + // -16325.62 + // -16325.62 + // -16325,62 + // + } - private static void CallWithSpecificSpecifiers() - { - // - decimal value = 16325.62m; - string specifier; + private static void CallWithSpecificSpecifiers() + { + // + decimal value = 16325.62m; + string specifier; - // Use standard numeric format specifiers. - specifier = "G"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: G: 16325.62 - specifier = "C"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: C: $16,325.62 - specifier = "E04"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: E04: 1.6326E+004 - specifier = "F"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: F: 16325.62 - specifier = "N"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: N: 16,325.62 - specifier = "P"; - Console.WriteLine("{0}: {1}", specifier, (value/10000).ToString(specifier)); - // Displays: P: 163.26 % + // Use standard numeric format specifiers. + specifier = "G"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: G: 16325.62 + specifier = "C"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: C: $16,325.62 + specifier = "E04"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: E04: 1.6326E+004 + specifier = "F"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: F: 16325.62 + specifier = "N"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: N: 16,325.62 + specifier = "P"; + Console.WriteLine($"{specifier}: {(value / 10000).ToString(specifier)}"); + // Displays: P: 163.26 % - // Use custom numeric format specifiers. - specifier = "0,0.000"; - Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier)); - // Displays: 0,0.000: 16,325.620 - specifier = "#,#.00#;(#,#.00#)"; - Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier)); - // Displays: #,#.00#;(#,#.00#): (16,325.62) - // - } + // Use custom numeric format specifiers. + specifier = "0,0.000"; + Console.WriteLine($"{specifier}: {value.ToString(specifier)}"); + // Displays: 0,0.000: 16,325.620 + specifier = "#,#.00#;(#,#.00#)"; + Console.WriteLine($"{specifier}: {(value * -1).ToString(specifier)}"); + // Displays: #,#.00#;(#,#.00#): (16,325.62) + // + } - private static void CallWithSpecificSpecifiersAndCultures() - { - // - decimal value = 16325.62m; - string specifier; - CultureInfo culture; + private static void CallWithSpecificSpecifiersAndCultures() + { + // + decimal value = 16325.62m; + string specifier; + CultureInfo culture; - // Use standard numeric format specifiers. - specifier = "G"; - culture = CultureInfo.CreateSpecificCulture("eu-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,62 - Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); - // Displays: 16325.62 + // Use standard numeric format specifiers. + specifier = "G"; + culture = CultureInfo.CreateSpecificCulture("eu-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,62 + Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); + // Displays: 16325.62 - specifier = "C"; - culture = CultureInfo.CreateSpecificCulture("en-US"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: $16,325.62 - culture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: £16,325.62 + specifier = "C"; + culture = CultureInfo.CreateSpecificCulture("en-US"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: $16,325.62 + culture = CultureInfo.CreateSpecificCulture("en-GB"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: £16,325.62 - specifier = "E04"; - culture = CultureInfo.CreateSpecificCulture("sv-SE"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1,6326E+004 - culture = CultureInfo.CreateSpecificCulture("en-NZ"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1.6326E+004 + specifier = "E04"; + culture = CultureInfo.CreateSpecificCulture("sv-SE"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1,6326E+004 + culture = CultureInfo.CreateSpecificCulture("en-NZ"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1.6326E+004 - specifier = "F"; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,62 - culture = CultureInfo.CreateSpecificCulture("en-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325.62 + specifier = "F"; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,62 + culture = CultureInfo.CreateSpecificCulture("en-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325.62 - specifier = "N"; - culture = CultureInfo.CreateSpecificCulture("es-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16.325,62 - culture = CultureInfo.CreateSpecificCulture("fr-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16 325,62 + specifier = "N"; + culture = CultureInfo.CreateSpecificCulture("es-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16.325,62 + culture = CultureInfo.CreateSpecificCulture("fr-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16 325,62 - specifier = "P"; - culture = CultureInfo.InvariantCulture; - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.26 % - culture = CultureInfo.CreateSpecificCulture("ar-EG"); - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.256 % - // - } + specifier = "P"; + culture = CultureInfo.InvariantCulture; + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.26 % + culture = CultureInfo.CreateSpecificCulture("ar-EG"); + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.256 % + // + } } diff --git a/snippets/csharp/System/Decimal/ToString/tostring.cs b/snippets/csharp/System/Decimal/ToString/tostring.cs index 80ac65eac19..bf607c900f6 100644 --- a/snippets/csharp/System/Decimal/ToString/tostring.cs +++ b/snippets/csharp/System/Decimal/ToString/tostring.cs @@ -2,15 +2,15 @@ // Example for the Decimal.ToString( ) methods. using System; using System.Globalization; -using Microsoft.VisualBasic; + class DecimalToStringDemo { - static void Main( ) + static void Main() { decimal nineBillPlus = 9876543210.9876543210M; - Console.WriteLine( "This example of\n" + + Console.WriteLine("This example of\n" + " Decimal.ToString( ), \n" + " Decimal.ToString( String ),\n" + " Decimal.ToString( IFormatProvider ), and \n" + @@ -19,50 +19,44 @@ static void Main( ) "[{0}] culture.\nDecimal numbers are formatted " + "with various combinations \nof format strings " + "and IFormatProvider.", - CultureInfo.CurrentCulture.Name ); + CultureInfo.CurrentCulture.Name); // Format the number without and with format strings. - Console.WriteLine( "\nIFormatProvider is not " + + Console.WriteLine("\nIFormatProvider is not " + "used; the default culture is [{0}]:", - CultureInfo.CurrentCulture.Name ); - Console.WriteLine( " {0,-30}{1}", "No format string:", - nineBillPlus.ToString( ) ); - Console.WriteLine( " {0,-30}{1}", "'N' format string:", - nineBillPlus.ToString( "N" ) ); - Console.WriteLine( " {0,-30}{1}", "'N5' format string:", - nineBillPlus.ToString( "N5" ) ); + CultureInfo.CurrentCulture.Name); + Console.WriteLine($" {"No format string:",-30}{nineBillPlus.ToString()}"); + Console.WriteLine($" {"'N' format string:",-30}{nineBillPlus.ToString("N")}"); + Console.WriteLine($" {"'N5' format string:",-30}{nineBillPlus.ToString("N5")}"); // Create a CultureInfo object for another culture. Use // [Dutch - The Netherlands] unless the current culture // is Dutch language. In that case use [English - U.S.]. string cultureName = - CultureInfo.CurrentCulture.Name.Substring( 0, 2 ) == + CultureInfo.CurrentCulture.Name.Substring(0, 2) == "nl" ? "en-US" : "nl-NL"; - CultureInfo culture = new CultureInfo( cultureName ); + CultureInfo culture = new(cultureName); // Use the CultureInfo object for an IFormatProvider. - Console.WriteLine( "\nA CultureInfo object " + + Console.WriteLine("\nA CultureInfo object " + "for [{0}] is used for the IFormatProvider: ", - cultureName ); - Console.WriteLine( " {0,-30}{1}", "No format string:", - nineBillPlus.ToString( culture ) ); - Console.WriteLine( " {0,-30}{1}", "'N5' format string:", - nineBillPlus.ToString( "N5", culture ) ); + cultureName); + Console.WriteLine($" {"No format string:",-30}{nineBillPlus.ToString(culture)}"); + Console.WriteLine($" {"'N5' format string:",-30}{nineBillPlus.ToString("N5", culture)}"); // Get the NumberFormatInfo object from CultureInfo, and // then change the digit group size to 4 and the digit // separator to '_'. NumberFormatInfo numInfo = culture.NumberFormat; - numInfo.NumberGroupSizes = new int[ ] { 4 }; + numInfo.NumberGroupSizes = new int[] { 4 }; numInfo.NumberGroupSeparator = "_"; // Use a NumberFormatInfo object for IFormatProvider. Console.WriteLine( "\nA NumberFormatInfo object with digit group " + "size = 4 and \ndigit separator " + - "= '_' is used for the IFormatProvider:" ); - Console.WriteLine( " {0,-30}{1}", "'N5' format string:", - nineBillPlus.ToString( "N5", culture ) ); + "= '_' is used for the IFormatProvider:"); + Console.WriteLine($" {"'N5' format string:",-30}{nineBillPlus.ToString("N5", culture)}"); } } diff --git a/snippets/csharp/System/Decimal/ToUInt16/touint16_1.cs b/snippets/csharp/System/Decimal/ToUInt16/touint16_1.cs index 57af4e6bb64..b05aa634215 100644 --- a/snippets/csharp/System/Decimal/ToUInt16/touint16_1.cs +++ b/snippets/csharp/System/Decimal/ToUInt16/touint16_1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 65535.999m, 65536m, 32767.999m, 32768m, -0.999m, -1m, -32768.999m, -32769m }; - foreach (var value in values) { - try { - ushort number = Decimal.ToUInt16(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + ushort number = decimal.ToUInt16(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 diff --git a/snippets/csharp/System/Decimal/ToUInt32/touint32_1.cs b/snippets/csharp/System/Decimal/ToUInt32/touint32_1.cs index 00656473f10..7d1d819200c 100644 --- a/snippets/csharp/System/Decimal/ToUInt32/touint32_1.cs +++ b/snippets/csharp/System/Decimal/ToUInt32/touint32_1.cs @@ -3,24 +3,26 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 4294967295.999m, 4294967296m, 4294967296m, 2147483647.999m, 2147483648m, -0.999m, -1m, -2147483648.999m, -2147483649m }; - foreach (var value in values) { - try { - uint number = Decimal.ToUInt32(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + uint number = decimal.ToUInt32(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 @@ -35,4 +37,4 @@ public static void Main( ) // OverflowException: -1 // OverflowException: -2147483648.999 // OverflowException: -2147483649 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Decimal/ToUInt64/touint64_1.cs b/snippets/csharp/System/Decimal/ToUInt64/touint64_1.cs index 3405d78ccae..ed278b4de02 100644 --- a/snippets/csharp/System/Decimal/ToUInt64/touint64_1.cs +++ b/snippets/csharp/System/Decimal/ToUInt64/touint64_1.cs @@ -3,26 +3,28 @@ class Example { - public static void Main( ) - { - decimal[] values = { 123m, new Decimal(123000, 0, 0, false, 3), + public static void Main() + { + decimal[] values = { 123m, new decimal(123000, 0, 0, false, 3), 123.999m, 18446744073709551615.999m, 18446744073709551616m, 9223372036854775807.999m, 9223372036854775808m, -0.999m, -1m, -9223372036854775808.999m, -9223372036854775809m }; - foreach (var value in values) { - try { - ulong number = Decimal.ToUInt64(value); - Console.WriteLine("{0} --> {1}", value, number); - } - catch (OverflowException e) - { - Console.WriteLine("{0}: {1}", e.GetType().Name, value); - } - } - } + foreach (decimal value in values) + { + try + { + ulong number = decimal.ToUInt64(value); + Console.WriteLine($"{value} --> {number}"); + } + catch (OverflowException e) + { + Console.WriteLine($"{e.GetType().Name}: {value}"); + } + } + } } // The example displays the following output: // 123 --> 123 diff --git a/snippets/csharp/System/Decimal/TryParse/TryParse.cs b/snippets/csharp/System/Decimal/TryParse/TryParse.cs index 97e9d4723f2..7c0d2d4fe93 100644 --- a/snippets/csharp/System/Decimal/TryParse/TryParse.cs +++ b/snippets/csharp/System/Decimal/TryParse/TryParse.cs @@ -3,101 +3,101 @@ public class Class1 { - public static void Main() - { - CallTryParse1(); - Console.WriteLine("----------"); - CallTryParse2(); - } + public static void Main() + { + CallTryParse1(); + Console.WriteLine("----------"); + CallTryParse2(); + } - private static void CallTryParse1() - { - // - string value; - decimal number; + private static void CallTryParse1() + { + // + string value; + decimal number; - // Parse a floating-point value with a thousands separator. - value = "1,643.57"; - if (Decimal.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a thousands separator. + value = "1,643.57"; + if (decimal.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a floating-point value with a currency symbol and a - // thousands separator. - value = "$1,643.57"; - if (Decimal.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a currency symbol and a + // thousands separator. + value = "$1,643.57"; + if (decimal.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse value in exponential notation. - value = "-1.643e6"; - if (Decimal.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse value in exponential notation. + value = "-1.643e6"; + if (decimal.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a negative integer value. - value = "-1689346178821"; - if (Decimal.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); - // The example displays the following output to the console: - // 1643.57 - // Unable to parse '$1,643.57'. - // Unable to parse '-1.643e6'. - // -1689346178821 - // - } + // Parse a negative integer value. + value = "-1689346178821"; + if (decimal.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); + // The example displays the following output to the console: + // 1643.57 + // Unable to parse '$1,643.57'. + // Unable to parse '-1.643e6'. + // -1689346178821 + // + } - private static void CallTryParse2() - { - // - string value; - NumberStyles style; - CultureInfo culture; - decimal number; + private static void CallTryParse2() + { + // + string value; + NumberStyles style; + CultureInfo culture; + decimal number; - // Parse currency value using en-GB culture. - value = "£1,097.63"; - style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; - culture = CultureInfo.CreateSpecificCulture("en-GB"); - if (Decimal.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '£1,097.63' to 1097.63. + // Parse currency value using en-GB culture. + value = "£1,097.63"; + style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; + culture = CultureInfo.CreateSpecificCulture("en-GB"); + if (decimal.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '£1,097.63' to 1097.63. - value = "1345,978"; - style = NumberStyles.AllowDecimalPoint; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - if (Decimal.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '1345,978' to 1345.978. + value = "1345,978"; + style = NumberStyles.AllowDecimalPoint; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + if (decimal.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '1345,978' to 1345.978. - value = "1.345,978"; - style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; - culture = CultureInfo.CreateSpecificCulture("es-ES"); - if (Decimal.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '1.345,978' to 1345.978. + value = "1.345,978"; + style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; + culture = CultureInfo.CreateSpecificCulture("es-ES"); + if (decimal.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '1.345,978' to 1345.978. - value = "1 345,978"; - if (Decimal.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Unable to convert '1 345,978'. - // - } + value = "1 345,978"; + if (decimal.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Unable to convert '1 345,978'. + // + } } diff --git a/snippets/csharp/System/Decimal/op_Addition/addition1.cs b/snippets/csharp/System/Decimal/op_Addition/addition1.cs index 885cfac38cb..ce932ef2c3d 100644 --- a/snippets/csharp/System/Decimal/op_Addition/addition1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/addition1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - Decimal number1 = 120.07m; - Decimal number2 = 163.19m; - Decimal number3 = number1 + number2; - Console.WriteLine("{0} + {1} = {2}", - number1, number2, number3); - } + public static void Main() + { + decimal number1 = 120.07m; + decimal number2 = 163.19m; + decimal number3 = number1 + number2; + Console.WriteLine($"{number1} + {number2} = {number3}"); + } } // The example displays the following output: // 120.07 + 163.19 = 283.26 diff --git a/snippets/csharp/System/Decimal/op_Addition/decrement1.cs b/snippets/csharp/System/Decimal/op_Addition/decrement1.cs index e6f4f3b7c6b..d34fd7e07d3 100644 --- a/snippets/csharp/System/Decimal/op_Addition/decrement1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/decrement1.cs @@ -3,12 +3,12 @@ public class Example { - public static void Main() - { - Decimal number = 1079.8m; - Console.WriteLine("Original value: {0:N}", number); - Console.WriteLine("Decremented value: {0:N}", --number); - } + public static void Main() + { + decimal number = 1079.8m; + Console.WriteLine($"Original value: {number:N}"); + Console.WriteLine($"Decremented value: {--number:N}"); + } } // The example displays the following output: // Original value: 1,079.80 diff --git a/snippets/csharp/System/Decimal/op_Addition/decrement2.cs b/snippets/csharp/System/Decimal/op_Addition/decrement2.cs index 38e6aac08a3..eed75d5b509 100644 --- a/snippets/csharp/System/Decimal/op_Addition/decrement2.cs +++ b/snippets/csharp/System/Decimal/op_Addition/decrement2.cs @@ -3,12 +3,12 @@ public class Example { - public static void Main() - { - Decimal number = 1079.8m; - Console.WriteLine("Original value: {0:N}", number); - Console.WriteLine("Decremented value: {0:N}", Decimal.Subtract(number, 1)); - } + public static void Main() + { + decimal number = 1079.8m; + Console.WriteLine($"Original value: {number:N}"); + Console.WriteLine($"Decremented value: {decimal.Subtract(number, 1):N}"); + } } // The example displays the following output: // Original value: 1,079.80 diff --git a/snippets/csharp/System/Decimal/op_Addition/division1.cs b/snippets/csharp/System/Decimal/op_Addition/division1.cs index 7d477d7e406..ecd1f689443 100644 --- a/snippets/csharp/System/Decimal/op_Addition/division1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/division1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - Decimal number1 = 16.8m; - Decimal number2 = 4.1m; - Decimal number3 = number1 / number2; - Console.WriteLine("{0:N2} / {1:N2} = {2:N2}", - number1, number2, number3); - } + public static void Main() + { + decimal number1 = 16.8m; + decimal number2 = 4.1m; + decimal number3 = number1 / number2; + Console.WriteLine($"{number1:N2} / {number2:N2} = {number3:N2}"); + } } // The example displays the following output: // 16.80 / 4.10 = 4.10 diff --git a/snippets/csharp/System/Decimal/op_Addition/equality1.cs b/snippets/csharp/System/Decimal/op_Addition/equality1.cs index 9badd9be9ad..17fdad0e4aa 100644 --- a/snippets/csharp/System/Decimal/op_Addition/equality1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/equality1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0695m; - Decimal number2 = 16354.0699m; - Console.WriteLine("{0} = {1}: {2}", number1, - number2, number1 == number2); + public static void Main() + { + decimal number1 = 16354.0695m; + decimal number2 = 16354.0699m; + Console.WriteLine($"{number1} = {number2}: {number1 == number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} = {1}: {2}", number1, - number2, number1 == number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} = {number2}: {number1 == number2}"); + } } // The example displays the following output: // 16354.0695 = 16354.0699: False diff --git a/snippets/csharp/System/Decimal/op_Addition/greaterthan1.cs b/snippets/csharp/System/Decimal/op_Addition/greaterthan1.cs index ce44c158459..f576cdd5010 100644 --- a/snippets/csharp/System/Decimal/op_Addition/greaterthan1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/greaterthan1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0699m; - Decimal number2 = 16354.0695m; - Console.WriteLine("{0} > {1}: {2}", number1, - number2, number1 > number2); + public static void Main() + { + decimal number1 = 16354.0699m; + decimal number2 = 16354.0695m; + Console.WriteLine($"{number1} > {number2}: {number1 > number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} > {1}: {2}", number1, - number2, number1 > number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} > {number2}: {number1 > number2}"); + } } // The example displays the following output: // 16354.0699 > 16354.0695: True diff --git a/snippets/csharp/System/Decimal/op_Addition/greaterthanorequal1.cs b/snippets/csharp/System/Decimal/op_Addition/greaterthanorequal1.cs index 8505e8ae279..c6ee8c6697e 100644 --- a/snippets/csharp/System/Decimal/op_Addition/greaterthanorequal1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/greaterthanorequal1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0699m; - Decimal number2 = 16354.0695m; - Console.WriteLine("{0} >= {1}: {2}", number1, - number2, number1 >= number2); + public static void Main() + { + decimal number1 = 16354.0699m; + decimal number2 = 16354.0695m; + Console.WriteLine($"{number1} >= {number2}: {number1 >= number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} >= {1}: {2}", number1, - number2, number1 >= number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} >= {number2}: {number1 >= number2}"); + } } // The example displays the following output: // 16354.0699 >= 16354.0695: True diff --git a/snippets/csharp/System/Decimal/op_Addition/increment1.cs b/snippets/csharp/System/Decimal/op_Addition/increment1.cs index faa3619b751..cc86873aaec 100644 --- a/snippets/csharp/System/Decimal/op_Addition/increment1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/increment1.cs @@ -3,12 +3,12 @@ public class Example { - public static void Main() - { - Decimal number = 1079.8m; - Console.WriteLine("Original value: {0:N}", number); - Console.WriteLine("Incremented value: {0:N}", ++number); - } + public static void Main() + { + decimal number = 1079.8m; + Console.WriteLine($"Original value: {number:N}"); + Console.WriteLine($"Incremented value: {++number:N}"); + } } // The example displays the following output: // Original value: 1,079.80 diff --git a/snippets/csharp/System/Decimal/op_Addition/increment2.cs b/snippets/csharp/System/Decimal/op_Addition/increment2.cs index c1ccb66f1b4..a83c7608a4d 100644 --- a/snippets/csharp/System/Decimal/op_Addition/increment2.cs +++ b/snippets/csharp/System/Decimal/op_Addition/increment2.cs @@ -3,12 +3,12 @@ public class Example { - public static void Main() - { - Decimal number = 1079.8m; - Console.WriteLine("Original value: {0:N}", number); - Console.WriteLine("Incremented value: {0:N}", Decimal.Add(number, 1)); - } + public static void Main() + { + decimal number = 1079.8m; + Console.WriteLine($"Original value: {number:N}"); + Console.WriteLine($"Incremented value: {decimal.Add(number, 1):N}"); + } } // The example displays the following output: // Original value: 1,079.80 diff --git a/snippets/csharp/System/Decimal/op_Addition/inequality1.cs b/snippets/csharp/System/Decimal/op_Addition/inequality1.cs index 3925d1142f5..f252f8bbdc0 100644 --- a/snippets/csharp/System/Decimal/op_Addition/inequality1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/inequality1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0695m; - Decimal number2 = 16354.0699m; - Console.WriteLine("{0} <> {1}: {2}", number1, - number2, number1 != number2); + public static void Main() + { + decimal number1 = 16354.0695m; + decimal number2 = 16354.0699m; + Console.WriteLine($"{number1} <> {number2}: {number1 != number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} <> {1}: {2}", number1, - number2, number1 != number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} <> {number2}: {number1 != number2}"); + } } // The example displays the following output: // 16354.0695 <> 16354.0699: True diff --git a/snippets/csharp/System/Decimal/op_Addition/lessthan1.cs b/snippets/csharp/System/Decimal/op_Addition/lessthan1.cs index c009e5343cc..522b496b29c 100644 --- a/snippets/csharp/System/Decimal/op_Addition/lessthan1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/lessthan1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0699m; - Decimal number2 = 16354.0695m; - Console.WriteLine("{0} < {1}: {2}", number1, - number2, number1 < number2); + public static void Main() + { + decimal number1 = 16354.0699m; + decimal number2 = 16354.0695m; + Console.WriteLine($"{number1} < {number2}: {number1 < number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} < {1}: {2}", number1, - number2, number1 < number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} < {number2}: {number1 < number2}"); + } } // The example displays the following output: // 16354.0699 < 16354.0695: False diff --git a/snippets/csharp/System/Decimal/op_Addition/lessthanorequal1.cs b/snippets/csharp/System/Decimal/op_Addition/lessthanorequal1.cs index 76dadfeb3b9..f12852af04a 100644 --- a/snippets/csharp/System/Decimal/op_Addition/lessthanorequal1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/lessthanorequal1.cs @@ -3,18 +3,16 @@ public class Example { - public static void Main() - { - Decimal number1 = 16354.0699m; - Decimal number2 = 16354.0695m; - Console.WriteLine("{0} <= {1}: {2}", number1, - number2, number1 <= number2); + public static void Main() + { + decimal number1 = 16354.0699m; + decimal number2 = 16354.0695m; + Console.WriteLine($"{number1} <= {number2}: {number1 <= number2}"); - number1 = Decimal.Round(number1, 2); - number2 = Decimal.Round(number2, 2); - Console.WriteLine("{0} <= {1}: {2}", number1, - number2, number1 <= number2); - } + number1 = decimal.Round(number1, 2); + number2 = decimal.Round(number2, 2); + Console.WriteLine($"{number1} <= {number2}: {number1 <= number2}"); + } } // The example displays the following output: // 16354.0699 <= 16354.0695: False diff --git a/snippets/csharp/System/Decimal/op_Addition/modulus1.cs b/snippets/csharp/System/Decimal/op_Addition/modulus1.cs index 2e710cb5045..491f942c13f 100644 --- a/snippets/csharp/System/Decimal/op_Addition/modulus1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/modulus1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - Decimal number1 = 16.8m; - Decimal number2 = 4.1m; - Decimal number3 = number1 % number2; - Console.WriteLine("{0:N2} % {1:N2} = {2:N2}", - number1, number2, number3); - } + public static void Main() + { + decimal number1 = 16.8m; + decimal number2 = 4.1m; + decimal number3 = number1 % number2; + Console.WriteLine($"{number1:N2} % {number2:N2} = {number3:N2}"); + } } // The example displays the following output: // 16.80 % 4.10 = 0.40 diff --git a/snippets/csharp/System/Decimal/op_Addition/multiply1.cs b/snippets/csharp/System/Decimal/op_Addition/multiply1.cs index 6f9d8900139..3fe22f308e2 100644 --- a/snippets/csharp/System/Decimal/op_Addition/multiply1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/multiply1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - Decimal number1 = 16.8m; - Decimal number2 = 4.1m; - Decimal number3 = number1 * number2; - Console.WriteLine("{0:N2} x {1:N2} = {2:N2}", - number1, number2, number3); - } + public static void Main() + { + decimal number1 = 16.8m; + decimal number2 = 4.1m; + decimal number3 = number1 * number2; + Console.WriteLine($"{number1:N2} x {number2:N2} = {number3:N2}"); + } } // The example displays the following output: // 16.80 x 4.10 = 68.88 diff --git a/snippets/csharp/System/Decimal/op_Addition/subtraction1.cs b/snippets/csharp/System/Decimal/op_Addition/subtraction1.cs index 230ec89c07c..c43133452b1 100644 --- a/snippets/csharp/System/Decimal/op_Addition/subtraction1.cs +++ b/snippets/csharp/System/Decimal/op_Addition/subtraction1.cs @@ -3,14 +3,13 @@ public class Example { - public static void Main() - { - Decimal number1 = 120.07m; - Decimal number2 = 163.19m; - Decimal number3 = number1 - number2; - Console.WriteLine("{0} - {1} = {2}", - number1, number2, number3); - } + public static void Main() + { + decimal number1 = 120.07m; + decimal number2 = 163.19m; + decimal number3 = number1 - number2; + Console.WriteLine($"{number1} - {number2} = {number3}"); + } } // The example displays the following output: // 120.07 - 163.19 = -43.12 diff --git a/snippets/csharp/System/Decimal/op_Explicit/cfromchar.cs b/snippets/csharp/System/Decimal/op_Explicit/cfromchar.cs index b543c851e82..ddeffab3833 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/cfromchar.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/cfromchar.cs @@ -6,14 +6,13 @@ class Example public static void Main() { // Define an array of Char values. - Char[] values = { '\0', ' ', '*', 'A', 'a', '{', 'Æ' }; + char[] values = { '\0', ' ', '*', 'A', 'a', '{', 'Æ' }; // Convert each Char value to a Decimal. - foreach (var value in values) { - decimal decValue = value; - Console.WriteLine("'{0}' ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (char value in values) + { + decimal decValue = value; + Console.WriteLine($"'{value}' ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/cfromdouble.cs b/snippets/csharp/System/Decimal/op_Explicit/cfromdouble.cs index 76e4c3cfee7..b0ee28ce5d4 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/cfromdouble.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/cfromdouble.cs @@ -7,15 +7,15 @@ class DecimalFromDoubleDemo const string formatter = "{0,25:E16}{1,33}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the double argument; catch exceptions that are thrown. - public static void DecimalFromDouble( double argument ) + public static void DecimalFromDouble(double argument) { object decValue; @@ -24,33 +24,33 @@ public static void DecimalFromDouble( double argument ) { decValue = (decimal)argument; } - catch( Exception ex ) + catch (Exception ex) { - decValue = GetExceptionType( ex ); + decValue = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, decValue ); + Console.WriteLine(formatter, argument, decValue); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the explicit conversion from double " + - "to decimal \ngenerates the following output.\n" ); - Console.WriteLine( formatter, "double argument", - "decimal value" ); - Console.WriteLine( formatter, "---------------", - "-------------" ); + "to decimal \ngenerates the following output.\n"); + Console.WriteLine(formatter, "double argument", + "decimal value"); + Console.WriteLine(formatter, "---------------", + "-------------"); // Convert double values and display the results. - DecimalFromDouble( 1.234567890123E-30 ); - DecimalFromDouble( 1.2345678901234E-25 ); - DecimalFromDouble( 1.23456789012345E-20 ); - DecimalFromDouble( 1.234567890123456E-10 ); - DecimalFromDouble( 1.2345678901234567 ); - DecimalFromDouble( 1.23456789012345678E+12 ); - DecimalFromDouble( 1.234567890123456789E+28 ); - DecimalFromDouble( 1.234567890123456789E+30 ); + DecimalFromDouble(1.234567890123E-30); + DecimalFromDouble(1.2345678901234E-25); + DecimalFromDouble(1.23456789012345E-20); + DecimalFromDouble(1.234567890123456E-10); + DecimalFromDouble(1.2345678901234567); + DecimalFromDouble(1.23456789012345678E+12); + DecimalFromDouble(1.234567890123456789E+28); + DecimalFromDouble(1.234567890123456789E+30); } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/cfromsingle.cs b/snippets/csharp/System/Decimal/op_Explicit/cfromsingle.cs index d81c0a38f1c..4315f23b28f 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/cfromsingle.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/cfromsingle.cs @@ -7,15 +7,15 @@ class DecimalFromSingleDemo const string formatter = "{0,16:E7}{1,33}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the float argument; catch exceptions that are thrown. - public static void DecimalFromSingle( float argument ) + public static void DecimalFromSingle(float argument) { object decValue; @@ -24,33 +24,33 @@ public static void DecimalFromSingle( float argument ) { decValue = (decimal)argument; } - catch( Exception ex ) + catch (Exception ex) { - decValue = GetExceptionType( ex ); + decValue = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, decValue ); + Console.WriteLine(formatter, argument, decValue); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the explicit conversion from float " + - "to decimal \ngenerates the following output.\n" ); - Console.WriteLine( formatter, "float argument", - "decimal value" ); - Console.WriteLine( formatter, "--------------", - "-------------" ); + "to decimal \ngenerates the following output.\n"); + Console.WriteLine(formatter, "float argument", + "decimal value"); + Console.WriteLine(formatter, "--------------", + "-------------"); // Convert float values and display the results. - DecimalFromSingle( 1.2345E-30F ); - DecimalFromSingle( 1.2345E-26F ); - DecimalFromSingle( 1.23456E-22F ); - DecimalFromSingle( 1.23456E-12F ); - DecimalFromSingle( 1.234567F ); - DecimalFromSingle( 1.234567E+12F ); - DecimalFromSingle( 1.2345678E+28F ); - DecimalFromSingle( 1.2345678E+30F ); + DecimalFromSingle(1.2345E-30F); + DecimalFromSingle(1.2345E-26F); + DecimalFromSingle(1.23456E-22F); + DecimalFromSingle(1.23456E-12F); + DecimalFromSingle(1.234567F); + DecimalFromSingle(1.234567E+12F); + DecimalFromSingle(1.2345678E+28F); + DecimalFromSingle(1.2345678E+30F); } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctochar.cs b/snippets/csharp/System/Decimal/op_Explicit/ctochar.cs index 66cc3b03329..11224472ea6 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctochar.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctochar.cs @@ -3,25 +3,26 @@ class Example { - public static void Main( ) - { - // Define an array of decimal values. - decimal[] values = { 3.33m, 55.5m, 77.7m, 123m, 123.999m, 170m, + public static void Main() + { + // Define an array of decimal values. + decimal[] values = { 3.33m, 55.5m, 77.7m, 123m, 123.999m, 170m, 188.88m, 222m, 244m, 8217m, 8250m, 65536m, -1m }; - // Convert each value to a Char. - foreach (decimal value in values) { - try { - char charValue = (char) value; - Console.WriteLine("{0} --> {1} ({2:X4})", value, - charValue, (ushort) charValue); - } - catch (OverflowException) { - Console.WriteLine("OverflowException: Cannot convert {0}", - value); - } - } - } + // Convert each value to a Char. + foreach (decimal value in values) + { + try + { + char charValue = (char)value; + Console.WriteLine($"{value} --> {charValue} ({(ushort)charValue:X4})"); + } + catch (OverflowException) + { + Console.WriteLine($"OverflowException: Cannot convert {value}"); + } + } + } } // The example displays the following output: // 3.33 --> ? (0003) diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctos_byte.cs b/snippets/csharp/System/Decimal/op_Explicit/ctos_byte.cs index 74b436a6423..c6ae3bfac3f 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctos_byte.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctos_byte.cs @@ -6,21 +6,21 @@ class Example public static void Main() { // Define an array of decimal values. - decimal[] values = { 78m, new Decimal(78000, 0, 0, false, 3), + decimal[] values = { 78m, new decimal(78000, 0, 0, false, 3), 78.999m, 255.999m, 256m, 127.999m, 128m, -0.999m, -1m, -128.999m, -129m }; - foreach (var value in values) { - try { - Byte byteValue = (Byte) value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, byteValue, - byteValue.GetType().Name); - } - catch (OverflowException) { - Console.WriteLine("OverflowException: Cannot convert {0}", - value); - } - } + foreach (decimal value in values) + { + try + { + byte byteValue = (byte)value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {byteValue} ({byteValue.GetType().Name})"); + } + catch (OverflowException) + { + Console.WriteLine($"OverflowException: Cannot convert {value}"); + } + } } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctosgl_dbl.cs b/snippets/csharp/System/Decimal/op_Explicit/ctosgl_dbl.cs index c196ab9ca52..5fe4ce931cf 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctosgl_dbl.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctosgl_dbl.cs @@ -3,7 +3,7 @@ class Example { - public static void Main( ) + public static void Main() { // Define an array of decimal values. decimal[] values = { 0.0000000000000000000000000001M, @@ -13,12 +13,11 @@ public static void Main( ) 123456789123456789123456789M, decimal.MinValue, decimal.MaxValue }; // Convert each value to a double. - foreach (var value in values) { - double dblValue = (double) value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, dblValue, - dblValue.GetType().Name); - } + foreach (decimal value in values) + { + double dblValue = (double)value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})"); + } } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctou_int16.cs b/snippets/csharp/System/Decimal/op_Explicit/ctou_int16.cs index 201699b423b..e0c9377c94a 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctou_int16.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctou_int16.cs @@ -8,15 +8,15 @@ class DecimalToU_Int16Demo const string formatter = "{0,16}{1,19}{2,19}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int16( decimal argument ) + public static void DecimalToU_Int16(decimal argument) { object Int16Value; object UInt16Value; @@ -26,9 +26,9 @@ public static void DecimalToU_Int16( decimal argument ) { Int16Value = (short)argument; } - catch( Exception ex ) + catch (Exception ex) { - Int16Value = GetExceptionType( ex ); + Int16Value = GetExceptionType(ex); } // Convert the argument to a ushort value. @@ -36,39 +36,39 @@ public static void DecimalToU_Int16( decimal argument ) { UInt16Value = (ushort)argument; } - catch( Exception ex ) + catch (Exception ex) { - UInt16Value = GetExceptionType( ex ); + UInt16Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int16Value, UInt16Value ); + Console.WriteLine(formatter, argument, + Int16Value, UInt16Value); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the explicit conversions from decimal " + "to short \nand decimal to ushort generates the " + "following output. It displays \nseveral converted " + - "decimal values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "short/exception", "ushort/exception" ); - Console.WriteLine( formatter, "----------------", - "---------------", "----------------" ); + "decimal values.\n"); + Console.WriteLine(formatter, "decimal argument", + "short/exception", "ushort/exception"); + Console.WriteLine(formatter, "----------------", + "---------------", "----------------"); // Convert decimal values and display the results. - DecimalToU_Int16( 123M ); - DecimalToU_Int16( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int16( 123.999M ); - DecimalToU_Int16( 65535.999M ); - DecimalToU_Int16( 65536M ); - DecimalToU_Int16( 32767.999M ); - DecimalToU_Int16( 32768M ); - DecimalToU_Int16( - 0.999M ); - DecimalToU_Int16( - 1M ); - DecimalToU_Int16( - 32768.999M ); - DecimalToU_Int16( - 32769M ); + DecimalToU_Int16(123M); + DecimalToU_Int16(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int16(123.999M); + DecimalToU_Int16(65535.999M); + DecimalToU_Int16(65536M); + DecimalToU_Int16(32767.999M); + DecimalToU_Int16(32768M); + DecimalToU_Int16(-0.999M); + DecimalToU_Int16(-1M); + DecimalToU_Int16(-32768.999M); + DecimalToU_Int16(-32769M); } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctou_int32.cs b/snippets/csharp/System/Decimal/op_Explicit/ctou_int32.cs index eec7fb0531a..10b1c62f370 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctou_int32.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctou_int32.cs @@ -8,15 +8,15 @@ class DecimalToU_Int32Demo const string formatter = "{0,17}{1,19}{2,19}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int32( decimal argument ) + public static void DecimalToU_Int32(decimal argument) { object Int32Value; object UInt32Value; @@ -26,9 +26,9 @@ public static void DecimalToU_Int32( decimal argument ) { Int32Value = (int)argument; } - catch( Exception ex ) + catch (Exception ex) { - Int32Value = GetExceptionType( ex ); + Int32Value = GetExceptionType(ex); } // Convert the argument to a uint value. @@ -36,39 +36,39 @@ public static void DecimalToU_Int32( decimal argument ) { UInt32Value = (uint)argument; } - catch( Exception ex ) + catch (Exception ex) { - UInt32Value = GetExceptionType( ex ); + UInt32Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int32Value, UInt32Value ); + Console.WriteLine(formatter, argument, + Int32Value, UInt32Value); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the explicit conversions from decimal " + "to int \nand decimal to uint generates the following " + "output. It displays \nseveral converted decimal " + - "values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "int/exception", "uint/exception" ); - Console.WriteLine( formatter, "----------------", - "-------------", "--------------" ); + "values.\n"); + Console.WriteLine(formatter, "decimal argument", + "int/exception", "uint/exception"); + Console.WriteLine(formatter, "----------------", + "-------------", "--------------"); // Convert decimal values and display the results. - DecimalToU_Int32( 123M ); - DecimalToU_Int32( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int32( 123.999M ); - DecimalToU_Int32( 4294967295.999M ); - DecimalToU_Int32( 4294967296M ); - DecimalToU_Int32( 2147483647.999M ); - DecimalToU_Int32( 2147483648M ); - DecimalToU_Int32( - 0.999M ); - DecimalToU_Int32( - 1M ); - DecimalToU_Int32( - 2147483648.999M ); - DecimalToU_Int32( - 2147483649M ); + DecimalToU_Int32(123M); + DecimalToU_Int32(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int32(123.999M); + DecimalToU_Int32(4294967295.999M); + DecimalToU_Int32(4294967296M); + DecimalToU_Int32(2147483647.999M); + DecimalToU_Int32(2147483648M); + DecimalToU_Int32(-0.999M); + DecimalToU_Int32(-1M); + DecimalToU_Int32(-2147483648.999M); + DecimalToU_Int32(-2147483649M); } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/ctou_int64.cs b/snippets/csharp/System/Decimal/op_Explicit/ctou_int64.cs index d6dcd712fcd..70e27ccba0c 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/ctou_int64.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/ctou_int64.cs @@ -8,15 +8,15 @@ class DecimalToU_Int64Demo const string formatter = "{0,25}{1,22}{2,22}"; // Get the exception type name; remove the namespace prefix. - public static string GetExceptionType( Exception ex ) + public static string GetExceptionType(Exception ex) { - string exceptionType = ex.GetType( ).ToString( ); + string exceptionType = ex.GetType().ToString(); return exceptionType.Substring( - exceptionType.LastIndexOf( '.' ) + 1 ); + exceptionType.LastIndexOf('.') + 1); } // Convert the decimal argument; catch exceptions that are thrown. - public static void DecimalToU_Int64( decimal argument ) + public static void DecimalToU_Int64(decimal argument) { object Int64Value; object UInt64Value; @@ -26,9 +26,9 @@ public static void DecimalToU_Int64( decimal argument ) { Int64Value = (long)argument; } - catch( Exception ex ) + catch (Exception ex) { - Int64Value = GetExceptionType( ex ); + Int64Value = GetExceptionType(ex); } // Convert the argument to a ulong value. @@ -36,39 +36,39 @@ public static void DecimalToU_Int64( decimal argument ) { UInt64Value = (ulong)argument; } - catch( Exception ex ) + catch (Exception ex) { - UInt64Value = GetExceptionType( ex ); + UInt64Value = GetExceptionType(ex); } - Console.WriteLine( formatter, argument, - Int64Value, UInt64Value ); + Console.WriteLine(formatter, argument, + Int64Value, UInt64Value); } - public static void Main( ) + public static void Main() { Console.WriteLine( "This example of the explicit conversions from decimal " + "to long \nand decimal to ulong generates the following " + "output. It displays \nseveral converted decimal " + - "values.\n" ); - Console.WriteLine( formatter, "decimal argument", - "long/exception", "ulong/exception" ); - Console.WriteLine( formatter, "----------------", - "--------------", "---------------" ); + "values.\n"); + Console.WriteLine(formatter, "decimal argument", + "long/exception", "ulong/exception"); + Console.WriteLine(formatter, "----------------", + "--------------", "---------------"); // Convert decimal values and display the results. - DecimalToU_Int64( 123M ); - DecimalToU_Int64( new decimal( 123000, 0, 0, false, 3 ) ); - DecimalToU_Int64( 123.999M ); - DecimalToU_Int64( 18446744073709551615.999M ); - DecimalToU_Int64( 18446744073709551616M ); - DecimalToU_Int64( 9223372036854775807.999M ); - DecimalToU_Int64( 9223372036854775808M ); - DecimalToU_Int64( - 0.999M ); - DecimalToU_Int64( - 1M ); - DecimalToU_Int64( - 9223372036854775808.999M ); - DecimalToU_Int64( - 9223372036854775809M ); + DecimalToU_Int64(123M); + DecimalToU_Int64(new decimal(123000, 0, 0, false, 3)); + DecimalToU_Int64(123.999M); + DecimalToU_Int64(18446744073709551615.999M); + DecimalToU_Int64(18446744073709551616M); + DecimalToU_Int64(9223372036854775807.999M); + DecimalToU_Int64(9223372036854775808M); + DecimalToU_Int64(-0.999M); + DecimalToU_Int64(-1M); + DecimalToU_Int64(-9223372036854775808.999M); + DecimalToU_Int64(-9223372036854775809M); } } diff --git a/snippets/csharp/System/Decimal/op_Explicit/tosbyte.cs b/snippets/csharp/System/Decimal/op_Explicit/tosbyte.cs index 59a46087f50..3ab1f8de47b 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/tosbyte.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/tosbyte.cs @@ -6,21 +6,21 @@ class Example public static void Main() { // Define an array of decimal values. - decimal[] values = { 78m, new Decimal(78000, 0, 0, false, 3), + decimal[] values = { 78m, new decimal(78000, 0, 0, false, 3), 78.999m, 255.999m, 256m, 127.999m, 128m, -0.999m, -1m, -128.999m, -129m }; - foreach (var value in values) { - try { - SByte byteValue = (SByte) value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, byteValue, - byteValue.GetType().Name); - } - catch (OverflowException) { - Console.WriteLine("OverflowException: Cannot convert {0}", - value); - } - } + foreach (decimal value in values) + { + try + { + sbyte byteValue = (sbyte)value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {byteValue} ({byteValue.GetType().Name})"); + } + catch (OverflowException) + { + Console.WriteLine($"OverflowException: Cannot convert {value}"); + } + } } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/op_Explicit/tosingle1.cs b/snippets/csharp/System/Decimal/op_Explicit/tosingle1.cs index 4dacc2bea6d..17724fab372 100644 --- a/snippets/csharp/System/Decimal/op_Explicit/tosingle1.cs +++ b/snippets/csharp/System/Decimal/op_Explicit/tosingle1.cs @@ -3,7 +3,7 @@ class Example { - public static void Main( ) + public static void Main() { // Define an array of decimal values. decimal[] values = { 0.0000000000000000000000000001M, @@ -13,12 +13,11 @@ public static void Main( ) 123456789123456789123456789M, decimal.MinValue, decimal.MaxValue }; // Convert each value to a double. - foreach (var value in values) { - float dblValue = (float) value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, dblValue, - dblValue.GetType().Name); - } + foreach (decimal value in values) + { + float dblValue = (float)value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})"); + } } } // The example displays the following output: diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfrombyte.cs b/snippets/csharp/System/Decimal/op_Implicit/cfrombyte.cs index ab5b5775d9b..d41526fa115 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfrombyte.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfrombyte.cs @@ -9,11 +9,10 @@ public static void Main() byte[] values = { byte.MinValue, byte.MaxValue, 0x3F, 123, 200 }; // Convert each value to a Decimal. - foreach (var value in values) { - decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (byte value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromint16.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromint16.cs index b9717eef29b..386213a3216 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromint16.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromint16.cs @@ -9,11 +9,10 @@ public static void Main() short[] values = { short.MinValue, short.MaxValue, 0xFFF, 12345, -10000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (short value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromint32.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromint32.cs index 0fb47727593..c3d1521e0c8 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromint32.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromint32.cs @@ -9,11 +9,10 @@ public static void Main() int[] values = { int.MinValue, int.MaxValue, 0xFFFFFF, 123456789, -1000000000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (int value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromint64.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromint64.cs index 2b2866797e2..e01291d9a43 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromint64.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromint64.cs @@ -10,11 +10,10 @@ public static void Main() 0xFFFFFFFFFFFF, 123456789123456789, -1000000000000000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (long value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromsbyte.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromsbyte.cs index 2cff427ad64..0566b9eee98 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromsbyte.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromsbyte.cs @@ -9,11 +9,10 @@ public static void Main() sbyte[] values = { sbyte.MinValue, sbyte.MaxValue, 0x3F, 123, -100 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (sbyte value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromuint16.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromuint16.cs index 7a4315a2884..d8911211351 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromuint16.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromuint16.cs @@ -9,11 +9,10 @@ public static void Main() ushort[] values = { ushort.MinValue, ushort.MaxValue, 0xFFF, 12345, 40000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (ushort value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromuint32.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromuint32.cs index b0b136d48c5..3d70ab47dc8 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromuint32.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromuint32.cs @@ -9,11 +9,10 @@ public static void Main() uint[] values = { uint.MinValue, uint.MaxValue, 0xFFFFFF, 123456789, 4000000000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (uint value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Decimal/op_Implicit/cfromuint64.cs b/snippets/csharp/System/Decimal/op_Implicit/cfromuint64.cs index 0e2ec14b2df..c2575368d82 100644 --- a/snippets/csharp/System/Decimal/op_Implicit/cfromuint64.cs +++ b/snippets/csharp/System/Decimal/op_Implicit/cfromuint64.cs @@ -10,11 +10,10 @@ public static void Main() 0xFFFFFFFFFFFF, 123456789123456789, 1000000000000000 }; // Convert each value to a Decimal. - foreach (var value in values) { - Decimal decValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", value, - value.GetType().Name, decValue, - decValue.GetType().Name); + foreach (ulong value in values) + { + decimal decValue = value; + Console.WriteLine($"{value} ({value.GetType().Name}) --> {decValue} ({decValue.GetType().Name})"); } } } diff --git a/snippets/csharp/System/Delegate/CreateDelegate/openClosedOver.cs b/snippets/csharp/System/Delegate/CreateDelegate/openClosedOver.cs index 7d5d15d287f..24448beb052 100644 --- a/snippets/csharp/System/Delegate/CreateDelegate/openClosedOver.cs +++ b/snippets/csharp/System/Delegate/CreateDelegate/openClosedOver.cs @@ -1,4 +1,4 @@ -// All four permutations of instance/static with open/closed. +// All four permutations of instance/static with open/closed. // // using System; @@ -17,22 +17,19 @@ public class C { private int id; - public C(int id) { this.id = id; } + public C(int id) => this.id = id; public void M1(string s) => Console.WriteLine($"Instance method M1 on C: id = {this.id}, s = {s}"); - public static void M2(string s) - { - Console.WriteLine($"Static method M2 on C: s = {s}"); - } + public static void M2(string s) => Console.WriteLine($"Static method M2 on C: s = {s}"); } public class Example2 { public static void Main() { - C c1 = new C(42); + C c1 = new(42); // Get a MethodInfo for each method. // diff --git a/snippets/csharp/System/Delegate/CreateDelegate/source.cs b/snippets/csharp/System/Delegate/CreateDelegate/source.cs index cd0a1acbb4e..c6c8647118e 100644 --- a/snippets/csharp/System/Delegate/CreateDelegate/source.cs +++ b/snippets/csharp/System/Delegate/CreateDelegate/source.cs @@ -1,4 +1,4 @@ -// Showing all the things D(A) can bind to. +// Showing all the things D(A) can bind to. // // using System; @@ -18,54 +18,31 @@ public class C1 public int ID => id; public C1(int id) => this.id = id; - public void M1(C1 c) - { - Console.WriteLine("Instance method M1(C1 c) on C1: this.id = {0}, c.ID = {1}", - this.id, c.ID); - } + public void M1(C1 c) => Console.WriteLine($"Instance method M1(C1 c) on C1: this.id = {this.id}, c.ID = {c.ID}"); - public void M2() - { - Console.WriteLine($"Instance method M2() on C1: this.id = {this.id}"); - } + public void M2() => Console.WriteLine($"Instance method M2() on C1: this.id = {this.id}"); - public static void M3(C1 c) - { - Console.WriteLine($"Static method M3(C1 c) on C1: c.ID = {c.ID}"); - } + public static void M3(C1 c) => Console.WriteLine($"Static method M3(C1 c) on C1: c.ID = {c.ID}"); - public static void M4(C1 c1, C1 c2) - { - Console.WriteLine("Static method M4(C1 c1, C1 c2) on C1: c1.ID = {0}, c2.ID = {1}", - c1.ID, c2.ID); - } + public static void M4(C1 c1, C1 c2) => Console.WriteLine($"Static method M4(C1 c1, C1 c2) on C1: c1.ID = {c1.ID}, c2.ID = {c2.ID}"); } public class F { - public void M1(C1 c) - { - Console.WriteLine($"Instance method M1(C1 c) on F: c.ID = {c.ID}"); - } + public void M1(C1 c) => Console.WriteLine($"Instance method M1(C1 c) on F: c.ID = {c.ID}"); - public static void M3(C1 c) - { - Console.WriteLine($"Static method M3(C1 c) on F: c.ID = {c.ID}"); - } + public static void M3(C1 c) => Console.WriteLine($"Static method M3(C1 c) on F: c.ID = {c.ID}"); - public static void M4(F f, C1 c) - { - Console.WriteLine($"Static method M4(F f, C1 c) on F: c.ID = {c.ID}"); - } + public static void M4(F f, C1 c) => Console.WriteLine($"Static method M4(F f, C1 c) on F: c.ID = {c.ID}"); } public class Example { public static void Main() { - C1 c1 = new (42); - C1 c2 = new (1491); - F f1 = new (); + C1 c1 = new(42); + C1 c2 = new(1491); + F f1 = new(); D d; diff --git a/snippets/csharp/System/Delegate/GetInvocationList/GetInvocationList1.cs b/snippets/csharp/System/Delegate/GetInvocationList/GetInvocationList1.cs index 27f139f24bc..0ca7f37e4c7 100644 --- a/snippets/csharp/System/Delegate/GetInvocationList/GetInvocationList1.cs +++ b/snippets/csharp/System/Delegate/GetInvocationList/GetInvocationList1.cs @@ -6,52 +6,50 @@ public class Example { - public static void Main() - { - Action outputMessage = null; - outputMessage += Console.WriteLine; - outputMessage += OutputToFile; - outputMessage += ShowMessageBox; + public static void Main() + { + Action outputMessage = null; + outputMessage += Console.WriteLine; + outputMessage += OutputToFile; + outputMessage += ShowMessageBox; -// Dim output1 As Action(Of String) = AddressOf Console.WriteLine -// Dim output2 As Action(Of String) = AddressOf OutputToFile -// Dim output3 As Action(Of String) = AddressOf MessageBox.Show -// -// outputMessage = [Delegate].Combine( { output1, output2, output3 } ) - Console.WriteLine("Invocation list has {0} methods.", - outputMessage.GetInvocationList().Length); + // Dim output1 As Action(Of String) = AddressOf Console.WriteLine + // Dim output2 As Action(Of String) = AddressOf OutputToFile + // Dim output3 As Action(Of String) = AddressOf MessageBox.Show + // + // outputMessage = [Delegate].Combine( { output1, output2, output3 } ) + Console.WriteLine($"Invocation list has {outputMessage.GetInvocationList().Length} methods."); - // Invoke delegates normally. - outputMessage("Hello there!"); - Console.WriteLine("Press to continue..."); - Console.ReadLine(); + // Invoke delegates normally. + outputMessage("Hello there!"); + Console.WriteLine("Press to continue..."); + Console.ReadLine(); - // Invoke each delegate in the invocation list in reverse order. - for (int ctr = outputMessage.GetInvocationList().Length - 1; ctr >= 0; ctr--) { - var outputMsg = outputMessage.GetInvocationList()[ctr]; - outputMsg.DynamicInvoke("Greetings and salutations!"); - } - Console.WriteLine("Press to continue..."); - Console.ReadLine(); + // Invoke each delegate in the invocation list in reverse order. + for (int ctr = outputMessage.GetInvocationList().Length - 1; ctr >= 0; ctr--) + { + var outputMsg = outputMessage.GetInvocationList()[ctr]; + outputMsg.DynamicInvoke("Greetings and salutations!"); + } + Console.WriteLine("Press to continue..."); + Console.ReadLine(); - // Invoke each delegate that doesn't write to a file. - for (int ctr = 0; ctr < outputMessage.GetInvocationList().Length; ctr++) { - var outputMsg = outputMessage.GetInvocationList()[ctr]; - if (!outputMsg.GetMethodInfo().Name.Contains("File")) - outputMsg.DynamicInvoke( new String[] { "Hi!" } ); - } - } + // Invoke each delegate that doesn't write to a file. + for (int ctr = 0; ctr < outputMessage.GetInvocationList().Length; ctr++) + { + var outputMsg = outputMessage.GetInvocationList()[ctr]; + if (!outputMsg.GetMethodInfo().Name.Contains("File")) + outputMsg.DynamicInvoke(new string[] { "Hi!" }); + } + } - private static void OutputToFile(String s) - { - var sw = new StreamWriter(@".\output.txt"); - sw.WriteLine(s); - sw.Close(); - } + private static void OutputToFile(string s) + { + var sw = new StreamWriter(@".\output.txt"); + sw.WriteLine(s); + sw.Close(); + } - private static void ShowMessageBox(String s) - { - MessageBox.Show(s); - } + private static void ShowMessageBox(string s) => MessageBox.Show(s); } // diff --git a/snippets/csharp/System/DivideByZeroException/Overview/exception1.cs b/snippets/csharp/System/DivideByZeroException/Overview/exception1.cs index 31531ce5a29..c00f353ef8b 100644 --- a/snippets/csharp/System/DivideByZeroException/Overview/exception1.cs +++ b/snippets/csharp/System/DivideByZeroException/Overview/exception1.cs @@ -3,18 +3,20 @@ public class Example { - public static void Main() - { - int number1 = 3000; - int number2 = 0; - try { - Console.WriteLine(number1 / number2); - } - catch (DivideByZeroException) { - Console.WriteLine("Division of {0} by zero.", number1); - } - } + public static void Main() + { + int number1 = 3000; + int number2 = 0; + try + { + Console.WriteLine(number1 / number2); + } + catch (DivideByZeroException) + { + Console.WriteLine($"Division of {number1} by zero."); + } + } } // The example displays the following output: // Division of 3000 by zero. -// \ No newline at end of file +// diff --git a/snippets/csharp/System/DivideByZeroException/Overview/exception2.cs b/snippets/csharp/System/DivideByZeroException/Overview/exception2.cs index a5521ffeaba..f5e4efec35e 100644 --- a/snippets/csharp/System/DivideByZeroException/Overview/exception2.cs +++ b/snippets/csharp/System/DivideByZeroException/Overview/exception2.cs @@ -3,14 +3,14 @@ public class Example { - public static void Main() - { - int number1 = 3000; - int number2 = 0; + public static void Main() + { + int number1 = 3000; + int number2 = 0; - Console.WriteLine((double)number1 / number2); - } + Console.WriteLine((double)number1 / number2); + } } // The example displays the following output: // Infinity -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Double/CompareTo/doublesample.cs b/snippets/csharp/System/Double/CompareTo/doublesample.cs index ef7b2e5b42e..9307884f713 100644 --- a/snippets/csharp/System/Double/CompareTo/doublesample.cs +++ b/snippets/csharp/System/Double/CompareTo/doublesample.cs @@ -1,128 +1,134 @@ using System; -class DoubleSample { - public static void Main() - { - // - Double d = 4.55; - // - - // - Console.WriteLine("A double is of type {0}.", d.GetType().ToString()); - // - - // - bool done = false; - string inp; - do { - Console.Write("Enter a real number: "); - inp = Console.ReadLine(); - try { - d = Double.Parse(inp); - Console.WriteLine("You entered {0}.", d.ToString()); - done = true; - } - catch (FormatException) { - Console.WriteLine("You did not enter a number."); - } - catch (ArgumentNullException) { - Console.WriteLine("You did not supply any input."); - } - catch (OverflowException) { - Console.WriteLine("The value you entered, {0}, is out of range.", inp); - } - } while (!done); - // - - // - if (d > Double.MaxValue) - Console.WriteLine("Your number is bigger than a double."); - // - - // - if (d < Double.MinValue) - Console.WriteLine("Your number is smaller than a double."); - // - - // - Console.WriteLine("Epsilon, or the permittivity of a vacuum, has value {0}", Double.Epsilon.ToString()); - // - - // - Double zero = 0; - - // This condition will return false. - if ((0 / zero) == Double.NaN) - Console.WriteLine("0 / 0 can be tested with Double.NaN."); - else - Console.WriteLine("0 / 0 cannot be tested with Double.NaN; use Double.IsNan() instead."); - // - - // - // This will return true. - if (Double.IsNaN(0 / zero)) - Console.WriteLine("Double.IsNan() can determine whether a value is not-a-number."); - // - - // - // This will equal Infinity. - Console.WriteLine("10.0 minus NegativeInfinity equals {0}.", (10.0 - Double.NegativeInfinity).ToString()); - // - - // - // This will equal Infinity. - Console.WriteLine("PositiveInfinity plus 10.0 equals {0}.", (Double.PositiveInfinity + 10.0).ToString()); - // - - // - // This will return "true". - Console.WriteLine("IsInfinity(3.0 / 0) == {0}.", Double.IsInfinity(3.0 / 0) ? "true" : "false"); - // - - // - // This will return "true". - Console.WriteLine("IsPositiveInfinity(4.0 / 0) == {0}.", Double.IsPositiveInfinity(4.0 / 0) ? "true" : "false"); - // - - // - // This will return "true". - Console.WriteLine("IsNegativeInfinity(-5.0 / 0) == {0}.", Double.IsNegativeInfinity(-5.0 / 0) ? "true" : "false"); - // - - // - Double a = 500; - Object obj1; - // - - // - // The variables point to the same objects. - Object obj2; - obj1 = a; - obj2 = obj1; - - if (Double.ReferenceEquals(obj1, obj2)) - Console.WriteLine("The variables point to the same double object."); - else - Console.WriteLine("The variables point to different double objects."); - // - - // - obj1 = (Double)450; - - if (a.CompareTo(obj1) < 0) - Console.WriteLine("{0} is less than {1}.", a.ToString(), obj1.ToString()); - - if (a.CompareTo(obj1) > 0) - Console.WriteLine("{0} is greater than {1}.", a.ToString(), obj1.ToString()); - - if (a.CompareTo(obj1) == 0) - Console.WriteLine("{0} equals {1}.", a.ToString(), obj1.ToString()); - // - - // - obj1 = (Double)500; - if (a.Equals(obj1)) - Console.WriteLine("The value type and reference type values are equal."); - // - } +class DoubleSample +{ + public static void Main() + { + // + double d = 4.55; + // + + // + Console.WriteLine($"A double is of type {d.GetType().ToString()}."); + // + + // + bool done = false; + string inp; + do + { + Console.Write("Enter a real number: "); + inp = Console.ReadLine(); + try + { + d = double.Parse(inp); + Console.WriteLine($"You entered {d.ToString()}."); + done = true; + } + catch (FormatException) + { + Console.WriteLine("You did not enter a number."); + } + catch (ArgumentNullException) + { + Console.WriteLine("You did not supply any input."); + } + catch (OverflowException) + { + Console.WriteLine($"The value you entered, {inp}, is out of range."); + } + } while (!done); + // + + // + if (d > double.MaxValue) + Console.WriteLine("Your number is bigger than a double."); + // + + // + if (d < double.MinValue) + Console.WriteLine("Your number is smaller than a double."); + // + + // + Console.WriteLine($"Epsilon, or the permittivity of a vacuum, has value {double.Epsilon.ToString()}"); + // + + // + double zero = 0; + + // This condition will return false. + if ((0 / zero) == double.NaN) + Console.WriteLine("0 / 0 can be tested with Double.NaN."); + else + Console.WriteLine("0 / 0 cannot be tested with Double.NaN; use Double.IsNan() instead."); + // + + // + // This will return true. + if (double.IsNaN(0 / zero)) + Console.WriteLine("Double.IsNan() can determine whether a value is not-a-number."); + // + + // + // This will equal Infinity. + Console.WriteLine($"10.0 minus NegativeInfinity equals {(10.0 - double.NegativeInfinity).ToString()}."); + // + + // + // This will equal Infinity. + Console.WriteLine($"PositiveInfinity plus 10.0 equals {(double.PositiveInfinity + 10.0).ToString()}."); + // + + // + // This will return "true". + Console.WriteLine($"IsInfinity(3.0 / 0) == {(double.IsInfinity(3.0 / 0) ? "true" : "false")}."); + // + + // + // This will return "true". + Console.WriteLine($"IsPositiveInfinity(4.0 / 0) == {(double.IsPositiveInfinity(4.0 / 0) ? "true" : "false")}."); + // + + // + // This will return "true". + Console.WriteLine($"IsNegativeInfinity(-5.0 / 0) == {(double.IsNegativeInfinity(-5.0 / 0) ? "true" : "false")}."); + // + + // + double a = 500; + object obj1; + // + + // + // The variables point to the same objects. + object obj2; + obj1 = a; + obj2 = obj1; + + if (double.ReferenceEquals(obj1, obj2)) + Console.WriteLine("The variables point to the same double object."); + else + Console.WriteLine("The variables point to different double objects."); + // + + // + obj1 = (double)450; + + if (a.CompareTo(obj1) < 0) + Console.WriteLine($"{a.ToString()} is less than {obj1.ToString()}."); + + if (a.CompareTo(obj1) > 0) + Console.WriteLine($"{a.ToString()} is greater than {obj1.ToString()}."); + + if (a.CompareTo(obj1) == 0) + Console.WriteLine($"{a.ToString()} equals {obj1.ToString()}."); + // + + // + obj1 = (double)500; + if (a.Equals(obj1)) + Console.WriteLine("The value type and reference type values are equal."); + // + } } diff --git a/snippets/csharp/System/Double/Epsilon/Equals_25051.cs b/snippets/csharp/System/Double/Epsilon/Equals_25051.cs index a1f4800204d..925e2613127 100644 --- a/snippets/csharp/System/Double/Epsilon/Equals_25051.cs +++ b/snippets/csharp/System/Double/Epsilon/Equals_25051.cs @@ -2,73 +2,73 @@ public class Class1 { - public static void Main() - { - CompareUsingEquals(); - Console.WriteLine(); - CompareApproximateValues(); - Console.WriteLine(); - CompareObjectsUsingEquals(); - Console.WriteLine(); - CompareApproximateObjectValues(); - } + public static void Main() + { + CompareUsingEquals(); + Console.WriteLine(); + CompareApproximateValues(); + Console.WriteLine(); + CompareObjectsUsingEquals(); + Console.WriteLine(); + CompareApproximateObjectValues(); + } - private static void CompareUsingEquals() - { - // - // Initialize two doubles with apparently identical values - double double1 = .33333; - double double2 = (double) 1/3; - // Compare them for equality - Console.WriteLine(double1.Equals(double2)); // displays false - // - } + private static void CompareUsingEquals() + { + // + // Initialize two doubles with apparently identical values + double double1 = .33333; + double double2 = (double)1 / 3; + // Compare them for equality + Console.WriteLine(double1.Equals(double2)); // displays false + // + } - private static void CompareApproximateValues() - { - Console.WriteLine("Snippet2"); - // - // Initialize two doubles with apparently identical values - double double1 = .333333; - double double2 = (double) 1/3; - // Define the tolerance for variation in their values - double difference = Math.Abs(double1 * .00001); + private static void CompareApproximateValues() + { + Console.WriteLine("Snippet2"); + // + // Initialize two doubles with apparently identical values + double double1 = .333333; + double double2 = (double)1 / 3; + // Define the tolerance for variation in their values + double difference = Math.Abs(double1 * .00001); - // Compare the values - // The output to the console indicates that the two values are equal - if (Math.Abs(double1 - double2) <= difference) - Console.WriteLine("double1 and double2 are equal."); - else - Console.WriteLine("double1 and double2 are unequal."); - // - } + // Compare the values + // The output to the console indicates that the two values are equal + if (Math.Abs(double1 - double2) <= difference) + Console.WriteLine("double1 and double2 are equal."); + else + Console.WriteLine("double1 and double2 are unequal."); + // + } - private static void CompareObjectsUsingEquals() - { - // - // Initialize two doubles with apparently identical values - double double1 = .33333; - object double2 = (double) 1/3; - // Compare them for equality - Console.WriteLine(double1.Equals(double2)); // displays false - // - } + private static void CompareObjectsUsingEquals() + { + // + // Initialize two doubles with apparently identical values + double double1 = .33333; + object double2 = (double)1 / 3; + // Compare them for equality + Console.WriteLine(double1.Equals(double2)); // displays false + // + } - private static void CompareApproximateObjectValues() - { - // - // Initialize two doubles with apparently identical values - double double1 = .33333; - object double2 = (double) 1/3; - // Define the tolerance for variation in their values - double difference = Math.Abs(double1 * .0001); + private static void CompareApproximateObjectValues() + { + // + // Initialize two doubles with apparently identical values + double double1 = .33333; + object double2 = (double)1 / 3; + // Define the tolerance for variation in their values + double difference = Math.Abs(double1 * .0001); - // Compare the values - // The output to the console indicates that the two values are equal - if (Math.Abs(double1 - (double) double2) <= difference) - Console.WriteLine("double1 and double2 are equal."); - else - Console.WriteLine("double1 and double2 are unequal."); - // - } + // Compare the values + // The output to the console indicates that the two values are equal + if (Math.Abs(double1 - (double)double2) <= difference) + Console.WriteLine("double1 and double2 are equal."); + else + Console.WriteLine("double1 and double2 are unequal."); + // + } } diff --git a/snippets/csharp/System/Double/Epsilon/epsilon.cs b/snippets/csharp/System/Double/Epsilon/epsilon.cs index 4cc778bc854..648bcb1c572 100644 --- a/snippets/csharp/System/Double/Epsilon/epsilon.cs +++ b/snippets/csharp/System/Double/Epsilon/epsilon.cs @@ -1,21 +1,21 @@ -// +// using System; public class Example { - public static void Main() - { - double[] values = { 0, Double.Epsilon, Double.Epsilon * .5 }; + public static void Main() + { + double[] values = { 0, double.Epsilon, double.Epsilon * .5 }; - for (int ctr = 0; ctr <= values.Length - 2; ctr++) - { - for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) - { - Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); - } - Console.WriteLine(); - } - } + for (int ctr = 0; ctr <= values.Length - 2; ctr++) + { + for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) + { + Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); + } + Console.WriteLine(); + } + } } // The example displays the following output: // 0 = 4.94065645841247E-324: False diff --git a/snippets/csharp/System/Double/Epsilon/epsilon1.cs b/snippets/csharp/System/Double/Epsilon/epsilon1.cs index 20687107010..84895de02ea 100644 --- a/snippets/csharp/System/Double/Epsilon/epsilon1.cs +++ b/snippets/csharp/System/Double/Epsilon/epsilon1.cs @@ -5,8 +5,8 @@ public class Example1 { public static void Main() { - double[] values = { 0.0, Double.Epsilon }; - foreach (var value in values) + double[] values = { 0.0, double.Epsilon }; + foreach (double value in values) { Console.WriteLine(GetComponentParts(value)); Console.WriteLine(); @@ -15,20 +15,19 @@ public static void Main() private static string GetComponentParts(double value) { - string result = String.Format("{0:R}: ", value); + string result = $"{value:R}: "; int indent = result.Length; // Convert the double to an 8-byte array. byte[] bytes = BitConverter.GetBytes(value); // Get the sign bit (byte 7, bit 7). - result += String.Format("Sign: {0}\n", - (bytes[7] & 0x80) == 0x80 ? "1 (-)" : "0 (+)"); + result += $"Sign: {((bytes[7] & 0x80) == 0x80 ? "1 (-)" : "0 (+)")}\n"; // Get the exponent (byte 6 bits 4-7 to byte 7, bits 0-6) int exponent = (bytes[7] & 0x07F) << 4; exponent = exponent | ((bytes[6] & 0xF0) >> 4); int adjustment = exponent != 0 ? 1023 : 1022; - result += String.Format("{0}Exponent: 0x{1:X4} ({1})\n", new String(' ', indent), exponent - adjustment); + result += string.Format("{0}Exponent: 0x{1:X4} ({1})\n", new string(' ', indent), exponent - adjustment); // Get the significand (bits 0-51) long significand = ((bytes[6] & 0x0F) << 48); @@ -38,7 +37,7 @@ private static string GetComponentParts(double value) significand = significand | ((long)bytes[2] << 16); significand = significand | ((long)bytes[1] << 8); significand = significand | bytes[0]; - result += String.Format("{0}Mantissa: 0x{1:X13}\n", new String(' ', indent), significand); + result += $"{new string(' ', indent)}Mantissa: 0x{significand:X13}\n"; return result; } diff --git a/snippets/csharp/System/Double/Equals/equalsoverl.cs b/snippets/csharp/System/Double/Equals/equalsoverl.cs index 8a3fad02ecd..f71f1e426e5 100644 --- a/snippets/csharp/System/Double/Equals/equalsoverl.cs +++ b/snippets/csharp/System/Double/Equals/equalsoverl.cs @@ -3,58 +3,52 @@ public class OverExample { - static double value = 112; + static double value = 112; - public static void Main() - { - byte byte1= 112; - Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1)); - TestObjectForEquality(byte1); + public static void Main() + { + byte byte1 = 112; + Console.WriteLine($"value = byte1: {value.Equals(byte1),16}"); + TestObjectForEquality(byte1); - short short1 = 112; - Console.WriteLine("value = short1: {0,16}", value.Equals(short1)); - TestObjectForEquality(short1); + short short1 = 112; + Console.WriteLine($"value = short1: {value.Equals(short1),16}"); + TestObjectForEquality(short1); - int int1 = 112; - Console.WriteLine("value = int1: {0,18}", value.Equals(int1)); - TestObjectForEquality(int1); + int int1 = 112; + Console.WriteLine($"value = int1: {value.Equals(int1),18}"); + TestObjectForEquality(int1); - long long1 = 112; - Console.WriteLine("value = long1: {0,17}", value.Equals(long1)); - TestObjectForEquality(long1); + long long1 = 112; + Console.WriteLine($"value = long1: {value.Equals(long1),17}"); + TestObjectForEquality(long1); - sbyte sbyte1 = 112; - Console.WriteLine("value = sbyte1: {0,16}", value.Equals(sbyte1)); - TestObjectForEquality(sbyte1); + sbyte sbyte1 = 112; + Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),16}"); + TestObjectForEquality(sbyte1); - ushort ushort1 = 112; - Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1)); - TestObjectForEquality(ushort1); + ushort ushort1 = 112; + Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}"); + TestObjectForEquality(ushort1); - uint uint1 = 112; - Console.WriteLine("value = uint1: {0,18}", value.Equals(uint1)); - TestObjectForEquality(uint1); + uint uint1 = 112; + Console.WriteLine($"value = uint1: {value.Equals(uint1),18}"); + TestObjectForEquality(uint1); - ulong ulong1 = 112; - Console.WriteLine("value = ulong1: {0,17}", value.Equals(ulong1)); - TestObjectForEquality(ulong1); + ulong ulong1 = 112; + Console.WriteLine($"value = ulong1: {value.Equals(ulong1),17}"); + TestObjectForEquality(ulong1); - decimal dec1 = 112m; - Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1)); - TestObjectForEquality(dec1); + decimal dec1 = 112m; + Console.WriteLine($"value = dec1: {value.Equals(dec1),21}"); + TestObjectForEquality(dec1); - float sng1 = 112; - Console.WriteLine("value = sng1: {0,19}", value.Equals(sng1)); - TestObjectForEquality(sng1); - } + float sng1 = 112; + Console.WriteLine($"value = sng1: {value.Equals(sng1),19}"); + TestObjectForEquality(sng1); + } - private static void TestObjectForEquality(Object obj) - { - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n", - value, value.GetType().Name, - obj, obj.GetType().Name, - value.Equals(obj)); - } + private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n"); } // The example displays the following output: // value = byte1: True diff --git a/snippets/csharp/System/Double/MaxValue/maxvalueex.cs b/snippets/csharp/System/Double/MaxValue/maxvalueex.cs index 17c43def32f..b81b100ccac 100644 --- a/snippets/csharp/System/Double/MaxValue/maxvalueex.cs +++ b/snippets/csharp/System/Double/MaxValue/maxvalueex.cs @@ -3,20 +3,17 @@ public class Example { - public static void Main() - { - double result1 = 7.997e307 + 9.985e307; - Console.WriteLine("{0} (Positive Infinity: {1})", - result1, Double.IsPositiveInfinity(result1)); + public static void Main() + { + double result1 = 7.997e307 + 9.985e307; + Console.WriteLine($"{result1} (Positive Infinity: {double.IsPositiveInfinity(result1)})"); - double result2 = 1.5935e250 * 7.948e110; - Console.WriteLine("{0} (Positive Infinity: {1})", - result2, Double.IsPositiveInfinity(result2)); + double result2 = 1.5935e250 * 7.948e110; + Console.WriteLine($"{result2} (Positive Infinity: {double.IsPositiveInfinity(result2)})"); - double result3 = Math.Pow(1.256e100, 1.34e20); - Console.WriteLine("{0} (Positive Infinity: {1})", - result3, Double.IsPositiveInfinity(result3)); - } + double result3 = Math.Pow(1.256e100, 1.34e20); + Console.WriteLine($"{result3} (Positive Infinity: {double.IsPositiveInfinity(result3)})"); + } } // The example displays the following output: // Infinity (Positive Infinity: True) diff --git a/snippets/csharp/System/Double/MinValue/minvalueex.cs b/snippets/csharp/System/Double/MinValue/minvalueex.cs index 43a61692a2c..cbd18de3971 100644 --- a/snippets/csharp/System/Double/MinValue/minvalueex.cs +++ b/snippets/csharp/System/Double/MinValue/minvalueex.cs @@ -3,16 +3,14 @@ public class Example { - public static void Main() - { - double result1 = -7.997e307 + -9.985e307; - Console.WriteLine("{0} (Negative Infinity: {1})", - result1, Double.IsNegativeInfinity(result1)); + public static void Main() + { + double result1 = -7.997e307 + -9.985e307; + Console.WriteLine($"{result1} (Negative Infinity: {double.IsNegativeInfinity(result1)})"); - double result2 = -1.5935e250 * 7.948e110; - Console.WriteLine("{0} (Negative Infinity: {1})", - result2, Double.IsNegativeInfinity(result2)); - } + double result2 = -1.5935e250 * 7.948e110; + Console.WriteLine($"{result2} (Negative Infinity: {double.IsNegativeInfinity(result2)})"); + } } // The example displays the following output: // -Infinity (Negative Infinity: True) diff --git a/snippets/csharp/System/Double/NaN/double.nan4.cs b/snippets/csharp/System/Double/NaN/double.nan4.cs index 8d5a2af66dc..5162c8cbae2 100644 --- a/snippets/csharp/System/Double/NaN/double.nan4.cs +++ b/snippets/csharp/System/Double/NaN/double.nan4.cs @@ -3,24 +3,24 @@ public class Example { - public static void Main() - { - Console.WriteLine("NaN == NaN: {0}", Double.NaN == Double.NaN); - Console.WriteLine("NaN != NaN: {0}", Double.NaN != Double.NaN); - Console.WriteLine("NaN.Equals(NaN): {0}", Double.NaN.Equals(Double.NaN)); - Console.WriteLine("! NaN.Equals(NaN): {0}", ! Double.NaN.Equals(Double.NaN)); - Console.WriteLine("IsNaN: {0}", Double.IsNaN(Double.NaN)); + public static void Main() + { + Console.WriteLine($"NaN == NaN: {double.NaN == double.NaN}"); + Console.WriteLine($"NaN != NaN: {double.NaN != double.NaN}"); + Console.WriteLine($"NaN.Equals(NaN): {double.NaN.Equals(double.NaN)}"); + Console.WriteLine($"! NaN.Equals(NaN): {!double.NaN.Equals(double.NaN)}"); + Console.WriteLine($"IsNaN: {double.IsNaN(double.NaN)}"); - Console.WriteLine("\nNaN > NaN: {0}", Double.NaN > Double.NaN); - Console.WriteLine("NaN >= NaN: {0}", Double.NaN >= Double.NaN); - Console.WriteLine("NaN < NaN: {0}", Double.NaN < Double.NaN); - Console.WriteLine("NaN < 100.0: {0}", Double.NaN < 100.0); - Console.WriteLine("NaN <= 100.0: {0}", Double.NaN <= 100.0); - Console.WriteLine("NaN >= 100.0: {0}", Double.NaN > 100.0); - Console.WriteLine("NaN.CompareTo(NaN): {0}", Double.NaN.CompareTo(Double.NaN)); - Console.WriteLine("NaN.CompareTo(100.0): {0}", Double.NaN.CompareTo(100.0)); - Console.WriteLine("(100.0).CompareTo(Double.NaN): {0}", (100.0).CompareTo(Double.NaN)); - } + Console.WriteLine($"\nNaN > NaN: {double.NaN > double.NaN}"); + Console.WriteLine($"NaN >= NaN: {double.NaN >= double.NaN}"); + Console.WriteLine($"NaN < NaN: {double.NaN < double.NaN}"); + Console.WriteLine($"NaN < 100.0: {double.NaN < 100.0}"); + Console.WriteLine($"NaN <= 100.0: {double.NaN <= 100.0}"); + Console.WriteLine($"NaN >= 100.0: {double.NaN > 100.0}"); + Console.WriteLine($"NaN.CompareTo(NaN): {double.NaN.CompareTo(double.NaN)}"); + Console.WriteLine($"NaN.CompareTo(100.0): {double.NaN.CompareTo(100.0)}"); + Console.WriteLine($"(100.0).CompareTo(Double.NaN): {(100.0).CompareTo(double.NaN)}"); + } } // The example displays the following output: // NaN == NaN: False @@ -38,4 +38,4 @@ public static void Main() // NaN.CompareTo(NaN): 0 // NaN.CompareTo(100.0): -1 // (100.0).CompareTo(Double.NaN): 1 -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Double/NaN/nan1.cs b/snippets/csharp/System/Double/NaN/nan1.cs index dd6162ed375..2682199fef1 100644 --- a/snippets/csharp/System/Double/NaN/nan1.cs +++ b/snippets/csharp/System/Double/NaN/nan1.cs @@ -2,32 +2,31 @@ public class Example { - public static void Main() - { - // - double zero = 0.0; - Console.WriteLine("{0} / {1} = {2}", zero, zero, zero/zero); - // The example displays the following output: - // 0 / 0 = NaN - // + public static void Main() + { + // + double zero = 0.0; + Console.WriteLine($"{zero} / {zero} = {zero / zero}"); + // The example displays the following output: + // 0 / 0 = NaN + // - // - double nan1 = Double.NaN; + // + double nan1 = double.NaN; - Console.WriteLine("{0} + {1} = {2}", 3, nan1, 3 + nan1); - Console.WriteLine("Abs({0}) = {1}", nan1, Math.Abs(nan1)); - // The example displays the following output: - // 3 + NaN = NaN - // Abs(NaN) = NaN - // - Console.WriteLine(); + Console.WriteLine($"{3} + {nan1} = {3 + nan1}"); + Console.WriteLine($"Abs({nan1}) = {Math.Abs(nan1)}"); + // The example displays the following output: + // 3 + NaN = NaN + // Abs(NaN) = NaN + // + Console.WriteLine(); - // - double result = Double.NaN; - Console.WriteLine("{0} = Double.Nan: {1}", - result, result == Double.NaN); - // The example displays the following output: - // NaN = Double.Nan: False - // - } + // + double result = double.NaN; + Console.WriteLine($"{result} = Double.Nan: {result == double.NaN}"); + // The example displays the following output: + // NaN = Double.Nan: False + // + } } diff --git a/snippets/csharp/System/Double/Overview/comparison1.cs b/snippets/csharp/System/Double/Overview/comparison1.cs index 39c0d36f900..808292c8164 100644 --- a/snippets/csharp/System/Double/Overview/comparison1.cs +++ b/snippets/csharp/System/Double/Overview/comparison1.cs @@ -1,14 +1,14 @@ -// +// using System; public class Example { - public static void Main() - { - double value1 = .333333333333333; - double value2 = 1.0/3; - Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}"); - } + public static void Main() + { + double value1 = .333333333333333; + double value2 = 1.0 / 3; + Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}"); + } } // The example displays the following output: // 0.333333333333333 = 0.33333333333333331: False diff --git a/snippets/csharp/System/Double/Overview/comparison4.cs b/snippets/csharp/System/Double/Overview/comparison4.cs index 577ba93083f..ff55e925ab3 100644 --- a/snippets/csharp/System/Double/Overview/comparison4.cs +++ b/snippets/csharp/System/Double/Overview/comparison4.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -21,9 +21,9 @@ static bool IsApproximatelyEqual(double value1, double value2, double epsilon) return true; // Handle NaN, Infinity. - if (Double.IsInfinity(value1) | Double.IsNaN(value1)) + if (double.IsInfinity(value1) | double.IsNaN(value1)) return value1.Equals(value2); - else if (Double.IsInfinity(value2) | Double.IsNaN(value2)) + else if (double.IsInfinity(value2) | double.IsNaN(value2)) return value1.Equals(value2); // Handle zero to avoid division by zero diff --git a/snippets/csharp/System/Double/Overview/convert1.cs b/snippets/csharp/System/Double/Overview/convert1.cs index dee3e3e473f..9410d6b38bc 100644 --- a/snippets/csharp/System/Double/Overview/convert1.cs +++ b/snippets/csharp/System/Double/Overview/convert1.cs @@ -5,13 +5,13 @@ public class Example4 public static void Main() { // - dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue, - Decimal.MaxValue, Int16.MinValue, Int16.MaxValue, - Int32.MinValue, Int32.MaxValue, Int64.MinValue, - Int64.MaxValue, SByte.MinValue, SByte.MaxValue, - Single.MinValue, Single.MaxValue, UInt16.MinValue, - UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue, - UInt64.MinValue, UInt64.MaxValue }; + dynamic[] values = { byte.MinValue, byte.MaxValue, decimal.MinValue, + decimal.MaxValue, short.MinValue, short.MaxValue, + int.MinValue, int.MaxValue, long.MinValue, + long.MaxValue, sbyte.MinValue, sbyte.MaxValue, + float.MinValue, float.MaxValue, ushort.MinValue, + ushort.MaxValue, uint.MinValue, uint.MaxValue, + ulong.MinValue, ulong.MaxValue }; double dblValue; foreach (dynamic value in values) { diff --git a/snippets/csharp/System/Double/Overview/convert2.cs b/snippets/csharp/System/Double/Overview/convert2.cs index efd4c149833..7fe3e137411 100644 --- a/snippets/csharp/System/Double/Overview/convert2.cs +++ b/snippets/csharp/System/Double/Overview/convert2.cs @@ -1,21 +1,21 @@ -// +// using System; public class Example5 { public static void Main() { - Double[] values = { Double.MinValue, -67890.1234, -12345.6789, - 12345.6789, 67890.1234, Double.MaxValue, - Double.NaN, Double.PositiveInfinity, - Double.NegativeInfinity }; + double[] values = { double.MinValue, -67890.1234, -12345.6789, + 12345.6789, 67890.1234, double.MaxValue, + double.NaN, double.PositiveInfinity, + double.NegativeInfinity }; checked { - foreach (var value in values) + foreach (double value in values) { try { - Int64 lValue = (long)value; + long lValue = (long)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"); } catch (OverflowException) @@ -24,7 +24,7 @@ public static void Main() } try { - UInt64 ulValue = (ulong)value; + ulong ulValue = (ulong)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"); } catch (OverflowException) @@ -33,7 +33,7 @@ public static void Main() } try { - Decimal dValue = (decimal)value; + decimal dValue = (decimal)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"); } catch (OverflowException) @@ -42,7 +42,7 @@ public static void Main() } try { - Single sValue = (float)value; + float sValue = (float)value; Console.WriteLine($"{value} ({value.GetType().Name}) --> {sValue} ({sValue.GetType().Name})"); } catch (OverflowException) diff --git a/snippets/csharp/System/Double/Overview/exceptional1.cs b/snippets/csharp/System/Double/Overview/exceptional1.cs index 73330fc6ca4..d93b80983d9 100644 --- a/snippets/csharp/System/Double/Overview/exceptional1.cs +++ b/snippets/csharp/System/Double/Overview/exceptional1.cs @@ -1,13 +1,13 @@ -// +// using System; public class Example6 { public static void Main() { - Double value1 = 1.1632875981534209e-225; - Double value2 = 9.1642346778e-175; - Double result = value1 * value2; + double value1 = 1.1632875981534209e-225; + double value2 = 9.1642346778e-175; + double result = value1 * value2; Console.WriteLine($"{value1} * {value2} = {result}"); Console.WriteLine($"{result} = 0: {result.Equals(0.0)}"); } diff --git a/snippets/csharp/System/Double/Overview/exceptional2.cs b/snippets/csharp/System/Double/Overview/exceptional2.cs index 68e1e4b4cb5..e365ee45701 100644 --- a/snippets/csharp/System/Double/Overview/exceptional2.cs +++ b/snippets/csharp/System/Double/Overview/exceptional2.cs @@ -1,20 +1,20 @@ -// +// using System; public class Example7 { public static void Main() { - Double value1 = 4.565e153; - Double value2 = 6.9375e172; - Double result = value1 * value2; - Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}"); - Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}{Environment.NewLine}"); + double value1 = 4.565e153; + double value2 = 6.9375e172; + double result = value1 * value2; + Console.WriteLine($"PositiveInfinity: {double.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {double.IsNegativeInfinity(result)}{Environment.NewLine}"); value1 = -value1; result = value1 * value2; - Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}"); - Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}"); + Console.WriteLine($"PositiveInfinity: {double.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {double.IsNegativeInfinity(result)}"); } } diff --git a/snippets/csharp/System/Double/Overview/precision1.cs b/snippets/csharp/System/Double/Overview/precision1.cs index ff8c2abd667..dc321f5b21c 100644 --- a/snippets/csharp/System/Double/Overview/precision1.cs +++ b/snippets/csharp/System/Double/Overview/precision1.cs @@ -11,9 +11,9 @@ public static void Run() double fromVariable = value; double fromParse = double.Parse("-4.42330604244772E-305"); - Console.WriteLine("Double value from literal: {0,29:R}", fromLiteral); - Console.WriteLine("Double value from variable: {0,28:R}", fromVariable); - Console.WriteLine("Double value from Parse method: {0,24:R}", fromParse); + Console.WriteLine($"Double value from literal: {fromLiteral,29:R}"); + Console.WriteLine($"Double value from variable: {fromVariable,28:R}"); + Console.WriteLine($"Double value from Parse method: {fromParse,24:R}"); // The output is: // Double value from literal: -4.42330604244772E-305 diff --git a/snippets/csharp/System/Double/Overview/precisionlist3.cs b/snippets/csharp/System/Double/Overview/precisionlist3.cs index 11e92c87224..b10bddb9a9c 100644 --- a/snippets/csharp/System/Double/Overview/precisionlist3.cs +++ b/snippets/csharp/System/Double/Overview/precisionlist3.cs @@ -1,14 +1,14 @@ -// +// using System; public class Example10 { public static void Main() { - Double[] values = { 10.0, 2.88, 2.88, 2.88, 9.0 }; - Double result = 27.64; - Double total = 0; - foreach (var value in values) + double[] values = { 10.0, 2.88, 2.88, 2.88, 9.0 }; + double result = 27.64; + double total = 0; + foreach (double value in values) total += value; if (total.Equals(result)) diff --git a/snippets/csharp/System/Double/Overview/representation1.cs b/snippets/csharp/System/Double/Overview/representation1.cs index 52b1d272ab1..6730805072e 100644 --- a/snippets/csharp/System/Double/Overview/representation1.cs +++ b/snippets/csharp/System/Double/Overview/representation1.cs @@ -1,13 +1,13 @@ -// +// using System; public class Example13 { public static void Main() { - Double value = .1; - Double result1 = value * 10; - Double result2 = 0; + double value = .1; + double result1 = value * 10; + double result2 = 0; for (int ctr = 1; ctr <= 10; ctr++) result2 += value; diff --git a/snippets/csharp/System/Double/Overview/representation2.cs b/snippets/csharp/System/Double/Overview/representation2.cs index d4ab7b394b6..a5ab2848291 100644 --- a/snippets/csharp/System/Double/Overview/representation2.cs +++ b/snippets/csharp/System/Double/Overview/representation2.cs @@ -1,12 +1,12 @@ -// +// using System; public class Example14 { public static void Main() { - Double value = 123456789012.34567; - Double additional = Double.Epsilon * 1e15; + double value = 123456789012.34567; + double additional = double.Epsilon * 1e15; Console.WriteLine($"{value} + {additional} = {value + additional}"); } } diff --git a/snippets/csharp/System/Double/Overview/source.cs b/snippets/csharp/System/Double/Overview/source.cs index fdaf6981acd..7f6604ba3dd 100644 --- a/snippets/csharp/System/Double/Overview/source.cs +++ b/snippets/csharp/System/Double/Overview/source.cs @@ -1,395 +1,368 @@ using System; using System.Globalization; -namespace Snippets { - class Launcher { - static void Main(string[] args) - { - Temperature t1 = Temperature.Parse("20'F", NumberStyles.Float, null); - Console.WriteLine( t1.ToString("F", null) ); - - string str1 = t1.ToString("C", null); - Console.WriteLine( str1 ); - - Temperature t2 = Temperature.Parse(str1, NumberStyles.Float, null); - Console.WriteLine( t2.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t2) ); - - Temperature t3 = Temperature.Parse("20'C", NumberStyles.Float, null); - Console.WriteLine( t3.ToString("F", null) ); - - Console.WriteLine( t1.CompareTo(t3) ); - } - } - // - // The Temperature class stores the temperature as a Double - // and delegates most of the functionality to the Double - // implementation. - public class Temperature : IComparable, IFormattable +namespace Snippets +{ + class Launcher { - // IComparable.CompareTo implementation. - public int CompareTo(object obj) { + static void Main(string[] args) + { + Temperature t1 = Temperature.Parse("20'F", NumberStyles.Float, null); + Console.WriteLine(t1.ToString("F", null)); + + string str1 = t1.ToString("C", null); + Console.WriteLine(str1); + + Temperature t2 = Temperature.Parse(str1, NumberStyles.Float, null); + Console.WriteLine(t2.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t2)); + + Temperature t3 = Temperature.Parse("20'C", NumberStyles.Float, null); + Console.WriteLine(t3.ToString("F", null)); + + Console.WriteLine(t1.CompareTo(t3)); + } + } + // + // The Temperature class stores the temperature as a Double + // and delegates most of the functionality to the Double + // implementation. + public class Temperature : IComparable, IFormattable + { + // IComparable.CompareTo implementation. + public int CompareTo(object obj) + { if (obj == null) return 1; - Temperature temp = obj as Temperature; + Temperature temp = obj as Temperature; if (obj != null) - return m_value.CompareTo(temp.m_value); - else - throw new ArgumentException("object is not a Temperature"); - } - - // IFormattable.ToString implementation. - public string ToString(string format, IFormatProvider provider) { - if( format != null ) { - if( format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - if( format.Equals("C") ) { - return String.Format("{0}'C", this.Celsius.ToString()); - } - } - - return m_value.ToString(format, provider); - } - - // Parses the temperature from a string in the form - // [ws][sign]digits['F|'C][ws] - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else if( s.TrimEnd(null).EndsWith("'C") ) { - temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = Double.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // + return m_value.CompareTo(temp.m_value); + else + throw new ArgumentException("object is not a Temperature"); + } + + // IFormattable.ToString implementation. + public string ToString(string format, IFormatProvider provider) + { + if (format != null) + { + if (format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + if (format.Equals("C")) + { + return $"{this.Celsius.ToString()}'C"; + } + } + + return m_value.ToString(format, provider); + } + + // Parses the temperature from a string in the form + // [ws][sign]digits['F|'C][ws] + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else if (s.TrimEnd(null).EndsWith("'C")) + { + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = double.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets2 { - // - public class Temperature { - public static double MinValue { - get { - return Double.MinValue; - } - } - - public static double MaxValue { - get { - return Double.MaxValue; - } - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets2 +{ + // + public class Temperature + { + public static double MinValue => double.MinValue; + + public static double MaxValue => double.MaxValue; + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets3 { - // - public class Temperature : IComparable +namespace Snippets3 +{ + // + public class Temperature : IComparable { - // IComparable.CompareTo implementation. - public int CompareTo(object obj) { + // IComparable.CompareTo implementation. + public int CompareTo(object obj) + { if (obj == null) return 1; - Temperature temp = obj as Temperature; + Temperature temp = obj as Temperature; if (obj != null) - return m_value.CompareTo(temp.m_value); - else - throw new ArgumentException("object is not a Temperature"); - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // + return m_value.CompareTo(temp.m_value); + else + throw new ArgumentException("object is not a Temperature"); + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets4 { - // - public class Temperature : IFormattable { - // IFormattable.ToString implementation. - public string ToString(string format, IFormatProvider provider) { - if( format != null ) { - if( format.Equals("F") ) { - return String.Format("{0}'F", this.Value.ToString()); - } - if( format.Equals("C") ) { - return String.Format("{0}'C", this.Celsius.ToString()); - } - } - - return m_value.ToString(format, provider); - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets4 +{ + // + public class Temperature : IFormattable + { + // IFormattable.ToString implementation. + public string ToString(string format, IFormatProvider provider) + { + if (format != null) + { + if (format.Equals("F")) + { + return $"{this.Value.ToString()}'F"; + } + if (format.Equals("C")) + { + return $"{this.Celsius.ToString()}'C"; + } + } + + return m_value.ToString(format, provider); + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets5 { - // - public class Temperature { - // Parses the temperature from a string in form - // [ws][sign]digits['F|'C][ws] - public static Temperature Parse(string s) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else if( s.TrimEnd(null).EndsWith("'C") ) { - temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) ); - } - else { - temp.Value = Double.Parse(s); - } - - return temp; - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets5 +{ + // + public class Temperature + { + // Parses the temperature from a string in form + // [ws][sign]digits['F|'C][ws] + public static Temperature Parse(string s) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else if (s.TrimEnd(null).EndsWith("'C")) + { + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf('\''), 2)); + } + else + { + temp.Value = double.Parse(s); + } + + return temp; + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets6 { - // - public class Temperature { - // Parses the temperature from a string in form - // [ws][sign]digits['F|'C][ws] - public static Temperature Parse(string s, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else if( s.TrimEnd(null).EndsWith("'C") ) { - temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), provider); - } - else { - temp.Value = Double.Parse(s, provider); - } - - return temp; - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets6 +{ + // + public class Temperature + { + // Parses the temperature from a string in form + // [ws][sign]digits['F|'C][ws] + public static Temperature Parse(string s, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else if (s.TrimEnd(null).EndsWith("'C")) + { + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf('\''), 2), provider); + } + else + { + temp.Value = double.Parse(s, provider); + } + + return temp; + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets7 { - // - public class Temperature { - // Parses the temperature from a string in form - // [ws][sign]digits['F|'C][ws] - public static Temperature Parse(string s, NumberStyles styles) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else if( s.TrimEnd(null).EndsWith("'C") ) { - temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles); - } - else { - temp.Value = Double.Parse(s, styles); - } - - return temp; - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets7 +{ + // + public class Temperature + { + // Parses the temperature from a string in form + // [ws][sign]digits['F|'C][ws] + public static Temperature Parse(string s, NumberStyles styles) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else if (s.TrimEnd(null).EndsWith("'C")) + { + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles); + } + else + { + temp.Value = double.Parse(s, styles); + } + + return temp; + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } -namespace Snippets8 { - // - public class Temperature { - // Parses the temperature from a string in form - // [ws][sign]digits['F|'C][ws] - public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) { - Temperature temp = new Temperature(); - - if( s.TrimEnd(null).EndsWith("'F") ) { - temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else if( s.TrimEnd(null).EndsWith("'C") ) { - temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider); - } - else { - temp.Value = Double.Parse(s, styles, provider); - } - - return temp; - } - - // The value holder - protected double m_value; - - public double Value { - get { - return m_value; - } - set { - m_value = value; - } - } - - public double Celsius { - get { - return (m_value-32.0)/1.8; - } - set { - m_value = 1.8*value+32.0; - } - } - } - // +namespace Snippets8 +{ + // + public class Temperature + { + // Parses the temperature from a string in form + // [ws][sign]digits['F|'C][ws] + public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) + { + Temperature temp = new(); + + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else if (s.TrimEnd(null).EndsWith("'C")) + { + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf('\''), 2), styles, provider); + } + else + { + temp.Value = double.Parse(s, styles, provider); + } + + return temp; + } + + // The value holder + protected double m_value; + + public double Value { + get => m_value; + set => m_value = value; + } + + public double Celsius { + get => (m_value - 32.0) / 1.8; + set => m_value = 1.8 * value + 32.0; + } + } + // } diff --git a/snippets/csharp/System/Double/Parse/Parse.cs b/snippets/csharp/System/Double/Parse/Parse.cs index 80df12dcd2b..2343922ca88 100644 --- a/snippets/csharp/System/Double/Parse/Parse.cs +++ b/snippets/csharp/System/Double/Parse/Parse.cs @@ -4,67 +4,65 @@ public class ParseString { - // - public static void Main() - { - // Set current thread culture to en-US. - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); + // + public static void Main() + { + // Set current thread culture to en-US. + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - string value; - NumberStyles styles; + string value; + NumberStyles styles; - // Parse a string in exponential notation with only the AllowExponent flag. - value = "-1.063E-02"; - styles = NumberStyles.AllowExponent; - ShowNumericValue(value, styles); + // Parse a string in exponential notation with only the AllowExponent flag. + value = "-1.063E-02"; + styles = NumberStyles.AllowExponent; + ShowNumericValue(value, styles); - // Parse a string in exponential notation - // with the AllowExponent and Number flags. - styles = NumberStyles.AllowExponent | NumberStyles.Number; - ShowNumericValue(value, styles); + // Parse a string in exponential notation + // with the AllowExponent and Number flags. + styles = NumberStyles.AllowExponent | NumberStyles.Number; + ShowNumericValue(value, styles); - // Parse a currency value with leading and trailing white space, and - // white space after the U.S. currency symbol. - value = " $ 6,164.3299 "; - styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; - ShowNumericValue(value, styles); + // Parse a currency value with leading and trailing white space, and + // white space after the U.S. currency symbol. + value = " $ 6,164.3299 "; + styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; + ShowNumericValue(value, styles); - // Parse negative value with thousands separator and decimal. - value = "(4,320.64)"; - styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | - NumberStyles.Float; - ShowNumericValue(value, styles); + // Parse negative value with thousands separator and decimal. + value = "(4,320.64)"; + styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | + NumberStyles.Float; + ShowNumericValue(value, styles); - styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | - NumberStyles.Float | NumberStyles.AllowThousands; - ShowNumericValue(value, styles); - } + styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | + NumberStyles.Float | NumberStyles.AllowThousands; + ShowNumericValue(value, styles); + } - private static void ShowNumericValue(string value, NumberStyles styles) - { - double number; - try - { - number = Double.Parse(value, styles); - Console.WriteLine("Converted '{0}' using {1} to {2}.", - value, styles.ToString(), number); - } - catch (FormatException) - { - Console.WriteLine("Unable to parse '{0}' with styles {1}.", - value, styles.ToString()); - } - Console.WriteLine(); - } - // The example displays the following output to the console: - // Unable to parse '-1.063E-02' with styles AllowExponent. - // - // Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063. - // - // Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299. - // - // Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float. - // - // Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64. - // + private static void ShowNumericValue(string value, NumberStyles styles) + { + double number; + try + { + number = double.Parse(value, styles); + Console.WriteLine($"Converted '{value}' using {styles.ToString()} to {number}."); + } + catch (FormatException) + { + Console.WriteLine($"Unable to parse '{value}' with styles {styles.ToString()}."); + } + Console.WriteLine(); + } + // The example displays the following output to the console: + // Unable to parse '-1.063E-02' with styles AllowExponent. + // + // Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063. + // + // Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299. + // + // Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float. + // + // Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64. + // } diff --git a/snippets/csharp/System/Double/Parse/Parse3.cs b/snippets/csharp/System/Double/Parse/Parse3.cs index 7d2c6ace5a0..d5eca130771 100644 --- a/snippets/csharp/System/Double/Parse/Parse3.cs +++ b/snippets/csharp/System/Double/Parse/Parse3.cs @@ -4,85 +4,79 @@ public class Temperature { - // Parses the temperature from a string. Temperature scale is - // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end - // of the string. - public static Temperature Parse(string s, NumberStyles styles, - IFormatProvider provider) - { - Temperature temp = new Temperature(); + // Parses the temperature from a string. Temperature scale is + // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end + // of the string. + public static Temperature Parse(string s, NumberStyles styles, + IFormatProvider provider) + { + Temperature temp = new(); - if (s.TrimEnd(null).EndsWith("'F")) - { - temp.Value = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2), - styles, provider); - } - else - { - if (s.TrimEnd(null).EndsWith("'C")) - temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2), - styles, provider); - else - temp.Value = Double.Parse(s, styles, provider); - } - return temp; - } + if (s.TrimEnd(null).EndsWith("'F")) + { + temp.Value = double.Parse(s.Remove(s.LastIndexOf((char)39), 2), + styles, provider); + } + else + { + if (s.TrimEnd(null).EndsWith("'C")) + temp.Celsius = double.Parse(s.Remove(s.LastIndexOf((char)39), 2), + styles, provider); + else + temp.Value = double.Parse(s, styles, provider); + } + return temp; + } - // Declare private constructor so Temperature so only Parse method can - // create a new instance - private Temperature() {} + // Declare private constructor so Temperature so only Parse method can + // create a new instance + private Temperature() { } - protected double m_value; + protected double m_value; - public double Value + public double Value { - get { return m_value; } - private set { m_value = value; } + get => m_value; + private set => m_value = value; } - public double Celsius + public double Celsius { - get { return (m_value - 32) / 1.8; } - private set { m_value = value * 1.8 + 32; } + get => (m_value - 32) / 1.8; + private set => m_value = value * 1.8 + 32; } - public double Fahrenheit - { - get {return m_value; } - } + public double Fahrenheit => m_value; } public class TestTemperature { - public static void Main() - { - string value; - NumberStyles styles; - IFormatProvider provider; - Temperature temp; + public static void Main() + { + string value; + NumberStyles styles; + IFormatProvider provider; + Temperature temp; - value = "25,3'C"; - styles = NumberStyles.Float; - provider = CultureInfo.CreateSpecificCulture("fr-FR"); - temp = Temperature.Parse(value, styles, provider); - Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", - temp.Fahrenheit, temp.Celsius); + value = "25,3'C"; + styles = NumberStyles.Float; + provider = CultureInfo.CreateSpecificCulture("fr-FR"); + temp = Temperature.Parse(value, styles, provider); + Console.WriteLine($"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."); - value = " (40) 'C"; - styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite - | NumberStyles.AllowParentheses; - provider = NumberFormatInfo.InvariantInfo; - temp = Temperature.Parse(value, styles, provider); - Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", - temp.Fahrenheit, temp.Celsius); + value = " (40) 'C"; + styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite + | NumberStyles.AllowParentheses; + provider = NumberFormatInfo.InvariantInfo; + temp = Temperature.Parse(value, styles, provider); + Console.WriteLine($"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."); - value = "5,778E03'C"; // Approximate surface temperature of the Sun - styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | - NumberStyles.AllowExponent; - provider = CultureInfo.CreateSpecificCulture("en-GB"); - temp = Temperature.Parse(value, styles, provider); - Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", - temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N")); - } + value = "5,778E03'C"; // Approximate surface temperature of the Sun + styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | + NumberStyles.AllowExponent; + provider = CultureInfo.CreateSpecificCulture("en-GB"); + temp = Temperature.Parse(value, styles, provider); + Console.WriteLine($"{temp.Fahrenheit.ToString("N")} degrees Fahrenheit equals {temp.Celsius.ToString("N")} degrees Celsius."); + } } // diff --git a/snippets/csharp/System/Double/Parse/parse2.cs b/snippets/csharp/System/Double/Parse/parse2.cs index c246ea71bb0..7eeb5c6b557 100644 --- a/snippets/csharp/System/Double/Parse/parse2.cs +++ b/snippets/csharp/System/Double/Parse/parse2.cs @@ -2,41 +2,45 @@ public class Example { - public static void Main() - { - // - string value; + public static void Main() + { + // + string value; - value = Double.MinValue.ToString(); - try { - Console.WriteLine(Double.Parse(value)); - } - catch (OverflowException) { - Console.WriteLine($"{value} is outside the range of the Double type."); - } + value = double.MinValue.ToString(); + try + { + Console.WriteLine(double.Parse(value)); + } + catch (OverflowException) + { + Console.WriteLine($"{value} is outside the range of the Double type."); + } - value = Double.MaxValue.ToString(); - try { - Console.WriteLine(Double.Parse(value)); - } - catch (OverflowException) { - Console.WriteLine($"{value} is outside the range of the Double type."); - } + value = double.MaxValue.ToString(); + try + { + Console.WriteLine(double.Parse(value)); + } + catch (OverflowException) + { + Console.WriteLine($"{value} is outside the range of the Double type."); + } - // Format without the default precision. - value = Double.MinValue.ToString("G17"); - try - { - Console.WriteLine(Double.Parse(value)); - } - catch (OverflowException) - { - Console.WriteLine($"{value} is outside the range of the Double type."); - } - // The example displays the following output: - // -1.79769313486232E+308 is outside the range of the Double type. - // 1.79769313486232E+308 is outside the range of the Double type. - // -1.79769313486232E+308 - // - } + // Format without the default precision. + value = double.MinValue.ToString("G17"); + try + { + Console.WriteLine(double.Parse(value)); + } + catch (OverflowException) + { + Console.WriteLine($"{value} is outside the range of the Double type."); + } + // The example displays the following output: + // -1.79769313486232E+308 is outside the range of the Double type. + // 1.79769313486232E+308 is outside the range of the Double type. + // -1.79769313486232E+308 + // + } } diff --git a/snippets/csharp/System/Double/ToString/ToString1.cs b/snippets/csharp/System/Double/ToString/ToString1.cs index e83551e10e5..7f09edb4f05 100644 --- a/snippets/csharp/System/Double/ToString/ToString1.cs +++ b/snippets/csharp/System/Double/ToString/ToString1.cs @@ -3,357 +3,358 @@ public class Class1 { - public static void Main() - { - CallDefaultToString(); - Console.WriteLine("----------"); - CallToStringWithFormatProvider(); - Console.WriteLine("----------"); - CallToStringWithFormatString(); - Console.WriteLine("----------"); - CallToStringWithFormatStringAndProvider(); - } + public static void Main() + { + CallDefaultToString(); + Console.WriteLine("----------"); + CallToStringWithFormatProvider(); + Console.WriteLine("----------"); + CallToStringWithFormatString(); + Console.WriteLine("----------"); + CallToStringWithFormatStringAndProvider(); + } - private static void CallDefaultToString() - { - // - double number; + private static void CallDefaultToString() + { + // + double number; - number = 1.6E20; - // Displays 1.6E+20. - Console.WriteLine(number.ToString()); + number = 1.6E20; + // Displays 1.6E+20. + Console.WriteLine(number.ToString()); - number = 1.6E2; - // Displays 160. - Console.WriteLine(number.ToString()); + number = 1.6E2; + // Displays 160. + Console.WriteLine(number.ToString()); - number = -3.541; - // Displays -3.541. - Console.WriteLine(number.ToString()); + number = -3.541; + // Displays -3.541. + Console.WriteLine(number.ToString()); - number = -1502345222199E-07; - // Displays -150234.5222199. - Console.WriteLine(number.ToString()); + number = -1502345222199E-07; + // Displays -150234.5222199. + Console.WriteLine(number.ToString()); - number = -15023452221990199574E-09; - // Displays -15023452221.9902. - Console.WriteLine(number.ToString()); + number = -15023452221990199574E-09; + // Displays -15023452221.9902. + Console.WriteLine(number.ToString()); - number = .60344; - // Displays 0.60344. - Console.WriteLine(number.ToString()); + number = .60344; + // Displays 0.60344. + Console.WriteLine(number.ToString()); - number = .000000001; - // Displays 1E-09. - Console.WriteLine(number.ToString()); - // - } + number = .000000001; + // Displays 1E-09. + Console.WriteLine(number.ToString()); + // + } - private static void CallToStringWithFormatProvider() - { - // - double value; + private static void CallToStringWithFormatProvider() + { + // + double value; - value = -16325.62015; - // Display value using the invariant culture. - Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); - // Display value using the en-GB culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); - // Display value using the de-DE culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); + value = -16325.62015; + // Display value using the invariant culture. + Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); + // Display value using the en-GB culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); + // Display value using the de-DE culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); - value = 16034.125E21; - // Display value using the invariant culture. - Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); - // Display value using the en-GB culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); - // Display value using the de-DE culture. - Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); - // This example displays the following output to the console: - // -16325.62015 - // -16325.62015 - // -16325,62015 - // 1.6034125E+25 - // 1.6034125E+25 - // 1,6034125E+25 - // - } + value = 16034.125E21; + // Display value using the invariant culture. + Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); + // Display value using the en-GB culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); + // Display value using the de-DE culture. + Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE"))); + // This example displays the following output to the console: + // -16325.62015 + // -16325.62015 + // -16325,62015 + // 1.6034125E+25 + // 1.6034125E+25 + // 1,6034125E+25 + // + } - private static void CallToStringWithFormatString() - { - // - double[] numbers= {1054.32179, -195489100.8377, 1.0437E21, + private static void CallToStringWithFormatString() + { + // + double[] numbers = {1054.32179, -195489100.8377, 1.0437E21, -1.0573e-05}; - string[] specifiers = { "C", "E", "e", "F", "G", "N", "P", + string[] specifiers = { "C", "E", "e", "F", "G", "N", "P", "R", "#,000.000", "0.###E-000", "000,000,000,000.00###" }; - foreach (double number in numbers) - { - Console.WriteLine("Formatting of {0}:", number); - foreach (string specifier in specifiers) { - Console.WriteLine(" {0,-22} {1}", - specifier + ":", number.ToString(specifier)); - // Add precision specifiers from 0 to 3. - if (specifier.Length == 1 & ! specifier.Equals("R")) { - for (int precision = 0; precision <= 3; precision++) { - string pSpecifier = String.Format("{0}{1}", specifier, precision); - Console.WriteLine(" {0,-22} {1}", - pSpecifier + ":", number.ToString(pSpecifier)); - } - Console.WriteLine(); + foreach (double number in numbers) + { + Console.WriteLine($"Formatting of {number}:"); + foreach (string specifier in specifiers) + { + Console.WriteLine($" {specifier + ":",-22} {number.ToString(specifier)}"); + // Add precision specifiers from 0 to 3. + if (specifier.Length == 1 & !specifier.Equals("R")) + { + for (int precision = 0; precision <= 3; precision++) + { + string pSpecifier = $"{specifier}{precision}"; + Console.WriteLine($" {pSpecifier + ":",-22} {number.ToString(pSpecifier)}"); + } + Console.WriteLine(); + } } - } - Console.WriteLine(); - } - // The example displays the following output to the console: - // Formatting of 1054.32179: - // C: $1,054.32 - // C0: $1,054 - // C1: $1,054.3 - // C2: $1,054.32 - // C3: $1,054.322 - // - // E: 1.054322E+003 - // E0: 1E+003 - // E1: 1.1E+003 - // E2: 1.05E+003 - // E3: 1.054E+003 - // - // e: 1.054322e+003 - // e0: 1e+003 - // e1: 1.1e+003 - // e2: 1.05e+003 - // e3: 1.054e+003 - // - // F: 1054.32 - // F0: 1054 - // F1: 1054.3 - // F2: 1054.32 - // F3: 1054.322 - // - // G: 1054.32179 - // G0: 1054.32179 - // G1: 1E+03 - // G2: 1.1E+03 - // G3: 1.05E+03 - // - // N: 1,054.32 - // N0: 1,054 - // N1: 1,054.3 - // N2: 1,054.32 - // N3: 1,054.322 - // - // P: 105,432.18 % - // P0: 105,432 % - // P1: 105,432.2 % - // P2: 105,432.18 % - // P3: 105,432.179 % - // - // R: 1054.32179 - // #,000.000: 1,054.322 - // 0.###E-000: 1.054E003 - // 000,000,000,000.00###: 000,000,001,054.32179 - // - // Formatting of -195489100.8377: - // C: ($195,489,100.84) - // C0: ($195,489,101) - // C1: ($195,489,100.8) - // C2: ($195,489,100.84) - // C3: ($195,489,100.838) - // - // E: -1.954891E+008 - // E0: -2E+008 - // E1: -2.0E+008 - // E2: -1.95E+008 - // E3: -1.955E+008 - // - // e: -1.954891e+008 - // e0: -2e+008 - // e1: -2.0e+008 - // e2: -1.95e+008 - // e3: -1.955e+008 - // - // F: -195489100.84 - // F0: -195489101 - // F1: -195489100.8 - // F2: -195489100.84 - // F3: -195489100.838 - // - // G: -195489100.8377 - // G0: -195489100.8377 - // G1: -2E+08 - // G2: -2E+08 - // G3: -1.95E+08 - // - // N: -195,489,100.84 - // N0: -195,489,101 - // N1: -195,489,100.8 - // N2: -195,489,100.84 - // N3: -195,489,100.838 - // - // P: -19,548,910,083.77 % - // P0: -19,548,910,084 % - // P1: -19,548,910,083.8 % - // P2: -19,548,910,083.77 % - // P3: -19,548,910,083.770 % - // - // R: -195489100.8377 - // #,000.000: -195,489,100.838 - // 0.###E-000: -1.955E008 - // 000,000,000,000.00###: -000,195,489,100.8377 - // - // Formatting of 1.0437E+21: - // C: $1,043,700,000,000,000,000,000.00 - // C0: $1,043,700,000,000,000,000,000 - // C1: $1,043,700,000,000,000,000,000.0 - // C2: $1,043,700,000,000,000,000,000.00 - // C3: $1,043,700,000,000,000,000,000.000 - // - // E: 1.043700E+021 - // E0: 1E+021 - // E1: 1.0E+021 - // E2: 1.04E+021 - // E3: 1.044E+021 - // - // e: 1.043700e+021 - // e0: 1e+021 - // e1: 1.0e+021 - // e2: 1.04e+021 - // e3: 1.044e+021 - // - // F: 1043700000000000000000.00 - // F0: 1043700000000000000000 - // F1: 1043700000000000000000.0 - // F2: 1043700000000000000000.00 - // F3: 1043700000000000000000.000 - // - // G: 1.0437E+21 - // G0: 1.0437E+21 - // G1: 1E+21 - // G2: 1E+21 - // G3: 1.04E+21 - // - // N: 1,043,700,000,000,000,000,000.00 - // N0: 1,043,700,000,000,000,000,000 - // N1: 1,043,700,000,000,000,000,000.0 - // N2: 1,043,700,000,000,000,000,000.00 - // N3: 1,043,700,000,000,000,000,000.000 - // - // P: 104,370,000,000,000,000,000,000.00 % - // P0: 104,370,000,000,000,000,000,000 % - // P1: 104,370,000,000,000,000,000,000.0 % - // P2: 104,370,000,000,000,000,000,000.00 % - // P3: 104,370,000,000,000,000,000,000.000 % - // - // R: 1.0437E+21 - // #,000.000: 1,043,700,000,000,000,000,000.000 - // 0.###E-000: 1.044E021 - // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00 - // - // Formatting of -1.0573E-05: - // C: $0.00 - // C0: $0 - // C1: $0.0 - // C2: $0.00 - // C3: $0.000 - // - // E: -1.057300E-005 - // E0: -1E-005 - // E1: -1.1E-005 - // E2: -1.06E-005 - // E3: -1.057E-005 - // - // e: -1.057300e-005 - // e0: -1e-005 - // e1: -1.1e-005 - // e2: -1.06e-005 - // e3: -1.057e-005 - // - // F: 0.00 - // F0: 0 - // F1: 0.0 - // F2: 0.00 - // F3: 0.000 - // - // G: -1.0573E-05 - // G0: -1.0573E-05 - // G1: -1E-05 - // G2: -1.1E-05 - // G3: -1.06E-05 - // - // N: 0.00 - // N0: 0 - // N1: 0.0 - // N2: 0.00 - // N3: 0.000 - // - // P: 0.00 % - // P0: 0 % - // P1: 0.0 % - // P2: 0.00 % - // P3: -0.001 % - // - // R: -1.0573E-05 - // #,000.000: 000.000 - // 0.###E-000: -1.057E-005 - // 000,000,000,000.00###: -000,000,000,000.00001 - // - } + Console.WriteLine(); + } + // The example displays the following output to the console: + // Formatting of 1054.32179: + // C: $1,054.32 + // C0: $1,054 + // C1: $1,054.3 + // C2: $1,054.32 + // C3: $1,054.322 + // + // E: 1.054322E+003 + // E0: 1E+003 + // E1: 1.1E+003 + // E2: 1.05E+003 + // E3: 1.054E+003 + // + // e: 1.054322e+003 + // e0: 1e+003 + // e1: 1.1e+003 + // e2: 1.05e+003 + // e3: 1.054e+003 + // + // F: 1054.32 + // F0: 1054 + // F1: 1054.3 + // F2: 1054.32 + // F3: 1054.322 + // + // G: 1054.32179 + // G0: 1054.32179 + // G1: 1E+03 + // G2: 1.1E+03 + // G3: 1.05E+03 + // + // N: 1,054.32 + // N0: 1,054 + // N1: 1,054.3 + // N2: 1,054.32 + // N3: 1,054.322 + // + // P: 105,432.18 % + // P0: 105,432 % + // P1: 105,432.2 % + // P2: 105,432.18 % + // P3: 105,432.179 % + // + // R: 1054.32179 + // #,000.000: 1,054.322 + // 0.###E-000: 1.054E003 + // 000,000,000,000.00###: 000,000,001,054.32179 + // + // Formatting of -195489100.8377: + // C: ($195,489,100.84) + // C0: ($195,489,101) + // C1: ($195,489,100.8) + // C2: ($195,489,100.84) + // C3: ($195,489,100.838) + // + // E: -1.954891E+008 + // E0: -2E+008 + // E1: -2.0E+008 + // E2: -1.95E+008 + // E3: -1.955E+008 + // + // e: -1.954891e+008 + // e0: -2e+008 + // e1: -2.0e+008 + // e2: -1.95e+008 + // e3: -1.955e+008 + // + // F: -195489100.84 + // F0: -195489101 + // F1: -195489100.8 + // F2: -195489100.84 + // F3: -195489100.838 + // + // G: -195489100.8377 + // G0: -195489100.8377 + // G1: -2E+08 + // G2: -2E+08 + // G3: -1.95E+08 + // + // N: -195,489,100.84 + // N0: -195,489,101 + // N1: -195,489,100.8 + // N2: -195,489,100.84 + // N3: -195,489,100.838 + // + // P: -19,548,910,083.77 % + // P0: -19,548,910,084 % + // P1: -19,548,910,083.8 % + // P2: -19,548,910,083.77 % + // P3: -19,548,910,083.770 % + // + // R: -195489100.8377 + // #,000.000: -195,489,100.838 + // 0.###E-000: -1.955E008 + // 000,000,000,000.00###: -000,195,489,100.8377 + // + // Formatting of 1.0437E+21: + // C: $1,043,700,000,000,000,000,000.00 + // C0: $1,043,700,000,000,000,000,000 + // C1: $1,043,700,000,000,000,000,000.0 + // C2: $1,043,700,000,000,000,000,000.00 + // C3: $1,043,700,000,000,000,000,000.000 + // + // E: 1.043700E+021 + // E0: 1E+021 + // E1: 1.0E+021 + // E2: 1.04E+021 + // E3: 1.044E+021 + // + // e: 1.043700e+021 + // e0: 1e+021 + // e1: 1.0e+021 + // e2: 1.04e+021 + // e3: 1.044e+021 + // + // F: 1043700000000000000000.00 + // F0: 1043700000000000000000 + // F1: 1043700000000000000000.0 + // F2: 1043700000000000000000.00 + // F3: 1043700000000000000000.000 + // + // G: 1.0437E+21 + // G0: 1.0437E+21 + // G1: 1E+21 + // G2: 1E+21 + // G3: 1.04E+21 + // + // N: 1,043,700,000,000,000,000,000.00 + // N0: 1,043,700,000,000,000,000,000 + // N1: 1,043,700,000,000,000,000,000.0 + // N2: 1,043,700,000,000,000,000,000.00 + // N3: 1,043,700,000,000,000,000,000.000 + // + // P: 104,370,000,000,000,000,000,000.00 % + // P0: 104,370,000,000,000,000,000,000 % + // P1: 104,370,000,000,000,000,000,000.0 % + // P2: 104,370,000,000,000,000,000,000.00 % + // P3: 104,370,000,000,000,000,000,000.000 % + // + // R: 1.0437E+21 + // #,000.000: 1,043,700,000,000,000,000,000.000 + // 0.###E-000: 1.044E021 + // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00 + // + // Formatting of -1.0573E-05: + // C: $0.00 + // C0: $0 + // C1: $0.0 + // C2: $0.00 + // C3: $0.000 + // + // E: -1.057300E-005 + // E0: -1E-005 + // E1: -1.1E-005 + // E2: -1.06E-005 + // E3: -1.057E-005 + // + // e: -1.057300e-005 + // e0: -1e-005 + // e1: -1.1e-005 + // e2: -1.06e-005 + // e3: -1.057e-005 + // + // F: 0.00 + // F0: 0 + // F1: 0.0 + // F2: 0.00 + // F3: 0.000 + // + // G: -1.0573E-05 + // G0: -1.0573E-05 + // G1: -1E-05 + // G2: -1.1E-05 + // G3: -1.06E-05 + // + // N: 0.00 + // N0: 0 + // N1: 0.0 + // N2: 0.00 + // N3: 0.000 + // + // P: 0.00 % + // P0: 0 % + // P1: 0.0 % + // P2: 0.00 % + // P3: -0.001 % + // + // R: -1.0573E-05 + // #,000.000: 000.000 + // 0.###E-000: -1.057E-005 + // 000,000,000,000.00###: -000,000,000,000.00001 + // + } - private static void CallToStringWithFormatStringAndProvider() - { - // - double value = 16325.62901; - string specifier; - CultureInfo culture; + private static void CallToStringWithFormatStringAndProvider() + { + // + double value = 16325.62901; + string specifier; + CultureInfo culture; - // Use standard numeric format specifiers. - specifier = "G"; - culture = CultureInfo.CreateSpecificCulture("eu-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,62901 - Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); - // Displays: 16325.62901 + // Use standard numeric format specifiers. + specifier = "G"; + culture = CultureInfo.CreateSpecificCulture("eu-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,62901 + Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture)); + // Displays: 16325.62901 - specifier = "C"; - culture = CultureInfo.CreateSpecificCulture("en-US"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: $16,325.63 - culture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: £16,325.63 + specifier = "C"; + culture = CultureInfo.CreateSpecificCulture("en-US"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: $16,325.63 + culture = CultureInfo.CreateSpecificCulture("en-GB"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: £16,325.63 - specifier = "E04"; - culture = CultureInfo.CreateSpecificCulture("sv-SE"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1,6326E+004 - culture = CultureInfo.CreateSpecificCulture("en-NZ"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 1.6326E+004 + specifier = "E04"; + culture = CultureInfo.CreateSpecificCulture("sv-SE"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1,6326E+004 + culture = CultureInfo.CreateSpecificCulture("en-NZ"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 1.6326E+004 - specifier = "F"; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325,63 - culture = CultureInfo.CreateSpecificCulture("en-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16325.63 + specifier = "F"; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325,63 + culture = CultureInfo.CreateSpecificCulture("en-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16325.63 - specifier = "N"; - culture = CultureInfo.CreateSpecificCulture("es-ES"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16.325,63 - culture = CultureInfo.CreateSpecificCulture("fr-CA"); - Console.WriteLine(value.ToString(specifier, culture)); - // Displays: 16 325,63 + specifier = "N"; + culture = CultureInfo.CreateSpecificCulture("es-ES"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16.325,63 + culture = CultureInfo.CreateSpecificCulture("fr-CA"); + Console.WriteLine(value.ToString(specifier, culture)); + // Displays: 16 325,63 - specifier = "P"; - culture = CultureInfo.InvariantCulture; - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.26 % - culture = CultureInfo.CreateSpecificCulture("ar-EG"); - Console.WriteLine((value/10000).ToString(specifier, culture)); - // Displays: 163.256 % - // - } + specifier = "P"; + culture = CultureInfo.InvariantCulture; + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.26 % + culture = CultureInfo.CreateSpecificCulture("ar-EG"); + Console.WriteLine((value / 10000).ToString(specifier, culture)); + // Displays: 163.256 % + // + } } diff --git a/snippets/csharp/System/Double/ToString/ToString7.cs b/snippets/csharp/System/Double/ToString/ToString7.cs index 1e73b78c0ad..028b964f885 100644 --- a/snippets/csharp/System/Double/ToString/ToString7.cs +++ b/snippets/csharp/System/Double/ToString/ToString7.cs @@ -3,16 +3,16 @@ public class Example { - public static void Main() - { - float number = 1764.3789m; + public static void Main() + { + float number = 1764.3789f; - // Format as a currency value. - Console.WriteLine(number.ToString("C")); + // Format as a currency value. + Console.WriteLine(number.ToString("C")); - // Format as a numeric value with 3 decimal places. - Console.WriteLine(number.ToString("N3")); - } + // Format as a numeric value with 3 decimal places. + Console.WriteLine(number.ToString("N3")); + } } // The example displays the following output: // $1,764.38 diff --git a/snippets/csharp/System/Double/ToString/roundtripex1.cs b/snippets/csharp/System/Double/ToString/roundtripex1.cs index d8394400f00..5e25a886268 100644 --- a/snippets/csharp/System/Double/ToString/roundtripex1.cs +++ b/snippets/csharp/System/Double/ToString/roundtripex1.cs @@ -4,33 +4,31 @@ public class Example { - static void Main(string[] args) - { - // - Console.WriteLine("Attempting to round-trip a Double with 'R':"); - double initialValue = 0.6822871999174; - string valueString = initialValue.ToString("R", - CultureInfo.InvariantCulture); - double roundTripped = double.Parse(valueString, - CultureInfo.InvariantCulture); - Console.WriteLine("{0:R} = {1:R}: {2}\n", - initialValue, roundTripped, initialValue.Equals(roundTripped)); - - Console.WriteLine("Attempting to round-trip a Double with 'G17':"); - string valueString17 = initialValue.ToString("G17", + static void Main(string[] args) + { + // + Console.WriteLine("Attempting to round-trip a Double with 'R':"); + double initialValue = 0.6822871999174; + string valueString = initialValue.ToString("R", CultureInfo.InvariantCulture); - double roundTripped17 = double.Parse(valueString17, + double roundTripped = double.Parse(valueString, CultureInfo.InvariantCulture); - Console.WriteLine("{0:R} = {1:R}: {2}\n", - initialValue, roundTripped17, initialValue.Equals(roundTripped17)); - // If compiled to an application that targets anycpu or x64 and run on an x64 system, - // the example displays the following output: - // Attempting to round-trip a Double with 'R': - // 0.6822871999174 = 0.68228719991740006: False - // - // Attempting to round-trip a Double with 'G17': - // 0.6822871999174 = 0.6822871999174: True - // - } + Console.WriteLine($"{initialValue:R} = {roundTripped:R}: {initialValue.Equals(roundTripped)}\n"); + + Console.WriteLine("Attempting to round-trip a Double with 'G17':"); + string valueString17 = initialValue.ToString("G17", + CultureInfo.InvariantCulture); + double roundTripped17 = double.Parse(valueString17, + CultureInfo.InvariantCulture); + Console.WriteLine($"{initialValue:R} = {roundTripped17:R}: {initialValue.Equals(roundTripped17)}\n"); + // If compiled to an application that targets anycpu or x64 and run on an x64 system, + // the example displays the following output: + // Attempting to round-trip a Double with 'R': + // 0.6822871999174 = 0.68228719991740006: False + // + // Attempting to round-trip a Double with 'G17': + // 0.6822871999174 = 0.6822871999174: True + // + } } // diff --git a/snippets/csharp/System/Double/ToString/roundtripex2.cs b/snippets/csharp/System/Double/ToString/roundtripex2.cs index a5e21c4fa63..a4d301c4089 100644 --- a/snippets/csharp/System/Double/ToString/roundtripex2.cs +++ b/snippets/csharp/System/Double/ToString/roundtripex2.cs @@ -3,21 +3,19 @@ public class Example { - static void Main(string[] args) - { - Console.WriteLine("Attempting to round-trip a Double with 'R':"); - double initialValue = 0.6822871999174; - string valueString = initialValue.ToString("R"); - double roundTripped = double.Parse(valueString); - Console.WriteLine("{0:R} = {1:R}: {2}\n", - initialValue, roundTripped, initialValue.Equals(roundTripped)); + static void Main(string[] args) + { + Console.WriteLine("Attempting to round-trip a Double with 'R':"); + double initialValue = 0.6822871999174; + string valueString = initialValue.ToString("R"); + double roundTripped = double.Parse(valueString); + Console.WriteLine($"{initialValue:R} = {roundTripped:R}: {initialValue.Equals(roundTripped)}\n"); - Console.WriteLine("Attempting to round-trip a Double with 'G17':"); - string valueString17 = initialValue.ToString("G17"); - double roundTripped17 = double.Parse(valueString17); - Console.WriteLine("{0:R} = {1:R}: {2}\n", - initialValue, roundTripped17, initialValue.Equals(roundTripped17)); - } + Console.WriteLine("Attempting to round-trip a Double with 'G17':"); + string valueString17 = initialValue.ToString("G17"); + double roundTripped17 = double.Parse(valueString17); + Console.WriteLine($"{initialValue:R} = {roundTripped17:R}: {initialValue.Equals(roundTripped17)}\n"); + } } // If compiled to an application that targets anycpu or x64 and run on an x64 system, // the example displays the following output: diff --git a/snippets/csharp/System/Double/TryParse/TryParse1.cs b/snippets/csharp/System/Double/TryParse/TryParse1.cs index c667f92bde6..27491d7a006 100644 --- a/snippets/csharp/System/Double/TryParse/TryParse1.cs +++ b/snippets/csharp/System/Double/TryParse/TryParse1.cs @@ -3,99 +3,99 @@ public class Class1 { - public static void Main() - { - DefaultTryParse(); - Console.WriteLine("----------"); - TryParseWithConstraints(); - } + public static void Main() + { + DefaultTryParse(); + Console.WriteLine("----------"); + TryParseWithConstraints(); + } - private static void DefaultTryParse() - { - string value; - double number; + private static void DefaultTryParse() + { + string value; + double number; - // Parse a floating-point value with a thousands separator. - value = "1,643.57"; - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a thousands separator. + value = "1,643.57"; + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a floating-point value with a currency symbol and a - // thousands separator. - value = "$1,643.57"; - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse a floating-point value with a currency symbol and a + // thousands separator. + value = "$1,643.57"; + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse value in exponential notation. - value = "-1.643e6"; - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); + // Parse value in exponential notation. + value = "-1.643e6"; + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); - // Parse a negative integer value. - value = "-168934617882109132"; - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("Unable to parse '{0}'.", value); - // The example displays the following output to the console: - // 1643.57 - // Unable to parse '$1,643.57'. - // -1643000 - // -1.68934617882109E+17 - } + // Parse a negative integer value. + value = "-168934617882109132"; + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"Unable to parse '{value}'."); + // The example displays the following output to the console: + // 1643.57 + // Unable to parse '$1,643.57'. + // -1643000 + // -1.68934617882109E+17 + } - private static void TryParseWithConstraints() - { - // - string value; - NumberStyles style; - CultureInfo culture; - double number; + private static void TryParseWithConstraints() + { + // + string value; + NumberStyles style; + CultureInfo culture; + double number; - // Parse currency value using en-GB culture. - value = "£1,097.63"; - style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; - culture = CultureInfo.CreateSpecificCulture("en-GB"); - if (Double.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '£1,097.63' to 1097.63. + // Parse currency value using en-GB culture. + value = "£1,097.63"; + style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; + culture = CultureInfo.CreateSpecificCulture("en-GB"); + if (double.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '£1,097.63' to 1097.63. - value = "1345,978"; - style = NumberStyles.AllowDecimalPoint; - culture = CultureInfo.CreateSpecificCulture("fr-FR"); - if (Double.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '1345,978' to 1345.978. + value = "1345,978"; + style = NumberStyles.AllowDecimalPoint; + culture = CultureInfo.CreateSpecificCulture("fr-FR"); + if (double.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '1345,978' to 1345.978. - value = "1.345,978"; - style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; - culture = CultureInfo.CreateSpecificCulture("es-ES"); - if (Double.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Converted '1.345,978' to 1345.978. + value = "1.345,978"; + style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands; + culture = CultureInfo.CreateSpecificCulture("es-ES"); + if (double.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Converted '1.345,978' to 1345.978. - value = "1 345,978"; - if (Double.TryParse(value, style, culture, out number)) - Console.WriteLine("Converted '{0}' to {1}.", value, number); - else - Console.WriteLine("Unable to convert '{0}'.", value); - // Displays: - // Unable to convert '1 345,978'. - // - } + value = "1 345,978"; + if (double.TryParse(value, style, culture, out number)) + Console.WriteLine($"Converted '{value}' to {number}."); + else + Console.WriteLine($"Unable to convert '{value}'."); + // Displays: + // Unable to convert '1 345,978'. + // + } } diff --git a/snippets/csharp/System/Double/TryParse/tryparse1a.cs b/snippets/csharp/System/Double/TryParse/tryparse1a.cs index 70e56228153..4ffd3843a1e 100644 --- a/snippets/csharp/System/Double/TryParse/tryparse1a.cs +++ b/snippets/csharp/System/Double/TryParse/tryparse1a.cs @@ -3,20 +3,21 @@ public class Example { - public static void Main() - { - string[] values = { "1,643.57", "$1,643.57", "-1.643e6", + public static void Main() + { + string[] values = { "1,643.57", "$1,643.57", "-1.643e6", "-168934617882109132", "123AE6", - null, String.Empty, "ABCDEF" }; - double number; + null, string.Empty, "ABCDEF" }; + double number; - foreach (var value in values) { - if (Double.TryParse(value, out number)) - Console.WriteLine("'{0}' --> {1}", value, number); - else - Console.WriteLine("Unable to parse '{0}'.", value); - } - } + foreach (string value in values) + { + if (double.TryParse(value, out number)) + Console.WriteLine($"'{value}' --> {number}"); + else + Console.WriteLine($"Unable to parse '{value}'."); + } + } } // The example displays the following output: // '1,643.57' --> 1643.57 diff --git a/snippets/csharp/System/Double/TryParse/tryparse2.cs b/snippets/csharp/System/Double/TryParse/tryparse2.cs index d396248c544..59577aa1677 100644 --- a/snippets/csharp/System/Double/TryParse/tryparse2.cs +++ b/snippets/csharp/System/Double/TryParse/tryparse2.cs @@ -3,25 +3,23 @@ public class Example { - public static void Main() - { - string value; - double number; + public static void Main() + { + string value; + double number; - value = Double.MinValue.ToString(); - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("{0} is outside the range of a Double.", - value); + value = double.MinValue.ToString(); + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"{value} is outside the range of a Double."); - value = Double.MaxValue.ToString(); - if (Double.TryParse(value, out number)) - Console.WriteLine(number); - else - Console.WriteLine("{0} is outside the range of a Double.", - value); - } + value = double.MaxValue.ToString(); + if (double.TryParse(value, out number)) + Console.WriteLine(number); + else + Console.WriteLine($"{value} is outside the range of a Double."); + } } // The example displays the following output: // -1.79769313486232E+308 is outside the range of the Double type.