From a01a296a0ae00c2515513152f820ee92586c07c1 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Thu, 13 Aug 2026 13:56:09 -0700
Subject: [PATCH 1/9] Modernize C# code snippets - System/S* (#12970)
---
.../csharp/System/SByte/MaxValue/MaxValue1.cs | 65 ++-
snippets/csharp/System/SByte/Parse/Program.cs | 4 +
.../csharp/System/SByte/Parse/Project.csproj | 6 +
snippets/csharp/System/SByte/Parse/parse_1.cs | 135 +++---
.../csharp/System/SByte/Parse/parseex1.cs | 72 +--
.../csharp/System/SByte/Parse/parseex2.cs | 87 ++--
.../csharp/System/SByte/Parse/parseex3.cs | 56 +--
.../csharp/System/SByte/ToString/Program.cs | 4 +
.../System/SByte/ToString/Project.csproj | 6 +
.../csharp/System/SByte/ToString/tostring2.cs | 28 +-
.../csharp/System/SByte/ToString/tostring3.cs | 44 +-
.../csharp/System/SByte/ToString/tostring4.cs | 36 +-
.../csharp/System/SByte/ToString/tostring5.cs | 53 ++-
.../csharp/System/SByte/TryParse/TryParse1.cs | 54 +--
.../csharp/System/SByte/TryParse/tryparse2.cs | 94 ++--
.../System/Single/CompareTo/compareto2.cs | 22 +-
.../System/Single/CompareTo/compareto3.cs | 22 +-
.../System/Single/CompareTo/singlesample.cs | 95 ++--
.../Single/Epsilon/SingleEquals_25051.cs | 130 +++---
.../csharp/System/Single/Epsilon/epsilon.cs | 30 +-
.../csharp/System/Single/Epsilon/epsilon1.cs | 66 +--
.../csharp/System/Single/Equals/equalsabs1.cs | 66 +--
.../System/Single/Equals/equalsoverl.cs | 76 ++--
.../System/Single/MaxValue/maxvalueex.cs | 18 +-
.../System/Single/MinValue/minvalueex.cs | 18 +-
snippets/csharp/System/Single/NaN/Program.cs | 2 +
.../csharp/System/Single/NaN/Project.csproj | 6 +
snippets/csharp/System/Single/NaN/nan1.cs | 55 ++-
.../csharp/System/Single/NaN/single.nan4.cs | 38 +-
.../System/Single/Overview/comparison1.cs | 14 +-
.../System/Single/Overview/comparison2.cs | 4 +-
.../System/Single/Overview/comparison4.cs | 6 +-
.../csharp/System/Single/Overview/convert1.cs | 20 +-
.../csharp/System/Single/Overview/convert2.cs | 20 +-
.../System/Single/Overview/exceptional2.cs | 10 +-
.../System/Single/Overview/precisionlist1.cs | 8 +-
.../System/Single/Overview/precisionlist3.cs | 8 +-
.../System/Single/Overview/representation1.cs | 8 +-
.../System/Single/Overview/representation2.cs | 4 +-
.../csharp/System/Single/Parse/Program.cs | 3 +
.../csharp/System/Single/Parse/Project.csproj | 6 +
snippets/csharp/System/Single/Parse/parse1.cs | 45 +-
snippets/csharp/System/Single/Parse/parse2.cs | 106 +++--
snippets/csharp/System/Single/Parse/parse3.cs | 77 ++--
.../System/Single/ToString/ToString1.cs | 409 +++++++++---------
.../System/Single/ToString/ToString7.cs | 20 +-
.../System/Single/TryParse/tryparse1.cs | 172 ++++----
.../csharp/System/Span.Enumerator/Program.cs | 8 +-
.../csharp/System/Span.Enumerator/Program2.cs | 4 +-
.../csharp/System/Span/Overview/program.cs | 12 +-
snippets/csharp/System/Span/Slice/Program.cs | 4 +-
snippets/csharp/System/Span/Slice/Program2.cs | 2 +-
.../Overview/example1a.cs | 40 +-
53 files changed, 1213 insertions(+), 1185 deletions(-)
create mode 100644 snippets/csharp/System/SByte/Parse/Program.cs
create mode 100644 snippets/csharp/System/SByte/Parse/Project.csproj
create mode 100644 snippets/csharp/System/SByte/ToString/Program.cs
create mode 100644 snippets/csharp/System/SByte/ToString/Project.csproj
create mode 100644 snippets/csharp/System/Single/NaN/Program.cs
create mode 100644 snippets/csharp/System/Single/NaN/Project.csproj
create mode 100644 snippets/csharp/System/Single/Parse/Program.cs
create mode 100644 snippets/csharp/System/Single/Parse/Project.csproj
diff --git a/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs b/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs
index ddf3b1c4b76..4070fb14c4a 100644
--- a/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs
+++ b/snippets/csharp/System/SByte/MaxValue/MaxValue1.cs
@@ -2,39 +2,36 @@
public class SByteRangeExample
{
- public static void Main()
- {
- //
- long longValue = -130;
- sbyte byteValue;
-
- if (longValue <= sbyte.MaxValue &&
- longValue >= sbyte.MinValue)
- {
- byteValue = (sbyte) longValue;
- Console.WriteLine("Converted long integer value to {0}.", byteValue);
- }
- else
- {
- sbyte rangeLimit;
- string relationship;
-
- if (longValue > sbyte.MaxValue)
- {
- rangeLimit = sbyte.MaxValue;
- relationship = "greater";
- }
- else
- {
- rangeLimit = sbyte.MinValue;
- relationship = "less";
- }
+ public static void Main()
+ {
+ //
+ long longValue = -130;
+ sbyte byteValue;
- Console.WriteLine("Conversion failure: {0:n0} is {1} than {2}.",
- longValue,
- relationship,
- rangeLimit);
- }
- //
- }
+ if (longValue <= sbyte.MaxValue &&
+ longValue >= sbyte.MinValue)
+ {
+ byteValue = (sbyte)longValue;
+ Console.WriteLine($"Converted long integer value to {byteValue}.");
+ }
+ else
+ {
+ sbyte rangeLimit;
+ string relationship;
+
+ if (longValue > sbyte.MaxValue)
+ {
+ rangeLimit = sbyte.MaxValue;
+ relationship = "greater";
+ }
+ else
+ {
+ rangeLimit = sbyte.MinValue;
+ relationship = "less";
+ }
+
+ Console.WriteLine($"Conversion failure: {longValue:n0} is {relationship} than {rangeLimit}.");
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System/SByte/Parse/Program.cs b/snippets/csharp/System/SByte/Parse/Program.cs
new file mode 100644
index 00000000000..ddcbf34259a
--- /dev/null
+++ b/snippets/csharp/System/SByte/Parse/Program.cs
@@ -0,0 +1,4 @@
+SByteParseDefaultExample.Run();
+SByteParseStylesExample.Run();
+SByteConversion.Run();
+SByteParseProviderExample.Run();
diff --git a/snippets/csharp/System/SByte/Parse/Project.csproj b/snippets/csharp/System/SByte/Parse/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/SByte/Parse/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/SByte/Parse/parse_1.cs b/snippets/csharp/System/SByte/Parse/parse_1.cs
index 270d3a5c0cb..2b0b413595d 100644
--- a/snippets/csharp/System/SByte/Parse/parse_1.cs
+++ b/snippets/csharp/System/SByte/Parse/parse_1.cs
@@ -4,77 +4,74 @@
public class SByteConversion
{
- NumberFormatInfo provider = NumberFormatInfo.CurrentInfo;
+ NumberFormatInfo provider = NumberFormatInfo.CurrentInfo;
- public static void Main()
- {
- string stringValue;
- NumberStyles style;
+ public static void Run()
+ {
+ string stringValue;
+ NumberStyles style;
- stringValue = " 123 ";
- style = NumberStyles.None;
- CallParseOperation(stringValue, style);
-
- stringValue = "000,000,123";
- style = NumberStyles.Integer | NumberStyles.AllowThousands;
- CallParseOperation(stringValue, style);
-
- stringValue = "-100";
- style = NumberStyles.AllowLeadingSign;
- CallParseOperation(stringValue, style);
-
- stringValue = "100-";
- style = NumberStyles.AllowLeadingSign;
- CallParseOperation(stringValue, style);
-
- stringValue = "100-";
- style = NumberStyles.AllowTrailingSign;
- CallParseOperation(stringValue, style);
-
- stringValue = "$100";
- style = NumberStyles.AllowCurrencySymbol;
- CallParseOperation(stringValue, style);
-
- style = NumberStyles.Integer;
- CallParseOperation(stringValue, style);
-
- style = NumberStyles.AllowDecimalPoint;
- CallParseOperation("100.0", style);
-
- stringValue = "1e02";
- style = NumberStyles.AllowExponent;
- CallParseOperation(stringValue, style);
-
- stringValue = "(100)";
- style = NumberStyles.AllowParentheses;
- CallParseOperation(stringValue, style);
- }
-
- private static void CallParseOperation(string stringValue,
- NumberStyles style)
- {
- sbyte number;
-
- if (stringValue == null)
- Console.WriteLine("Cannot parse a null string...");
-
- try
- {
- number = sbyte.Parse(stringValue, style);
- Console.WriteLine("SByte.Parse('{0}', {1})) = {2}",
- stringValue, style, number);
- }
- catch (FormatException)
- {
- Console.WriteLine("'{0}' and {1} throw a FormatException",
- stringValue, style);
- }
- catch (OverflowException)
- {
- Console.WriteLine("'{0}' is outside the range of a signed byte",
- stringValue);
- }
- }
+ stringValue = " 123 ";
+ style = NumberStyles.None;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "000,000,123";
+ style = NumberStyles.Integer | NumberStyles.AllowThousands;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "-100";
+ style = NumberStyles.AllowLeadingSign;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "100-";
+ style = NumberStyles.AllowLeadingSign;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "100-";
+ style = NumberStyles.AllowTrailingSign;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "$100";
+ style = NumberStyles.AllowCurrencySymbol;
+ CallParseOperation(stringValue, style);
+
+ style = NumberStyles.Integer;
+ CallParseOperation(stringValue, style);
+
+ style = NumberStyles.AllowDecimalPoint;
+ CallParseOperation("100.0", style);
+
+ stringValue = "1e02";
+ style = NumberStyles.AllowExponent;
+ CallParseOperation(stringValue, style);
+
+ stringValue = "(100)";
+ style = NumberStyles.AllowParentheses;
+ CallParseOperation(stringValue, style);
+ }
+
+ private static void CallParseOperation(string stringValue,
+ NumberStyles style)
+ {
+ sbyte number;
+
+ if (stringValue == null)
+ Console.WriteLine("Cannot parse a null string...");
+
+ try
+ {
+ number = sbyte.Parse(stringValue, style);
+ Console.WriteLine($"SByte.Parse('{stringValue}', {style}) = {number}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{stringValue}' and {style} throw a FormatException");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{stringValue}' is outside the range of a signed byte");
+ }
+ }
}
// The example displays the following information to the console:
// ' 123 ' and None throw a FormatException
diff --git a/snippets/csharp/System/SByte/Parse/parseex1.cs b/snippets/csharp/System/SByte/Parse/parseex1.cs
index 7ea26bee91c..b06f1e0d1de 100644
--- a/snippets/csharp/System/SByte/Parse/parseex1.cs
+++ b/snippets/csharp/System/SByte/Parse/parseex1.cs
@@ -1,40 +1,40 @@
using System;
-public class Example
+public class SByteParseDefaultExample
{
- public static void Main()
- {
- //
- // Define an array of numeric strings.
- string[] values = { "-16", " -3", "+ 12", " +12 ", " 12 ",
- "+120", "(103)", "192", "-160" };
-
- // Parse each string and display the result.
- foreach (string value in values)
- {
- try {
- Console.WriteLine("Converted '{0}' to the SByte value {1}.",
- value, SByte.Parse(value));
- }
- catch (FormatException) {
- Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.",
- value);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}' is out of range of the SByte type.",
- value);
- }
- }
- // The example displays the following output:
- // Converted '-16' to the SByte value -16.
- // Converted ' -3' to the SByte value -3.
- // '+ 12' cannot be parsed successfully by SByte type.
- // Converted ' +12 ' to the SByte value 12.
- // Converted ' 12 ' to the SByte value 12.
- // Converted '+120' to the SByte value 120.
- // '(103)' cannot be parsed successfully by SByte type.
- // '192' is out of range of the SByte type.
- // '-160' is out of range of the SByte type.
- //
- }
+ public static void Run()
+ {
+ //
+ // Define an array of numeric strings.
+ string[] values = ["-16", " -3", "+ 12", " +12 ", " 12 ",
+ "+120", "(103)", "192", "-160"];
+
+ // Parse each string and display the result.
+ foreach (string value in values)
+ {
+ try
+ {
+ Console.WriteLine($"Converted '{value}' to the SByte value {sbyte.Parse(value)}.");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{value}' cannot be parsed successfully by SByte type.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{value}' is out of range of the SByte type.");
+ }
+ }
+ // The example displays the following output:
+ // Converted '-16' to the SByte value -16.
+ // Converted ' -3' to the SByte value -3.
+ // '+ 12' cannot be parsed successfully by SByte type.
+ // Converted ' +12 ' to the SByte value 12.
+ // Converted ' 12 ' to the SByte value 12.
+ // Converted '+120' to the SByte value 120.
+ // '(103)' cannot be parsed successfully by SByte type.
+ // '192' is out of range of the SByte type.
+ // '-160' is out of range of the SByte type.
+ //
+ }
}
diff --git a/snippets/csharp/System/SByte/Parse/parseex2.cs b/snippets/csharp/System/SByte/Parse/parseex2.cs
index 180b56a6661..133f250ba97 100644
--- a/snippets/csharp/System/SByte/Parse/parseex2.cs
+++ b/snippets/csharp/System/SByte/Parse/parseex2.cs
@@ -2,55 +2,60 @@
using System;
using System.Globalization;
-public class Example
+public class SByteParseStylesExample
{
- public static void Main()
- {
- NumberStyles style;
- sbyte number;
+ public static void Run()
+ {
+ NumberStyles style;
+ sbyte number;
- // Parse value with no styles allowed.
- string[] values1 = { " 121 ", "121", "-121" };
- style = NumberStyles.None;
- Console.WriteLine("Styles: {0}", style.ToString());
- foreach (string value in values1)
- {
- try {
- number = SByte.Parse(value, style);
- Console.WriteLine(" Converted '{0}' to {1}.", value, number);
- }
- catch (FormatException) {
- Console.WriteLine(" Unable to parse '{0}'.", value);
- }
- }
- Console.WriteLine();
-
- // Parse value with trailing sign.
- style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
- string[] values2 = { " 103+", " 103 +", "+103", "(103)", " +103 " };
- Console.WriteLine("Styles: {0}", style.ToString());
- foreach (string value in values2)
- {
- try {
- number = SByte.Parse(value, style);
- Console.WriteLine(" Converted '{0}' to {1}.", value, number);
- }
- catch (FormatException) {
- Console.WriteLine(" Unable to parse '{0}'.", value);
- }
- catch (OverflowException) {
- Console.WriteLine(" '{0}' is out of range of the SByte type.", value);
- }
- }
- Console.WriteLine();
- }
+ // Parse value with no styles allowed.
+ string[] values1 = [" 121 ", "121", "-121"];
+ style = NumberStyles.None;
+ Console.WriteLine($"Styles: {style}");
+ foreach (string value in values1)
+ {
+ try
+ {
+ number = sbyte.Parse(value, style);
+ Console.WriteLine($" Converted '{value}' to {number}.");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($" Unable to parse '{value}'.");
+ }
+ }
+ Console.WriteLine();
+
+ // Parse value with trailing sign.
+ style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
+ string[] values2 = [" 103+", " 103 +", "+103", "(103)", " +103 "];
+ Console.WriteLine($"Styles: {style}");
+ foreach (string value in values2)
+ {
+ try
+ {
+ number = sbyte.Parse(value, style);
+ Console.WriteLine($" Converted '{value}' to {number}.");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($" Unable to parse '{value}'.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($" '{value}' is out of range of the SByte type.");
+ }
+ }
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// Styles: None
// Unable to parse ' 121 '.
// Converted '121' to 121.
// Unable to parse '-121'.
-//
+//
// Styles: Integer, AllowTrailingSign
// Converted ' 103+' to 103.
// Converted ' 103 +' to 103.
diff --git a/snippets/csharp/System/SByte/Parse/parseex3.cs b/snippets/csharp/System/SByte/Parse/parseex3.cs
index bcf7c78017b..1111e07c903 100644
--- a/snippets/csharp/System/SByte/Parse/parseex3.cs
+++ b/snippets/csharp/System/SByte/Parse/parseex3.cs
@@ -2,34 +2,38 @@
using System;
using System.Globalization;
-public class Example
+public class SByteParseProviderExample
{
- public static void Main()
- {
- NumberFormatInfo nf = new NumberFormatInfo();
- nf.NegativeSign = "~";
-
- string[] values = { "-103", "+12", "~16", " 1", "~255" };
- IFormatProvider[] providers = { nf, CultureInfo.InvariantCulture };
-
- foreach (IFormatProvider provider in providers)
- {
- Console.WriteLine("Conversions using {0}:", ((object) provider).GetType().Name);
- foreach (string value in values)
- {
- try {
- Console.WriteLine(" Converted '{0}' to {1}.",
- value, SByte.Parse(value, provider));
- }
- catch (FormatException) {
- Console.WriteLine(" Unable to parse '{0}'.", value);
- }
- catch (OverflowException) {
- Console.WriteLine(" '{0}' is out of range of the SByte type.", value);
+ public static void Run()
+ {
+ NumberFormatInfo nf = new()
+ {
+ NegativeSign = "~"
+ };
+
+ string[] values = ["-103", "+12", "~16", " 1", "~255"];
+ IFormatProvider[] providers = [nf, CultureInfo.InvariantCulture];
+
+ foreach (IFormatProvider provider in providers)
+ {
+ Console.WriteLine($"Conversions using {((object)provider).GetType().Name}:");
+ foreach (string value in values)
+ {
+ try
+ {
+ Console.WriteLine($" Converted '{value}' to {sbyte.Parse(value, provider)}.");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($" Unable to parse '{value}'.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($" '{value}' is out of range of the SByte type.");
+ }
}
- }
- }
- }
+ }
+ }
}
// The example displays the following output:
// Conversions using NumberFormatInfo:
diff --git a/snippets/csharp/System/SByte/ToString/Program.cs b/snippets/csharp/System/SByte/ToString/Program.cs
new file mode 100644
index 00000000000..76bece4a57b
--- /dev/null
+++ b/snippets/csharp/System/SByte/ToString/Program.cs
@@ -0,0 +1,4 @@
+SByteToStringDefaultExample.Run();
+SByteToStringProviderExample.Run();
+SByteToStringFormatExample.Run();
+SByteToStringCultureExample.Run();
diff --git a/snippets/csharp/System/SByte/ToString/Project.csproj b/snippets/csharp/System/SByte/ToString/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/SByte/ToString/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/SByte/ToString/tostring2.cs b/snippets/csharp/System/SByte/ToString/tostring2.cs
index f42f7cb1e20..06d455317b5 100644
--- a/snippets/csharp/System/SByte/ToString/tostring2.cs
+++ b/snippets/csharp/System/SByte/ToString/tostring2.cs
@@ -1,20 +1,20 @@
//
using System;
-public class Example
+public class SByteToStringDefaultExample
{
- public static void Main()
- {
- sbyte value = -123;
- // Display value using default ToString method.
- Console.WriteLine(value.ToString()); // Displays -123
- // Display value using some standard format specifiers.
- Console.WriteLine(value.ToString("G")); // Displays -123
- Console.WriteLine(value.ToString("C")); // Displays ($-123.00)
- Console.WriteLine(value.ToString("D")); // Displays -123
- Console.WriteLine(value.ToString("F")); // Displays -123.00
- Console.WriteLine(value.ToString("N")); // Displays -123.00
- Console.WriteLine(value.ToString("X")); // Displays 85
- }
+ public static void Run()
+ {
+ sbyte value = -123;
+ // Display value using default ToString method.
+ Console.WriteLine(value.ToString()); // Displays -123
+ // Display value using some standard format specifiers.
+ Console.WriteLine(value.ToString("G")); // Displays -123
+ Console.WriteLine(value.ToString("C")); // Displays ($-123.00)
+ Console.WriteLine(value.ToString("D")); // Displays -123
+ Console.WriteLine(value.ToString("F")); // Displays -123.00
+ Console.WriteLine(value.ToString("N")); // Displays -123.00
+ Console.WriteLine(value.ToString("X")); // Displays 85
+ }
}
//
diff --git a/snippets/csharp/System/SByte/ToString/tostring3.cs b/snippets/csharp/System/SByte/ToString/tostring3.cs
index cb22ccd11f6..7a815890f84 100644
--- a/snippets/csharp/System/SByte/ToString/tostring3.cs
+++ b/snippets/csharp/System/SByte/ToString/tostring3.cs
@@ -2,36 +2,38 @@
using System;
using System.Globalization;
-public class Example
+public class SByteToStringProviderExample
{
- public static void Main()
- {
- // Define a custom NumberFormatInfo object with "~" as its negative sign.
- NumberFormatInfo nfi = new NumberFormatInfo();
- nfi.NegativeSign = "~";
-
- // Initialize an array of SByte values.
- sbyte[] bytes = { -122, 17, 124 };
+ public static void Run()
+ {
+ // Define a custom NumberFormatInfo object with "~" as its negative sign.
+ NumberFormatInfo nfi = new()
+ {
+ NegativeSign = "~"
+ };
- // Display the formatted result using the custom provider.
- Console.WriteLine("Using the custom NumberFormatInfo object:");
- foreach (sbyte value in bytes)
- Console.WriteLine(value.ToString(nfi));
+ // Initialize an array of SByte values.
+ sbyte[] bytes = [-122, 17, 124];
- Console.WriteLine();
-
- // Display the formatted result using the invariant culture.
- Console.WriteLine("Using the invariant culture:");
- foreach (sbyte value in bytes)
- Console.WriteLine(value.ToString(NumberFormatInfo.InvariantInfo));
- }
+ // Display the formatted result using the custom provider.
+ Console.WriteLine("Using the custom NumberFormatInfo object:");
+ foreach (sbyte value in bytes)
+ Console.WriteLine(value.ToString(nfi));
+
+ Console.WriteLine();
+
+ // Display the formatted result using the invariant culture.
+ Console.WriteLine("Using the invariant culture:");
+ foreach (sbyte value in bytes)
+ Console.WriteLine(value.ToString(NumberFormatInfo.InvariantInfo));
+ }
}
// The example displays the following output:
// Using the custom NumberFormatInfo object:
// ~122
// 17
// 124
-//
+//
// Using the invariant culture:
// -122
// 17
diff --git a/snippets/csharp/System/SByte/ToString/tostring4.cs b/snippets/csharp/System/SByte/ToString/tostring4.cs
index a6306b99045..92791063275 100644
--- a/snippets/csharp/System/SByte/ToString/tostring4.cs
+++ b/snippets/csharp/System/SByte/ToString/tostring4.cs
@@ -1,23 +1,23 @@
//
using System;
-using System.Globalization;
-public class Example
+
+public class SByteToStringFormatExample
{
- public static void Main()
- {
- sbyte[] values = { -124, 0, 118 };
- string[] specifiers = { "G", "C", "D3", "E2", "e3", "F",
- "N", "P", "X", "00.0", "#.0",
- "000;(0);**Zero**" };
-
- foreach (sbyte value in values)
- {
- foreach (string specifier in specifiers)
- Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
- Console.WriteLine();
- }
- }
+ public static void Run()
+ {
+ sbyte[] values = [-124, 0, 118];
+ string[] specifiers = ["G", "C", "D3", "E2", "e3", "F",
+ "N", "P", "X", "00.0", "#.0",
+ "000;(0);**Zero**"];
+
+ foreach (sbyte value in values)
+ {
+ foreach (string specifier in specifiers)
+ Console.WriteLine($"{specifier}: {value.ToString(specifier)}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// G: -124
@@ -32,7 +32,7 @@ public static void Main()
// 00.0: -124.0
// #.0: -124.0
// 000;(0);**Zero**: (124)
-//
+//
// G: 0
// C: $0.00
// D3: 000
@@ -45,7 +45,7 @@ public static void Main()
// 00.0: 00.0
// #.0: .0
// 000;(0);**Zero**: **Zero**
-//
+//
// G: 118
// C: $118.00
// D3: 118
diff --git a/snippets/csharp/System/SByte/ToString/tostring5.cs b/snippets/csharp/System/SByte/ToString/tostring5.cs
index 5f009ae9f53..cc55318e1ff 100644
--- a/snippets/csharp/System/SByte/ToString/tostring5.cs
+++ b/snippets/csharp/System/SByte/ToString/tostring5.cs
@@ -2,58 +2,55 @@
using System;
using System.Globalization;
-public class Example
+public class SByteToStringCultureExample
{
- public static void Main()
- {
- // Define cultures whose formatting conventions are to be used.
- CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
- CultureInfo.CreateSpecificCulture("fr-FR"),
- CultureInfo.CreateSpecificCulture("es-ES") };
- sbyte positiveNumber = 119;
- sbyte negativeNumber = -45;
- string[] specifiers = {"G", "C", "D4", "E2", "F", "N", "P", "X2"};
-
- foreach (string specifier in specifiers)
- {
- foreach (CultureInfo culture in cultures)
- Console.WriteLine("{0,2} format using {1} culture: {2, 16} {3, 16}",
- specifier, culture.Name,
- positiveNumber.ToString(specifier, culture),
- negativeNumber.ToString(specifier, culture));
- Console.WriteLine();
- }
- }
+ public static void Run()
+ {
+ // Define cultures whose formatting conventions are to be used.
+ CultureInfo[] cultures = [CultureInfo.CreateSpecificCulture("en-US"),
+ CultureInfo.CreateSpecificCulture("fr-FR"),
+ CultureInfo.CreateSpecificCulture("es-ES")];
+ sbyte positiveNumber = 119;
+ sbyte negativeNumber = -45;
+ string[] specifiers = ["G", "C", "D4", "E2", "F", "N", "P", "X2"];
+
+ foreach (string specifier in specifiers)
+ {
+ foreach (CultureInfo culture in cultures)
+ Console.WriteLine($"{specifier,2} format using {culture.Name} culture: {positiveNumber.ToString(specifier, culture),16} {negativeNumber.ToString(specifier, culture),16}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// G format using en-US culture: 119 -45
// G format using fr-FR culture: 119 -45
// G format using es-ES culture: 119 -45
-//
+//
// C format using en-US culture: $119.00 ($45.00)
// C format using fr-FR culture: 119,00 € -45,00 €
// C format using es-ES culture: 119,00 € -45,00 €
-//
+//
// D4 format using en-US culture: 0119 -0045
// D4 format using fr-FR culture: 0119 -0045
// D4 format using es-ES culture: 0119 -0045
-//
+//
// E2 format using en-US culture: 1.19E+002 -4.50E+001
// E2 format using fr-FR culture: 1,19E+002 -4,50E+001
// E2 format using es-ES culture: 1,19E+002 -4,50E+001
-//
+//
// F format using en-US culture: 119.00 -45.00
// F format using fr-FR culture: 119,00 -45,00
// F format using es-ES culture: 119,00 -45,00
-//
+//
// N format using en-US culture: 119.00 -45.00
// N format using fr-FR culture: 119,00 -45,00
// N format using es-ES culture: 119,00 -45,00
-//
+//
// P format using en-US culture: 11,900.00 % -4,500.00 %
// P format using fr-FR culture: 11 900,00 % -4 500,00 %
// P format using es-ES culture: 11.900,00 % -4.500,00 %
-//
+//
// X2 format using en-US culture: 77 D3
// X2 format using fr-FR culture: 77 D3
// X2 format using es-ES culture: 77 D3
diff --git a/snippets/csharp/System/SByte/TryParse/TryParse1.cs b/snippets/csharp/System/SByte/TryParse/TryParse1.cs
index 5b849932e1c..12bc0215ccd 100644
--- a/snippets/csharp/System/SByte/TryParse/TryParse1.cs
+++ b/snippets/csharp/System/SByte/TryParse/TryParse1.cs
@@ -2,31 +2,31 @@
public class ParseSByte
{
- public static void Main()
- {
- //
- string[] numericStrings = {"-3.6", "12.8", "+16.7", " 3 ", "(17)",
- "-17", "+12", "18-", "987", "1,024", " 127 "};
- sbyte number;
- foreach (string numericString in numericStrings)
- {
- if (sbyte.TryParse(numericString, out number))
- Console.WriteLine("Converted '{0}' to {1}.", numericString, number);
- else
- Console.WriteLine("Cannot convert '{0}' to an SByte.", numericString);
- }
- // The example displays the following output to the console:
- // Cannot convert '-3.6' to an SByte.
- // Cannot convert '12.8' to an SByte.
- // Cannot convert '+16.7' to an SByte.
- // Converted ' 3 ' to 3.
- // Cannot convert '(17)' to an SByte.
- // Converted '-17' to -17.
- // Converted '+12' to 12.
- // Cannot convert '18-' to an SByte.
- // Cannot convert '987' to an SByte.
- // Cannot convert '1,024' to an SByte.
- // Converted ' 127 ' to 127.
- //
- }
+ public static void Main()
+ {
+ //
+ string[] numericStrings = ["-3.6", "12.8", "+16.7", " 3 ", "(17)",
+ "-17", "+12", "18-", "987", "1,024", " 127 "];
+ sbyte number;
+ foreach (string numericString in numericStrings)
+ {
+ if (sbyte.TryParse(numericString, out number))
+ Console.WriteLine($"Converted '{numericString}' to {number}.");
+ else
+ Console.WriteLine($"Cannot convert '{numericString}' to an SByte.");
+ }
+ // The example displays the following output to the console:
+ // Cannot convert '-3.6' to an SByte.
+ // Cannot convert '12.8' to an SByte.
+ // Cannot convert '+16.7' to an SByte.
+ // Converted ' 3 ' to 3.
+ // Cannot convert '(17)' to an SByte.
+ // Converted '-17' to -17.
+ // Converted '+12' to 12.
+ // Cannot convert '18-' to an SByte.
+ // Cannot convert '987' to an SByte.
+ // Cannot convert '1,024' to an SByte.
+ // Converted ' 127 ' to 127.
+ //
+ }
}
diff --git a/snippets/csharp/System/SByte/TryParse/tryparse2.cs b/snippets/csharp/System/SByte/TryParse/tryparse2.cs
index 7c7e7867421..a7c235d4a1a 100644
--- a/snippets/csharp/System/SByte/TryParse/tryparse2.cs
+++ b/snippets/csharp/System/SByte/TryParse/tryparse2.cs
@@ -4,54 +4,54 @@
public class Example
{
- public static void Main()
- {
- string numericString;
- NumberStyles styles;
-
- numericString = "106";
- styles = NumberStyles.Integer;
- CallTryParse(numericString, styles);
-
- numericString = "-106";
- styles = NumberStyles.None;
- CallTryParse(numericString, styles);
-
- numericString = "103.00";
- styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
- CallTryParse(numericString, styles);
-
- numericString = "103.72";
- styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
- CallTryParse(numericString, styles);
+ public static void Main()
+ {
+ string numericString;
+ NumberStyles styles;
- numericString = "10E-01";
- styles = NumberStyles.Integer | NumberStyles.AllowExponent;
- CallTryParse(numericString, styles);
-
- numericString = "12E-01";
- CallTryParse(numericString, styles);
-
- numericString = "12E01";
- CallTryParse(numericString, styles);
-
- numericString = "C8";
- CallTryParse(numericString, NumberStyles.HexNumber);
-
- numericString = "0x8C";
- CallTryParse(numericString, NumberStyles.HexNumber);
- }
-
- private static void CallTryParse(string stringToConvert, NumberStyles styles)
- {
- sbyte number;
- bool result = SByte.TryParse(stringToConvert, styles,
- CultureInfo.InvariantCulture, out number);
- if (result)
- Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
- else
- Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
- }
+ numericString = "106";
+ styles = NumberStyles.Integer;
+ CallTryParse(numericString, styles);
+
+ numericString = "-106";
+ styles = NumberStyles.None;
+ CallTryParse(numericString, styles);
+
+ numericString = "103.00";
+ styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
+ CallTryParse(numericString, styles);
+
+ numericString = "103.72";
+ styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
+ CallTryParse(numericString, styles);
+
+ numericString = "10E-01";
+ styles = NumberStyles.Integer | NumberStyles.AllowExponent;
+ CallTryParse(numericString, styles);
+
+ numericString = "12E-01";
+ CallTryParse(numericString, styles);
+
+ numericString = "12E01";
+ CallTryParse(numericString, styles);
+
+ numericString = "C8";
+ CallTryParse(numericString, NumberStyles.HexNumber);
+
+ numericString = "0x8C";
+ CallTryParse(numericString, NumberStyles.HexNumber);
+ }
+
+ private static void CallTryParse(string stringToConvert, NumberStyles styles)
+ {
+ sbyte number;
+ bool result = sbyte.TryParse(stringToConvert, styles,
+ CultureInfo.InvariantCulture, out number);
+ if (result)
+ Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
+ else
+ Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
+ }
}
// The example displays the following output:
// Converted '106' to 106.
diff --git a/snippets/csharp/System/Single/CompareTo/compareto2.cs b/snippets/csharp/System/Single/CompareTo/compareto2.cs
index cdd6191ed77..1b6e27b4484 100644
--- a/snippets/csharp/System/Single/CompareTo/compareto2.cs
+++ b/snippets/csharp/System/Single/CompareTo/compareto2.cs
@@ -1,20 +1,20 @@
-//
+//
using System;
public class Example2
{
- public static void Main()
- {
- float value1 = 16.5457f;
- float operand = 3.8899982f;
- float value2 = value1 * operand / operand;
- Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}");
- Console.WriteLine();
- Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}");
- }
+ public static void Main()
+ {
+ float value1 = 16.5457f;
+ float operand = 3.8899982f;
+ float value2 = value1 * operand / operand;
+ Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}");
+ Console.WriteLine();
+ Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}");
+ }
}
// The example displays the following output:
// Comparing 16.5457 and 16.5457: -1
-//
+//
// Comparing 16.5457 and 16.545702: -1
//
diff --git a/snippets/csharp/System/Single/CompareTo/compareto3.cs b/snippets/csharp/System/Single/CompareTo/compareto3.cs
index 4d5b9b389fc..62892e15298 100644
--- a/snippets/csharp/System/Single/CompareTo/compareto3.cs
+++ b/snippets/csharp/System/Single/CompareTo/compareto3.cs
@@ -1,20 +1,20 @@
-//
+//
using System;
public class Example
{
- public static void Main()
- {
- float value1 = 16.5457f;
- float operand = 3.8899982f;
- object value2 = value1 * operand / operand;
- Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}");
- Console.WriteLine();
- Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}");
- }
+ public static void Main()
+ {
+ float value1 = 16.5457f;
+ float operand = 3.8899982f;
+ object value2 = value1 * operand / operand;
+ Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}");
+ Console.WriteLine();
+ Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}");
+ }
}
// The example displays the following output:
// Comparing 16.5457 and 16.5457: -1
-//
+//
// Comparing 16.5457 and 16.545702: -1
//
diff --git a/snippets/csharp/System/Single/CompareTo/singlesample.cs b/snippets/csharp/System/Single/CompareTo/singlesample.cs
index 590776253ac..16cd7f9a717 100644
--- a/snippets/csharp/System/Single/CompareTo/singlesample.cs
+++ b/snippets/csharp/System/Single/CompareTo/singlesample.cs
@@ -2,18 +2,19 @@
namespace SingleSnippet
{
- class SingleSample {
+ class SingleSample
+ {
public SingleSample()
{
- //
- Single s = 4.55F;
+ //
+ float s = 4.55F;
//
- //
- Console.WriteLine("A Single is of type {0}.", s.GetType().ToString());
+ //
+ Console.WriteLine($"A Single is of type {s.GetType()}.");
//
- //
+ //
bool done = false;
string inp;
do
@@ -22,8 +23,8 @@ public SingleSample()
inp = Console.ReadLine();
try
{
- s = Single.Parse(inp);
- Console.WriteLine("You entered {0}.", s.ToString());
+ s = float.Parse(inp);
+ Console.WriteLine($"You entered {s}.");
done = true;
}
catch (FormatException)
@@ -32,34 +33,34 @@ public SingleSample()
}
catch (Exception e)
{
- Console.WriteLine("An exception occurred while parsing your response: {0}", e.ToString());
+ Console.WriteLine($"An exception occurred while parsing your response: {e}");
}
} while (!done);
//
- //
- if (s > Single.MaxValue)
+ //
+ if (s > float.MaxValue)
{
Console.WriteLine("Your number is larger than a Single.");
}
//
- //
- if (s < Single.MinValue)
+ //
+ if (s < float.MinValue)
{
Console.WriteLine("Your number is smaller than a Single.");
}
//
- //
- Console.WriteLine("Epsilon, or the permittivity of a vacuum, has value {0}", Single.Epsilon.ToString());
+ //
+ Console.WriteLine($"Epsilon, or the permittivity of a vacuum, has value {float.Epsilon}");
//
- //
- Single zero = 0;
+ //
+ float zero = 0;
// This condition will return false.
- if ((0 / zero) == Single.NaN)
+ if ((0 / zero) == float.NaN)
{
Console.WriteLine("0 / 0 can be tested with Single.NaN.");
}
@@ -69,53 +70,53 @@ public SingleSample()
}
//
- //
+ //
// This will return true.
- if (Single.IsNaN(0 / zero))
+ if (float.IsNaN(0 / zero))
{
Console.WriteLine("Single.IsNan() can determine whether a value is not-a-number.");
}
//
- //
+ //
// This will equal Infinity.
- Console.WriteLine("10.0 minus NegativeInfinity equals {0}.", (10.0 - Single.NegativeInfinity).ToString());
+ Console.WriteLine($"10.0 minus NegativeInfinity equals {10.0 - float.NegativeInfinity}.");
//
- //
+ //
// This will equal Infinity.
- Console.WriteLine("PositiveInfinity plus 10.0 equals {0}.", (Single.PositiveInfinity + 10.0).ToString());
+ Console.WriteLine($"PositiveInfinity plus 10.0 equals {float.PositiveInfinity + 10.0}.");
//
- //
+ //
// This will return "true".
- Console.WriteLine("IsInfinity(3.0F / 0) == {0}.", Single.IsInfinity(3.0F / 0) ? "true" : "false");
+ Console.WriteLine($"IsInfinity(3.0F / 0) == {(float.IsInfinity(3.0F / 0) ? "true" : "false")}.");
//
- //
+ //
// This will return true.
- Console.WriteLine("IsPositiveInfinity(4.0F / 0) == {0}.", Single.IsPositiveInfinity(4.0F / 0) ? "true" : "false");
+ Console.WriteLine($"IsPositiveInfinity(4.0F / 0) == {(float.IsPositiveInfinity(4.0F / 0) ? "true" : "false")}.");
//
- //
+ //
// This will return true.
- Console.WriteLine("IsNegativeInfinity(-5.0F / 0) == {0}.", Single.IsNegativeInfinity(-5.0F / 0) ? "true" : "false");
+ Console.WriteLine($"IsNegativeInfinity(-5.0F / 0) == {(float.IsNegativeInfinity(-5.0F / 0) ? "true" : "false")}.");
//
//
- Single a;
+ float a;
a = 500;
- Object obj1;
+ object obj1;
//
- //
+ //
// The variables point to the same objects.
- Object obj2;
+ object obj2;
obj1 = a;
obj2 = obj1;
- if (Single.ReferenceEquals(obj1, obj2))
+ if (float.ReferenceEquals(obj1, obj2))
{
Console.WriteLine("The variables point to the same Single object.");
}
@@ -125,28 +126,29 @@ public SingleSample()
}
//
- //
- obj1 = (Single)450;
+ //
+ obj1 = (float)450;
if (a.CompareTo(obj1) < 0)
{
- Console.WriteLine("{0} is less than {1}.", a.ToString(), obj1.ToString());
+ Console.WriteLine($"{a} is less than {obj1}.");
}
if (a.CompareTo(obj1) > 0)
{
- Console.WriteLine("{0} is greater than {1}.", a.ToString(), obj1.ToString());
+ Console.WriteLine($"{a} is greater than {obj1}.");
}
if (a.CompareTo(obj1) == 0)
{
- Console.WriteLine("{0} equals {1}.", a.ToString(), obj1.ToString());
+ Console.WriteLine($"{a} equals {obj1}.");
}
//
- //
- obj1 = (Single)500;
- if (a.Equals(obj1)) {
+ //
+ obj1 = (float)500;
+ if (a.Equals(obj1))
+ {
Console.WriteLine("The value type and reference type values are equal.");
}
//
@@ -156,8 +158,5 @@ public SingleSample()
class EntryPoint
{
- static void Main(string[] args)
- {
- new SingleSnippet.SingleSample();
- }
-}
\ No newline at end of file
+ static void Main(string[] args) => new SingleSnippet.SingleSample();
+}
diff --git a/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs b/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs
index da27b7ae54c..af810b2453c 100644
--- a/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs
+++ b/snippets/csharp/System/Single/Epsilon/SingleEquals_25051.cs
@@ -2,73 +2,73 @@
public class Class1
{
- public static void Main()
- {
- CompareUsingEquals();
- Console.WriteLine();
- CompareApproximateValues();
- Console.WriteLine();
- CompareObjectsUsingEquals();
- Console.WriteLine();
- CompareApproximateObjectValues();
- Console.WriteLine();
- }
+ public static void Main()
+ {
+ CompareUsingEquals();
+ Console.WriteLine();
+ CompareApproximateValues();
+ Console.WriteLine();
+ CompareObjectsUsingEquals();
+ Console.WriteLine();
+ CompareApproximateObjectValues();
+ Console.WriteLine();
+ }
- private static void CompareUsingEquals()
- {
- //
- // Initialize two floats with apparently identical values
- float float1 = .33333f;
- float float2 = 1/3;
- // Compare them for equality
- Console.WriteLine(float1.Equals(float2)); // displays false
- //
- }
-
- private static void CompareApproximateValues()
- {
- //
- // Initialize two floats with apparently identical values
- float float1 = .33333f;
- float float2 = (float) 1/3;
- // Define the tolerance for variation in their values
- float difference = Math.Abs(float1 * .0001f);
+ private static void CompareUsingEquals()
+ {
+ //
+ // Initialize two floats with apparently identical values
+ float float1 = .33333f;
+ float float2 = 1 / 3;
+ // Compare them for equality
+ Console.WriteLine(float1.Equals(float2)); // displays false
+ //
+ }
- // Compare the values
- // The output to the console indicates that the two values are equal
- if (Math.Abs(float1 - float2) <= difference)
- Console.WriteLine("float1 and float2 are equal.");
- else
- Console.WriteLine("float1 and float2 are unequal.");
- //
- }
+ private static void CompareApproximateValues()
+ {
+ //
+ // Initialize two floats with apparently identical values
+ float float1 = .33333f;
+ float float2 = (float)1 / 3;
+ // Define the tolerance for variation in their values
+ float difference = Math.Abs(float1 * .0001f);
- private static void CompareObjectsUsingEquals()
- {
- //
- // Initialize two floats with apparently identical values
- float float1 = .33333f;
- object float2 = 1/3;
- // Compare them for equality
- Console.WriteLine(float1.Equals(float2)); // displays false
- //
- }
-
- private static void CompareApproximateObjectValues()
- {
- //
- // Initialize two floats with apparently identical values
- float float1 = .33333f;
- object float2 = (float) 1/3;
- // Define the tolerance for variation in their values
- float difference = Math.Abs(float1 * .0001f);
+ // Compare the values
+ // The output to the console indicates that the two values are equal
+ if (Math.Abs(float1 - float2) <= difference)
+ Console.WriteLine("float1 and float2 are equal.");
+ else
+ Console.WriteLine("float1 and float2 are unequal.");
+ //
+ }
- // Compare the values
- // The output to the console indicates that the two values are equal
- if (Math.Abs(float1 - (float) float2) <= difference)
- Console.WriteLine("float1 and float2 are equal.");
- else
- Console.WriteLine("float1 and float2 are unequal.");
- //
- }
+ private static void CompareObjectsUsingEquals()
+ {
+ //
+ // Initialize two floats with apparently identical values
+ float float1 = .33333f;
+ object float2 = 1 / 3;
+ // Compare them for equality
+ Console.WriteLine(float1.Equals(float2)); // displays false
+ //
+ }
+
+ private static void CompareApproximateObjectValues()
+ {
+ //
+ // Initialize two floats with apparently identical values
+ float float1 = .33333f;
+ object float2 = (float)1 / 3;
+ // Define the tolerance for variation in their values
+ float difference = Math.Abs(float1 * .0001f);
+
+ // Compare the values
+ // The output to the console indicates that the two values are equal
+ if (Math.Abs(float1 - (float)float2) <= difference)
+ Console.WriteLine("float1 and float2 are equal.");
+ else
+ Console.WriteLine("float1 and float2 are unequal.");
+ //
+ }
}
diff --git a/snippets/csharp/System/Single/Epsilon/epsilon.cs b/snippets/csharp/System/Single/Epsilon/epsilon.cs
index 2bf16f5c802..a5581e319f2 100644
--- a/snippets/csharp/System/Single/Epsilon/epsilon.cs
+++ b/snippets/csharp/System/Single/Epsilon/epsilon.cs
@@ -1,25 +1,25 @@
-//
+//
using System;
public class Example1
{
- public static void Main()
- {
- float[] values = { 0f, Single.Epsilon, Single.Epsilon * .5f };
-
- for (int ctr = 0; ctr <= values.Length - 2; ctr++)
- {
- for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++)
- {
- Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}");
- }
- Console.WriteLine();
- }
- }
+ public static void Main()
+ {
+ float[] values = [0f, float.Epsilon, float.Epsilon * .5f];
+
+ for (int ctr = 0; ctr <= values.Length - 2; ctr++)
+ {
+ for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++)
+ {
+ Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// 0 = 1.401298E-45: False
// 0 = 0: True
-//
+//
// 1.401298E-45 = 0: False
//
diff --git a/snippets/csharp/System/Single/Epsilon/epsilon1.cs b/snippets/csharp/System/Single/Epsilon/epsilon1.cs
index 87664989eac..d15e3769807 100644
--- a/snippets/csharp/System/Single/Epsilon/epsilon1.cs
+++ b/snippets/csharp/System/Single/Epsilon/epsilon1.cs
@@ -3,48 +3,48 @@
public class Example2
{
- public static void Main()
- {
- float[] values = { 0.0f, Single.Epsilon };
- foreach (var value in values) {
- Console.WriteLine(GetComponentParts(value));
- Console.WriteLine();
- }
- }
+ public static void Main()
+ {
+ float[] values = [0.0f, float.Epsilon];
+ foreach (float value in values)
+ {
+ Console.WriteLine(GetComponentParts(value));
+ Console.WriteLine();
+ }
+ }
- private static string GetComponentParts(float value)
- {
- string result = String.Format("{0:R}: ", value);
- int indent = result.Length;
+ private static string GetComponentParts(float value)
+ {
+ string result = $"{value:R}: ";
+ int indent = result.Length;
- // Convert the single to a 4-byte array.
- byte[] bytes = BitConverter.GetBytes(value);
- int formattedSingle = BitConverter.ToInt32(bytes, 0);
-
- // Get the sign bit (byte 3, bit 7).
- result += String.Format("Sign: {0}\n",
- (formattedSingle >> 31) != 0 ? "1 (-)" : "0 (+)");
+ // Convert the single to a 4-byte array.
+ byte[] bytes = BitConverter.GetBytes(value);
+ int formattedSingle = BitConverter.ToInt32(bytes, 0);
- // Get the exponent (byte 2 bit 7 to byte 3, bits 6)
- int exponent = (formattedSingle >> 23) & 0x000000FF;
- int adjustment = (exponent != 0) ? 127 : 126;
- result += String.Format("{0}Exponent: 0x{1:X4} ({1})\n", new String(' ', indent), exponent - adjustment);
+ // Get the sign bit (byte 3, bit 7).
+ result += $"Sign: {((formattedSingle >> 31) != 0 ? "1 (-)" : "0 (+)")}\n";
- // Get the significand (bits 0-22)
- long significand = exponent != 0 ?
- ((formattedSingle & 0x007FFFFF) | 0x800000) :
- (formattedSingle & 0x007FFFFF);
- result += String.Format("{0}Mantissa: 0x{1:X13}\n", new String(' ', indent), significand);
- return result;
- }
+ // Get the exponent (byte 2 bit 7 to byte 3, bits 6)
+ int exponent = (formattedSingle >> 23) & 0x000000FF;
+ int adjustment = (exponent != 0) ? 127 : 126;
+ result += string.Format("{0}Exponent: 0x{1:X4} ({1})\n", new string(' ', indent), exponent - adjustment);
+
+ // Get the significand (bits 0-22)
+ long significand = exponent != 0 ?
+ ((formattedSingle & 0x007FFFFF) | 0x800000) :
+ (formattedSingle & 0x007FFFFF);
+ result += $"{new string(' ', indent)}Mantissa: 0x{significand:X13}\n";
+ return result;
+ }
}
// // The example displays the following output:
// 0: Sign: 0 (+)
// Exponent: 0xFFFFFF82 (-126)
// Mantissa: 0x0000000000000
-//
-//
+//
+//
// 1.401298E-45: Sign: 0 (+)
// Exponent: 0xFFFFFF82 (-126)
// Mantissa: 0x0000000000001
-//
+//
diff --git a/snippets/csharp/System/Single/Equals/equalsabs1.cs b/snippets/csharp/System/Single/Equals/equalsabs1.cs
index 6aa1d68c28e..67e08171bac 100644
--- a/snippets/csharp/System/Single/Equals/equalsabs1.cs
+++ b/snippets/csharp/System/Single/Equals/equalsabs1.cs
@@ -1,43 +1,43 @@
-//
+//
using System;
public class Example
{
- public static void Main()
- {
- float value1 = .1f * 10f;
- float value2 = 0f;
- for (int ctr = 0; ctr < 10; ctr++)
- value2 += .1f;
-
- Console.WriteLine($"{value1:R} = {value2:R}: {HasMinimalDifference(value1, value2, 1)}");
- }
-
- public static bool HasMinimalDifference(float value1, float value2, int units)
- {
- byte[] bytes = BitConverter.GetBytes(value1);
- int iValue1 = BitConverter.ToInt32(bytes, 0);
-
- bytes = BitConverter.GetBytes(value2);
- int iValue2 = BitConverter.ToInt32(bytes, 0);
-
- // If the signs are different, return false except for +0 and -0.
- if ((iValue1 >> 31) != (iValue2 >> 31))
- {
- if (value1 == value2)
- return true;
-
- return false;
- }
+ public static void Main()
+ {
+ float value1 = .1f * 10f;
+ float value2 = 0f;
+ for (int ctr = 0; ctr < 10; ctr++)
+ value2 += .1f;
+
+ Console.WriteLine($"{value1:R} = {value2:R}: {HasMinimalDifference(value1, value2, 1)}");
+ }
+
+ public static bool HasMinimalDifference(float value1, float value2, int units)
+ {
+ byte[] bytes = BitConverter.GetBytes(value1);
+ int iValue1 = BitConverter.ToInt32(bytes, 0);
+
+ bytes = BitConverter.GetBytes(value2);
+ int iValue2 = BitConverter.ToInt32(bytes, 0);
- int diff = Math.Abs(iValue1 - iValue2);
+ // If the signs are different, return false except for +0 and -0.
+ if ((iValue1 >> 31) != (iValue2 >> 31))
+ {
+ if (value1 == value2)
+ return true;
- if (diff <= units)
- return true;
+ return false;
+ }
+
+ int diff = Math.Abs(iValue1 - iValue2);
+
+ if (diff <= units)
+ return true;
- return false;
- }
+ return false;
+ }
}
// The example displays the following output:
// 1 = 1.00000012: True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Single/Equals/equalsoverl.cs b/snippets/csharp/System/Single/Equals/equalsoverl.cs
index 33dd94b5851..d16ba1fa0d2 100644
--- a/snippets/csharp/System/Single/Equals/equalsoverl.cs
+++ b/snippets/csharp/System/Single/Equals/equalsoverl.cs
@@ -3,58 +3,52 @@
public class Example2
{
- static float value = 112;
+ static float value = 112;
- public static void Main()
- {
- byte byte1= 112;
- Console.WriteLine("value = byte1: {0,16}", value.Equals(byte1));
- TestObjectForEquality(byte1);
+ public static void Main()
+ {
+ byte byte1 = 112;
+ Console.WriteLine($"value = byte1: {value.Equals(byte1),16}");
+ TestObjectForEquality(byte1);
- short short1 = 112;
- Console.WriteLine("value = short1: {0,16}", value.Equals(short1));
- TestObjectForEquality(short1);
+ short short1 = 112;
+ Console.WriteLine($"value = short1: {value.Equals(short1),16}");
+ TestObjectForEquality(short1);
- int int1 = 112;
- Console.WriteLine("value = int1: {0,18}", value.Equals(int1));
- TestObjectForEquality(int1);
+ int int1 = 112;
+ Console.WriteLine($"value = int1: {value.Equals(int1),18}");
+ TestObjectForEquality(int1);
- long long1 = 112;
- Console.WriteLine("value = long1: {0,17}", value.Equals(long1));
- TestObjectForEquality(long1);
+ long long1 = 112;
+ Console.WriteLine($"value = long1: {value.Equals(long1),17}");
+ TestObjectForEquality(long1);
- sbyte sbyte1 = 112;
- Console.WriteLine("value = sbyte1: {0,16}", value.Equals(sbyte1));
- TestObjectForEquality(sbyte1);
+ sbyte sbyte1 = 112;
+ Console.WriteLine($"value = sbyte1: {value.Equals(sbyte1),16}");
+ TestObjectForEquality(sbyte1);
- ushort ushort1 = 112;
- Console.WriteLine("value = ushort1: {0,16}", value.Equals(ushort1));
- TestObjectForEquality(ushort1);
+ ushort ushort1 = 112;
+ Console.WriteLine($"value = ushort1: {value.Equals(ushort1),16}");
+ TestObjectForEquality(ushort1);
- uint uint1 = 112;
- Console.WriteLine("value = uint1: {0,18}", value.Equals(uint1));
- TestObjectForEquality(uint1);
+ uint uint1 = 112;
+ Console.WriteLine($"value = uint1: {value.Equals(uint1),18}");
+ TestObjectForEquality(uint1);
- ulong ulong1 = 112;
- Console.WriteLine("value = ulong1: {0,17}", value.Equals(ulong1));
- TestObjectForEquality(ulong1);
+ ulong ulong1 = 112;
+ Console.WriteLine($"value = ulong1: {value.Equals(ulong1),17}");
+ TestObjectForEquality(ulong1);
- decimal dec1 = 112m;
- Console.WriteLine("value = dec1: {0,21}", value.Equals(dec1));
- TestObjectForEquality(dec1);
+ decimal dec1 = 112m;
+ Console.WriteLine($"value = dec1: {value.Equals(dec1),21}");
+ TestObjectForEquality(dec1);
- double dbl1 = 112;
- Console.WriteLine("value = dbl1: {0,20}", value.Equals(dbl1));
- TestObjectForEquality(dbl1);
- }
+ double dbl1 = 112;
+ Console.WriteLine($"value = dbl1: {value.Equals(dbl1),20}");
+ TestObjectForEquality(dbl1);
+ }
- private static void TestObjectForEquality(Object obj)
- {
- Console.WriteLine("{0} ({1}) = {2} ({3}): {4}\n",
- value, value.GetType().Name,
- obj, obj.GetType().Name,
- value.Equals(obj));
- }
+ private static void TestObjectForEquality(object obj) => Console.WriteLine($"{value} ({value.GetType().Name}) = {obj} ({obj.GetType().Name}): {value.Equals(obj)}\n");
}
// The example displays the following output:
// value = byte1: True
diff --git a/snippets/csharp/System/Single/MaxValue/maxvalueex.cs b/snippets/csharp/System/Single/MaxValue/maxvalueex.cs
index e84e70b220d..aa87213e538 100644
--- a/snippets/csharp/System/Single/MaxValue/maxvalueex.cs
+++ b/snippets/csharp/System/Single/MaxValue/maxvalueex.cs
@@ -3,16 +3,14 @@
public class Example
{
- public static void Main()
- {
- float result1 = 1.867e38f + 2.385e38f;
- Console.WriteLine("{0} (Positive Infinity: {1})",
- result1, Single.IsPositiveInfinity(result1));
-
- float result2 = 1.5935e25f * 7.948e20f;
- Console.WriteLine("{0} (Positive Infinity: {1})",
- result2, Single.IsPositiveInfinity(result2));
- }
+ public static void Main()
+ {
+ float result1 = 1.867e38f + 2.385e38f;
+ Console.WriteLine($"{result1} (Positive Infinity: {float.IsPositiveInfinity(result1)})");
+
+ float result2 = 1.5935e25f * 7.948e20f;
+ Console.WriteLine($"{result2} (Positive Infinity: {float.IsPositiveInfinity(result2)})");
+ }
}
// The example displays the following output:
// Infinity (Positive Infinity: True)
diff --git a/snippets/csharp/System/Single/MinValue/minvalueex.cs b/snippets/csharp/System/Single/MinValue/minvalueex.cs
index 953c4ebbf79..24b4151ac66 100644
--- a/snippets/csharp/System/Single/MinValue/minvalueex.cs
+++ b/snippets/csharp/System/Single/MinValue/minvalueex.cs
@@ -3,16 +3,14 @@
public class Example
{
- public static void Main()
- {
- float result1 = -8.997e37f + -2.985e38f;
- Console.WriteLine("{0} (Negative Infinity: {1})",
- result1, Single.IsNegativeInfinity(result1));
-
- float result2 = -1.5935e25f * 7.948e32f;
- Console.WriteLine("{0} (Negative Infinity: {1})",
- result2, Single.IsNegativeInfinity(result2));
- }
+ public static void Main()
+ {
+ float result1 = -8.997e37f + -2.985e38f;
+ Console.WriteLine($"{result1} (Negative Infinity: {float.IsNegativeInfinity(result1)})");
+
+ float result2 = -1.5935e25f * 7.948e32f;
+ Console.WriteLine($"{result2} (Negative Infinity: {float.IsNegativeInfinity(result2)})");
+ }
}
// The example displays the following output:
// -Infinity (Negative Infinity: True)
diff --git a/snippets/csharp/System/Single/NaN/Program.cs b/snippets/csharp/System/Single/NaN/Program.cs
new file mode 100644
index 00000000000..67609d649bf
--- /dev/null
+++ b/snippets/csharp/System/Single/NaN/Program.cs
@@ -0,0 +1,2 @@
+SingleNaNOperationsExample.Run();
+SingleNaNComparisonExample.Run();
diff --git a/snippets/csharp/System/Single/NaN/Project.csproj b/snippets/csharp/System/Single/NaN/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Single/NaN/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Single/NaN/nan1.cs b/snippets/csharp/System/Single/NaN/nan1.cs
index c7af3af5178..d6abc4bf6d7 100644
--- a/snippets/csharp/System/Single/NaN/nan1.cs
+++ b/snippets/csharp/System/Single/NaN/nan1.cs
@@ -1,33 +1,32 @@
using System;
-public class Example
+public class SingleNaNOperationsExample
{
- public static void Main()
- {
- //
- float zero = 0.0f;
- Console.WriteLine("{0} / {1} = {2}", zero, zero, zero/zero);
- // The example displays the following output:
- // 0 / 0 = NaN
- //
+ public static void Run()
+ {
+ //
+ float zero = 0.0f;
+ Console.WriteLine($"{zero} / {zero} = {zero / zero}");
+ // The example displays the following output:
+ // 0 / 0 = NaN
+ //
- //
- float nan1 = Single.NaN;
-
- Console.WriteLine("{0} + {1} = {2}", 3, nan1, 3 + nan1);
- Console.WriteLine("Abs({0}) = {1}", nan1, Math.Abs(nan1));
- // The example displays the following output:
- // 3 + NaN = NaN
- // Abs(NaN) = NaN
- //
- Console.WriteLine();
-
- //
- float result = Single.NaN;
- Console.WriteLine("{0} = Single.NaN: {1}",
- result, result == Single.NaN);
- // The example displays the following output:
- // NaN = Single.Nan: False
- //
- }
+ //
+ float nan1 = float.NaN;
+
+ Console.WriteLine($"{3} + {nan1} = {3 + nan1}");
+ Console.WriteLine($"Abs({nan1}) = {Math.Abs(nan1)}");
+ // The example displays the following output:
+ // 3 + NaN = NaN
+ // Abs(NaN) = NaN
+ //
+ Console.WriteLine();
+
+ //
+ float result = float.NaN;
+ Console.WriteLine($"{result} = Single.NaN: {result == float.NaN}");
+ // The example displays the following output:
+ // NaN = Single.Nan: False
+ //
+ }
}
diff --git a/snippets/csharp/System/Single/NaN/single.nan4.cs b/snippets/csharp/System/Single/NaN/single.nan4.cs
index bf6ec01d851..ad96ed834b4 100644
--- a/snippets/csharp/System/Single/NaN/single.nan4.cs
+++ b/snippets/csharp/System/Single/NaN/single.nan4.cs
@@ -1,26 +1,26 @@
//
using System;
-public class Example
+public class SingleNaNComparisonExample
{
- public static void Main()
- {
- Console.WriteLine("NaN == NaN: {0}", Single.NaN == Single.NaN);
- Console.WriteLine("NaN != NaN: {0}", Single.NaN != Single.NaN);
- Console.WriteLine("NaN.Equals(NaN): {0}", Single.NaN.Equals(Single.NaN));
- Console.WriteLine("! NaN.Equals(NaN): {0}", ! Single.NaN.Equals(Single.NaN));
- Console.WriteLine("IsNaN: {0}", Double.IsNaN(Double.NaN));
-
- Console.WriteLine("\nNaN > NaN: {0}", Single.NaN > Single.NaN);
- Console.WriteLine("NaN >= NaN: {0}", Single.NaN >= Single.NaN);
- Console.WriteLine("NaN < NaN: {0}", Single.NaN < Single.NaN);
- Console.WriteLine("NaN < 100.0: {0}", Single.NaN < 100.0f);
- Console.WriteLine("NaN <= 100.0: {0}", Single.NaN <= 100.0f);
- Console.WriteLine("NaN >= 100.0: {0}", Single.NaN > 100.0f);
- Console.WriteLine("NaN.CompareTo(NaN): {0}", Single.NaN.CompareTo(Single.NaN));
- Console.WriteLine("NaN.CompareTo(100.0): {0}", Single.NaN.CompareTo(100.0f));
- Console.WriteLine("(100.0).CompareTo(Single.NaN): {0}", (100.0f).CompareTo(Single.NaN));
- }
+ public static void Run()
+ {
+ Console.WriteLine($"NaN == NaN: {float.NaN == float.NaN}");
+ Console.WriteLine($"NaN != NaN: {float.NaN != float.NaN}");
+ Console.WriteLine($"NaN.Equals(NaN): {float.NaN.Equals(float.NaN)}");
+ Console.WriteLine($"! NaN.Equals(NaN): {!float.NaN.Equals(float.NaN)}");
+ Console.WriteLine($"IsNaN: {double.IsNaN(double.NaN)}");
+
+ Console.WriteLine($"\nNaN > NaN: {float.NaN > float.NaN}");
+ Console.WriteLine($"NaN >= NaN: {float.NaN >= float.NaN}");
+ Console.WriteLine($"NaN < NaN: {float.NaN < float.NaN}");
+ Console.WriteLine($"NaN < 100.0: {float.NaN < 100.0f}");
+ Console.WriteLine($"NaN <= 100.0: {float.NaN <= 100.0f}");
+ Console.WriteLine($"NaN > 100.0: {float.NaN > 100.0f}");
+ Console.WriteLine($"NaN.CompareTo(NaN): {float.NaN.CompareTo(float.NaN)}");
+ Console.WriteLine($"NaN.CompareTo(100.0): {float.NaN.CompareTo(100.0f)}");
+ Console.WriteLine($"(100.0).CompareTo(Single.NaN): {(100.0f).CompareTo(float.NaN)}");
+ }
}
// The example displays the following output:
// NaN == NaN: False
diff --git a/snippets/csharp/System/Single/Overview/comparison1.cs b/snippets/csharp/System/Single/Overview/comparison1.cs
index 965c922e4f9..0d1eb7f0e2c 100644
--- a/snippets/csharp/System/Single/Overview/comparison1.cs
+++ b/snippets/csharp/System/Single/Overview/comparison1.cs
@@ -1,14 +1,14 @@
-//
+//
using System;
public class Example
{
- public static void Main()
- {
- float value1 = .3333333f;
- float value2 = 1.0f/3;
- Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}");
- }
+ public static void Main()
+ {
+ float value1 = .3333333f;
+ float value2 = 1.0f / 3;
+ Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}");
+ }
}
// The example displays the following output:
// 0.3333333 = 0.333333343: False
diff --git a/snippets/csharp/System/Single/Overview/comparison2.cs b/snippets/csharp/System/Single/Overview/comparison2.cs
index c18df56a7fa..400c11c3e1f 100644
--- a/snippets/csharp/System/Single/Overview/comparison2.cs
+++ b/snippets/csharp/System/Single/Overview/comparison2.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example1
{
@@ -13,7 +13,7 @@ public static void Main()
// The example displays the following output on modern .NET:
// 10.201438 = 10.201439: False
-
+
//
}
}
diff --git a/snippets/csharp/System/Single/Overview/comparison4.cs b/snippets/csharp/System/Single/Overview/comparison4.cs
index ded666dc514..4ef3e6cd562 100644
--- a/snippets/csharp/System/Single/Overview/comparison4.cs
+++ b/snippets/csharp/System/Single/Overview/comparison4.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example3
{
@@ -29,9 +29,9 @@ static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
return true;
// Handle NaN, Infinity.
- if (Double.IsInfinity(value1) | Double.IsNaN(value1))
+ if (double.IsInfinity(value1) | double.IsNaN(value1))
return value1.Equals(value2);
- else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
+ else if (double.IsInfinity(value2) | double.IsNaN(value2))
return value1.Equals(value2);
// Handle zero to avoid division by zero.
diff --git a/snippets/csharp/System/Single/Overview/convert1.cs b/snippets/csharp/System/Single/Overview/convert1.cs
index 8a5e0e75a97..c7995e864df 100644
--- a/snippets/csharp/System/Single/Overview/convert1.cs
+++ b/snippets/csharp/System/Single/Overview/convert1.cs
@@ -1,22 +1,22 @@
-//
+//
using System;
public class Example4
{
public static void Main()
{
- dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
- Decimal.MaxValue, Double.MinValue, Double.MaxValue,
- Int16.MinValue, Int16.MaxValue, Int32.MinValue,
- Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
- SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
- UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
- UInt64.MinValue, UInt64.MaxValue };
+ dynamic[] values = [byte.MinValue, byte.MaxValue, decimal.MinValue,
+ decimal.MaxValue, double.MinValue, double.MaxValue,
+ short.MinValue, short.MaxValue, int.MinValue,
+ int.MaxValue, long.MinValue, long.MaxValue,
+ sbyte.MinValue, sbyte.MaxValue, ushort.MinValue,
+ ushort.MaxValue, uint.MinValue, uint.MaxValue,
+ ulong.MinValue, ulong.MaxValue];
float sngValue;
foreach (var value in values)
{
- if (value.GetType() == typeof(Decimal) ||
- value.GetType() == typeof(Double))
+ if (value.GetType() == typeof(decimal) ||
+ value.GetType() == typeof(double))
sngValue = (float)value;
else
sngValue = value;
diff --git a/snippets/csharp/System/Single/Overview/convert2.cs b/snippets/csharp/System/Single/Overview/convert2.cs
index d9a17fb336c..812afb97838 100644
--- a/snippets/csharp/System/Single/Overview/convert2.cs
+++ b/snippets/csharp/System/Single/Overview/convert2.cs
@@ -1,21 +1,21 @@
-using System;
+using System;
public class Example5
{
public static void Main()
{
//
- float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
- 12345.6789f, 67890.1234f, Single.MaxValue,
- Single.NaN, Single.PositiveInfinity,
- Single.NegativeInfinity };
+ float[] values = [float.MinValue, -67890.1234f, -12345.6789f,
+ 12345.6789f, 67890.1234f, float.MaxValue,
+ float.NaN, float.PositiveInfinity,
+ float.NegativeInfinity];
checked
{
- foreach (var value in values)
+ foreach (float value in values)
{
try
{
- Int64 lValue = (long)value;
+ long lValue = (long)value;
Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})");
}
catch (OverflowException)
@@ -24,7 +24,7 @@ public static void Main()
}
try
{
- UInt64 ulValue = (ulong)value;
+ ulong ulValue = (ulong)value;
Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})");
}
catch (OverflowException)
@@ -33,7 +33,7 @@ public static void Main()
}
try
{
- Decimal dValue = (decimal)value;
+ decimal dValue = (decimal)value;
Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})");
}
catch (OverflowException)
@@ -41,7 +41,7 @@ public static void Main()
Console.WriteLine($"Unable to convert {value} to Decimal.");
}
- Double dblValue = value;
+ double dblValue = value;
Console.WriteLine($"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})");
Console.WriteLine();
}
diff --git a/snippets/csharp/System/Single/Overview/exceptional2.cs b/snippets/csharp/System/Single/Overview/exceptional2.cs
index 6c0cf45b151..b443cc4fe5c 100644
--- a/snippets/csharp/System/Single/Overview/exceptional2.cs
+++ b/snippets/csharp/System/Single/Overview/exceptional2.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example7
{
@@ -8,14 +8,14 @@ public static void Main()
float value1 = 3.065e35f;
float value2 = 6.9375e32f;
float result = value1 * value2;
- Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}");
- Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}");
+ Console.WriteLine($"PositiveInfinity: {float.IsPositiveInfinity(result)}");
+ Console.WriteLine($"NegativeInfinity: {float.IsNegativeInfinity(result)}");
Console.WriteLine();
value1 = -value1;
result = value1 * value2;
- Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}");
- Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}");
+ Console.WriteLine($"PositiveInfinity: {float.IsPositiveInfinity(result)}");
+ Console.WriteLine($"NegativeInfinity: {float.IsNegativeInfinity(result)}");
// The example displays the following output:
// PositiveInfinity: True
diff --git a/snippets/csharp/System/Single/Overview/precisionlist1.cs b/snippets/csharp/System/Single/Overview/precisionlist1.cs
index c42b4fc898f..02f1c908889 100644
--- a/snippets/csharp/System/Single/Overview/precisionlist1.cs
+++ b/snippets/csharp/System/Single/Overview/precisionlist1.cs
@@ -1,13 +1,13 @@
-using System;
+using System;
public class Example9
{
public static void Main()
{
//
- Double value1 = 1 / 3.0;
- Single sValue2 = 1 / 3.0f;
- Double value2 = (Double)sValue2;
+ double value1 = 1 / 3.0;
+ float sValue2 = 1 / 3.0f;
+ double value2 = (double)sValue2;
Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}");
// The example displays the following output on .NET:
diff --git a/snippets/csharp/System/Single/Overview/precisionlist3.cs b/snippets/csharp/System/Single/Overview/precisionlist3.cs
index c8f2421707d..08338d033b4 100644
--- a/snippets/csharp/System/Single/Overview/precisionlist3.cs
+++ b/snippets/csharp/System/Single/Overview/precisionlist3.cs
@@ -5,10 +5,10 @@ public class PrecisionList3Example
{
public static void Main()
{
- Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f };
- Single result = 27.65f;
- Single total = 0f;
- foreach (var value in values)
+ float[] values = [10.01f, 2.88f, 2.88f, 2.88f, 9.0f];
+ float result = 27.65f;
+ float total = 0f;
+ foreach (float value in values)
total += value;
if (total.Equals(result))
diff --git a/snippets/csharp/System/Single/Overview/representation1.cs b/snippets/csharp/System/Single/Overview/representation1.cs
index 6ea38e68a79..0e4b8f14ea2 100644
--- a/snippets/csharp/System/Single/Overview/representation1.cs
+++ b/snippets/csharp/System/Single/Overview/representation1.cs
@@ -1,13 +1,13 @@
-//
+//
using System;
public class Example12
{
public static void Main()
{
- Single value = .2f;
- Single result1 = value * 10f;
- Single result2 = 0f;
+ float value = .2f;
+ float result1 = value * 10f;
+ float result2 = 0f;
for (int ctr = 1; ctr <= 10; ctr++)
result2 += value;
diff --git a/snippets/csharp/System/Single/Overview/representation2.cs b/snippets/csharp/System/Single/Overview/representation2.cs
index a3a072bdb3b..831f6bba562 100644
--- a/snippets/csharp/System/Single/Overview/representation2.cs
+++ b/snippets/csharp/System/Single/Overview/representation2.cs
@@ -5,8 +5,8 @@ public class Example13
{
public static void Main()
{
- Single value = 123.456f;
- Single additional = Single.Epsilon * 1e15f;
+ float value = 123.456f;
+ float additional = float.Epsilon * 1e15f;
Console.WriteLine($"{value} + {additional} = {value + additional}");
}
}
diff --git a/snippets/csharp/System/Single/Parse/Program.cs b/snippets/csharp/System/Single/Parse/Program.cs
new file mode 100644
index 00000000000..54c708cd959
--- /dev/null
+++ b/snippets/csharp/System/Single/Parse/Program.cs
@@ -0,0 +1,3 @@
+SingleParseDefaultExample.Run();
+ParseString.Run();
+SingleParseProviderExample.Run();
diff --git a/snippets/csharp/System/Single/Parse/Project.csproj b/snippets/csharp/System/Single/Parse/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Single/Parse/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Single/Parse/parse1.cs b/snippets/csharp/System/Single/Parse/parse1.cs
index 94a4ae32ad5..57f3bdbc73e 100644
--- a/snippets/csharp/System/Single/Parse/parse1.cs
+++ b/snippets/csharp/System/Single/Parse/parse1.cs
@@ -1,28 +1,31 @@
//
using System;
-public class Example
+public class SingleParseDefaultExample
{
- public static void Main()
- {
- string[] values = { "100", "(100)", "-123,456,789", "123.45e+6",
- "+500", "5e2", "3.1416", "600.", "-.123",
- "-Infinity", "-1E-16", Double.MaxValue.ToString(),
- Single.MinValue.ToString(), String.Empty };
- foreach (string value in values)
- {
- try {
- float number = Single.Parse(value);
- Console.WriteLine("{0} -> {1}", value, number);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}' is not in a valid format.", value);
- }
- catch (OverflowException) {
- Console.WriteLine("{0} is outside the range of a Single.", value);
- }
- }
- }
+ public static void Run()
+ {
+ string[] values = ["100", "(100)", "-123,456,789", "123.45e+6",
+ "+500", "5e2", "3.1416", "600.", "-.123",
+ "-Infinity", "-1E-16", $"{double.MaxValue}",
+ $"{float.MinValue}", string.Empty];
+ foreach (string value in values)
+ {
+ try
+ {
+ float number = float.Parse(value);
+ Console.WriteLine($"{value} -> {number}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{value}' is not in a valid format.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"{value} is outside the range of a Single.");
+ }
+ }
+ }
}
// The example displays the following output:
// 100 -> 100
diff --git a/snippets/csharp/System/Single/Parse/parse2.cs b/snippets/csharp/System/Single/Parse/parse2.cs
index 9dd7be9bdf5..e06b0ce0fd3 100644
--- a/snippets/csharp/System/Single/Parse/parse2.cs
+++ b/snippets/csharp/System/Single/Parse/parse2.cs
@@ -5,66 +5,64 @@
public class ParseString
{
- public static void Main()
- {
- // Set current thread culture to en-US.
- Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
-
- string value;
- NumberStyles styles;
-
- // Parse a string in exponential notation with only the AllowExponent flag.
- value = "-1.063E-02";
- styles = NumberStyles.AllowExponent;
- ShowNumericValue(value, styles);
-
- // Parse a string in exponential notation
- // with the AllowExponent and Number flags.
- styles = NumberStyles.AllowExponent | NumberStyles.Number;
- ShowNumericValue(value, styles);
+ public static void Run()
+ {
+ // Set current thread culture to en-US.
+ Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
- // Parse a currency value with leading and trailing white space, and
- // white space after the U.S. currency symbol.
- value = " $ 6,164.3299 ";
- styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
- ShowNumericValue(value, styles);
-
- // Parse negative value with thousands separator and decimal.
- value = "(4,320.64)";
- styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
- NumberStyles.Float;
- ShowNumericValue(value, styles);
-
- styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
- NumberStyles.Float | NumberStyles.AllowThousands;
- ShowNumericValue(value, styles);
- }
+ string value;
+ NumberStyles styles;
- private static void ShowNumericValue(string value, NumberStyles styles)
- {
- Single number;
- try
- {
- number = Single.Parse(value, styles);
- Console.WriteLine("Converted '{0}' using {1} to {2}.",
- value, styles.ToString(), number);
- }
- catch (FormatException)
- {
- Console.WriteLine("Unable to parse '{0}' with styles {1}.",
- value, styles.ToString());
- }
- Console.WriteLine();
- }
+ // Parse a string in exponential notation with only the AllowExponent flag.
+ value = "-1.063E-02";
+ styles = NumberStyles.AllowExponent;
+ ShowNumericValue(value, styles);
+
+ // Parse a string in exponential notation
+ // with the AllowExponent and Number flags.
+ styles = NumberStyles.AllowExponent | NumberStyles.Number;
+ ShowNumericValue(value, styles);
+
+ // Parse a currency value with leading and trailing white space, and
+ // white space after the U.S. currency symbol.
+ value = " $ 6,164.3299 ";
+ styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
+ ShowNumericValue(value, styles);
+
+ // Parse negative value with thousands separator and decimal.
+ value = "(4,320.64)";
+ styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
+ NumberStyles.Float;
+ ShowNumericValue(value, styles);
+
+ styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
+ NumberStyles.Float | NumberStyles.AllowThousands;
+ ShowNumericValue(value, styles);
+ }
+
+ private static void ShowNumericValue(string value, NumberStyles styles)
+ {
+ float number;
+ try
+ {
+ number = float.Parse(value, styles);
+ Console.WriteLine($"Converted '{value}' using {styles} to {number}.");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"Unable to parse '{value}' with styles {styles}.");
+ }
+ Console.WriteLine();
+ }
}
// The example displays the following output to the console:
// Unable to parse '-1.063E-02' with styles AllowExponent.
-//
+//
// Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
-//
+//
// Converted ' $ 6,164.3299 ' using Number, AllowCurrencySymbol to 6164.3299.
-//
+//
// Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
-//
-// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
+//
+// Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
//
diff --git a/snippets/csharp/System/Single/Parse/parse3.cs b/snippets/csharp/System/Single/Parse/parse3.cs
index 09b21dd9db9..dd33935f0c4 100644
--- a/snippets/csharp/System/Single/Parse/parse3.cs
+++ b/snippets/csharp/System/Single/Parse/parse3.cs
@@ -2,51 +2,52 @@
using System;
using System.Globalization;
-public class Example
+public class SingleParseProviderExample
{
- public static void Main()
+ public static void Run()
{
- // Define an array of string values.
- string[] values = { " 987.654E-2", " 987,654E-2", "(98765,43210)",
- "9,876,543.210", "9.876.543,210", "98_76_54_32,19" };
- // Create a custom culture based on the invariant culture.
- CultureInfo ci = new CultureInfo("");
- ci.NumberFormat.NumberGroupSizes = new int[] { 2 };
- ci.NumberFormat.NumberGroupSeparator = "_";
+ // Define an array of string values.
+ string[] values = [" 987.654E-2", " 987,654E-2", "(98765,43210)",
+ "9,876,543.210", "9.876.543,210", "98_76_54_32,19"];
+ // Create a custom culture based on the invariant culture.
+ CultureInfo ci = new("");
+ ci.NumberFormat.NumberGroupSizes = [2];
+ ci.NumberFormat.NumberGroupSeparator = "_";
- // Define an array of format providers.
- CultureInfo[] providers = { new CultureInfo("en-US"),
- new CultureInfo("nl-NL"), ci };
+ // Define an array of format providers.
+ CultureInfo[] providers = [new CultureInfo("en-US"),
+ new CultureInfo("nl-NL"), ci];
- // Define an array of styles.
- NumberStyles[] styles = { NumberStyles.Currency, NumberStyles.Float };
+ // Define an array of styles.
+ NumberStyles[] styles = [NumberStyles.Currency, NumberStyles.Float];
- // Iterate the array of format providers.
- foreach (CultureInfo provider in providers)
- {
- Console.WriteLine("Parsing using the {0} culture:",
- provider.Name == String.Empty ? "Invariant" : provider.Name);
- // Parse each element in the array of string values.
- foreach (string value in values)
- {
- foreach (NumberStyles style in styles)
+ // Iterate the array of format providers.
+ foreach (CultureInfo provider in providers)
+ {
+ Console.WriteLine($"Parsing using the {(provider.Name == string.Empty ? "Invariant" : provider.Name)} culture:");
+ // Parse each element in the array of string values.
+ foreach (string value in values)
{
- try {
- float number = Single.Parse(value, style, provider);
- Console.WriteLine(" {0} ({1}) -> {2}",
- value, style, number);
- }
- catch (FormatException) {
- Console.WriteLine(" '{0}' is invalid using {1}.", value, style);
- }
- catch (OverflowException) {
- Console.WriteLine(" '{0}' is out of the range of a Single.", value);
- }
+ foreach (NumberStyles style in styles)
+ {
+ try
+ {
+ float number = float.Parse(value, style, provider);
+ Console.WriteLine($" {value} ({style}) -> {number}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($" '{value}' is invalid using {style}.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($" '{value}' is out of the range of a Single.");
+ }
+ }
}
- }
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Parsing using the en-US culture:
diff --git a/snippets/csharp/System/Single/ToString/ToString1.cs b/snippets/csharp/System/Single/ToString/ToString1.cs
index 5ea413b49bd..b8091c3ee9a 100644
--- a/snippets/csharp/System/Single/ToString/ToString1.cs
+++ b/snippets/csharp/System/Single/ToString/ToString1.cs
@@ -3,209 +3,208 @@
public class Class1
{
- public static void Main()
- {
- CallDefaultToString();
- Console.WriteLine("----------");
- CallToStringWithFormatProvider();
- Console.WriteLine("----------");
- CallToStringWithFormatString();
- Console.WriteLine("----------");
- CallToStringWithFormatStringAndProvider();
- }
-
- private static void CallDefaultToString()
- {
- //
- float number;
-
- number = 1.6E20F;
- // Displays 1.6E+20.
- Console.WriteLine(number.ToString());
-
- number = 1.6E2F;
- // Displays 160.
- Console.WriteLine(number.ToString());
-
- number = -3.541F;
- // Displays -3.541.
- Console.WriteLine(number.ToString());
-
- number = -1502345222199E-07F;
- // Displays -150234.5222199.
- Console.WriteLine(number.ToString());
-
- number = -15023452221990199574E-09F;
- // Displays -15023452221.9902.
- Console.WriteLine(number.ToString());
-
- number = .60344F;
- // Displays 0.60344.
- Console.WriteLine(number.ToString());
-
- number = .000000001F;
- // Displays 1E-09.
- Console.WriteLine(number.ToString());
- //
- }
-
- private static void CallToStringWithFormatProvider()
- {
- //
- float value;
-
- value = -16325.62015F;
- // Display value using the invariant culture.
- Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
- // Display value using the en-GB culture.
- Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
- // Display value using the de-DE culture.
- Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
-
- value = 16034.125E21F;
- // Display value using the invariant culture.
- Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
- // Display value using the en-GB culture.
- Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
- // Display value using the de-DE culture.
- Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
- // This example displays the following output to the console:
- // -16325.62015
- // -16325.62015
- // -16325,62015
- // 1.6034125E+25
- // 1.6034125E+25
- // 1,6034125E+25
- //
- }
-
- private static void CallToStringWithFormatString()
- {
- //
- float[] numbers= { 1054.32179F, -195489100.8377F, 1.0437E21F,
- -1.0573e-05F };
- string[] specifiers = { "C", "E", "e", "F", "G", "N", "P",
- "R", "#,000.000", "0.###E-000",
- "000,000,000,000.00###" };
-
- foreach (float number in numbers)
- {
- Console.WriteLine("Formatting of {0}:", number);
- foreach (string specifier in specifiers)
- Console.WriteLine(" {0,5}: {1}",
- specifier, number.ToString(specifier));
-
- Console.WriteLine();
- }
- // The example displays the following output to the console:
- // Formatting of 1054.32179:
- // C: $1,054.32
- // E: 1.054322E+003
- // e: 1.054322e+003
- // F: 1054.32
- // G: 1054.32179
- // N: 1,054.32
- // P: 105,432.18 %
- // R: 1054.32179
- // #,000.000: 1,054.322
- // 0.###E-000: 1.054E003
- // 000,000,000,000.00###: 000,000,001,054.322
- //
- // Formatting of -195489100.8377:
- // C: ($195,489,100.84)
- // E: -1.954891E+008
- // e: -1.954891e+008
- // F: -195489100.84
- // G: -195489100.8377
- // N: -195,489,100.84
- // P: -19,548,910,083.77 %
- // R: -195489100.8377
- // #,000.000: -195,489,100.838
- // 0.###E-000: -1.955E008
- // 000,000,000,000.00###: -000,195,489,100.00
- //
- // Formatting of 1.0437E+21:
- // C: $1,043,700,000,000,000,000,000.00
- // E: 1.043700E+021
- // e: 1.043700e+021
- // F: 1043700000000000000000.00
- // G: 1.0437E+21
- // N: 1,043,700,000,000,000,000,000.00
- // P: 104,370,000,000,000,000,000,000.00 %
- // R: 1.0437E+21
- // #,000.000: 1,043,700,000,000,000,000,000.000
- // 0.###E-000: 1.044E021
- // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00
- //
- // Formatting of -1.0573E-05:
- // C: $0.00
- // E: -1.057300E-005
- // e: -1.057300e-005
- // F: 0.00
- // G: -1.0573E-05
- // N: 0.00
- // P: 0.00 %
- // R: -1.0573E-05
- // #,000.000: 000.000
- // 0.###E-000: -1.057E-005
- // 000,000,000,000.00###: -000,000,000,000.00001
- //
- }
-
- private static void CallToStringWithFormatStringAndProvider()
- {
- //
- float value = 16325.62901F;
- string specifier;
- CultureInfo culture;
-
- // Use standard numeric format specifiers.
- specifier = "G";
- culture = CultureInfo.CreateSpecificCulture("eu-ES");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 16325,62901
- Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture));
- // Displays: 16325.62901
-
- specifier = "C";
- culture = CultureInfo.CreateSpecificCulture("en-US");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: $16,325.63
- culture = CultureInfo.CreateSpecificCulture("en-GB");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: £16,325.63
-
- specifier = "E04";
- culture = CultureInfo.CreateSpecificCulture("sv-SE");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 1,6326E+004
- culture = CultureInfo.CreateSpecificCulture("en-NZ");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 1.6326E+004
-
- specifier = "F";
- culture = CultureInfo.CreateSpecificCulture("fr-FR");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 16325,63
- culture = CultureInfo.CreateSpecificCulture("en-CA");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 16325.63
-
- specifier = "N";
- culture = CultureInfo.CreateSpecificCulture("es-ES");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 16.325,63
- culture = CultureInfo.CreateSpecificCulture("fr-CA");
- Console.WriteLine(value.ToString(specifier, culture));
- // Displays: 16 325,63
-
- specifier = "P";
- culture = CultureInfo.InvariantCulture;
- Console.WriteLine((value/10000).ToString(specifier, culture));
- // Displays: 163.26 %
- culture = CultureInfo.CreateSpecificCulture("ar-EG");
- Console.WriteLine((value/10000).ToString(specifier, culture));
- // Displays: 163.256 %
- //
- }
+ public static void Main()
+ {
+ CallDefaultToString();
+ Console.WriteLine("----------");
+ CallToStringWithFormatProvider();
+ Console.WriteLine("----------");
+ CallToStringWithFormatString();
+ Console.WriteLine("----------");
+ CallToStringWithFormatStringAndProvider();
+ }
+
+ private static void CallDefaultToString()
+ {
+ //
+ float number;
+
+ number = 1.6E20F;
+ // Displays 1.6E+20.
+ Console.WriteLine(number.ToString());
+
+ number = 1.6E2F;
+ // Displays 160.
+ Console.WriteLine(number.ToString());
+
+ number = -3.541F;
+ // Displays -3.541.
+ Console.WriteLine(number.ToString());
+
+ number = -1502345222199E-07F;
+ // Displays -150234.5222199.
+ Console.WriteLine(number.ToString());
+
+ number = -15023452221990199574E-09F;
+ // Displays -15023452221.9902.
+ Console.WriteLine(number.ToString());
+
+ number = .60344F;
+ // Displays 0.60344.
+ Console.WriteLine(number.ToString());
+
+ number = .000000001F;
+ // Displays 1E-09.
+ Console.WriteLine(number.ToString());
+ //
+ }
+
+ private static void CallToStringWithFormatProvider()
+ {
+ //
+ float value;
+
+ value = -16325.62015F;
+ // Display value using the invariant culture.
+ Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
+ // Display value using the en-GB culture.
+ Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
+ // Display value using the de-DE culture.
+ Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
+
+ value = 16034.125E21F;
+ // Display value using the invariant culture.
+ Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
+ // Display value using the en-GB culture.
+ Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB")));
+ // Display value using the de-DE culture.
+ Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
+ // This example displays the following output to the console:
+ // -16325.62015
+ // -16325.62015
+ // -16325,62015
+ // 1.6034125E+25
+ // 1.6034125E+25
+ // 1,6034125E+25
+ //
+ }
+
+ private static void CallToStringWithFormatString()
+ {
+ //
+ float[] numbers = [1054.32179F, -195489100.8377F, 1.0437E21F,
+ -1.0573e-05F];
+ string[] specifiers = ["C", "E", "e", "F", "G", "N", "P",
+ "R", "#,000.000", "0.###E-000",
+ "000,000,000,000.00###"];
+
+ foreach (float number in numbers)
+ {
+ Console.WriteLine($"Formatting of {number}:");
+ foreach (string specifier in specifiers)
+ Console.WriteLine($" {specifier,5}: {number.ToString(specifier)}");
+
+ Console.WriteLine();
+ }
+ // The example displays the following output to the console:
+ // Formatting of 1054.32179:
+ // C: $1,054.32
+ // E: 1.054322E+003
+ // e: 1.054322e+003
+ // F: 1054.32
+ // G: 1054.32179
+ // N: 1,054.32
+ // P: 105,432.18 %
+ // R: 1054.32179
+ // #,000.000: 1,054.322
+ // 0.###E-000: 1.054E003
+ // 000,000,000,000.00###: 000,000,001,054.322
+ //
+ // Formatting of -195489100.8377:
+ // C: ($195,489,100.84)
+ // E: -1.954891E+008
+ // e: -1.954891e+008
+ // F: -195489100.84
+ // G: -195489100.8377
+ // N: -195,489,100.84
+ // P: -19,548,910,083.77 %
+ // R: -195489100.8377
+ // #,000.000: -195,489,100.838
+ // 0.###E-000: -1.955E008
+ // 000,000,000,000.00###: -000,195,489,100.00
+ //
+ // Formatting of 1.0437E+21:
+ // C: $1,043,700,000,000,000,000,000.00
+ // E: 1.043700E+021
+ // e: 1.043700e+021
+ // F: 1043700000000000000000.00
+ // G: 1.0437E+21
+ // N: 1,043,700,000,000,000,000,000.00
+ // P: 104,370,000,000,000,000,000,000.00 %
+ // R: 1.0437E+21
+ // #,000.000: 1,043,700,000,000,000,000,000.000
+ // 0.###E-000: 1.044E021
+ // 000,000,000,000.00###: 1,043,700,000,000,000,000,000.00
+ //
+ // Formatting of -1.0573E-05:
+ // C: $0.00
+ // E: -1.057300E-005
+ // e: -1.057300e-005
+ // F: 0.00
+ // G: -1.0573E-05
+ // N: 0.00
+ // P: 0.00 %
+ // R: -1.0573E-05
+ // #,000.000: 000.000
+ // 0.###E-000: -1.057E-005
+ // 000,000,000,000.00###: -000,000,000,000.00001
+ //
+ }
+
+ private static void CallToStringWithFormatStringAndProvider()
+ {
+ //
+ float value = 16325.62901F;
+ string specifier;
+ CultureInfo culture;
+
+ // Use standard numeric format specifiers.
+ specifier = "G";
+ culture = CultureInfo.CreateSpecificCulture("eu-ES");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 16325,62901
+ Console.WriteLine(value.ToString(specifier, CultureInfo.InvariantCulture));
+ // Displays: 16325.62901
+
+ specifier = "C";
+ culture = CultureInfo.CreateSpecificCulture("en-US");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: $16,325.63
+ culture = CultureInfo.CreateSpecificCulture("en-GB");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: £16,325.63
+
+ specifier = "E04";
+ culture = CultureInfo.CreateSpecificCulture("sv-SE");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 1,6326E+004
+ culture = CultureInfo.CreateSpecificCulture("en-NZ");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 1.6326E+004
+
+ specifier = "F";
+ culture = CultureInfo.CreateSpecificCulture("fr-FR");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 16325,63
+ culture = CultureInfo.CreateSpecificCulture("en-CA");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 16325.63
+
+ specifier = "N";
+ culture = CultureInfo.CreateSpecificCulture("es-ES");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 16.325,63
+ culture = CultureInfo.CreateSpecificCulture("fr-CA");
+ Console.WriteLine(value.ToString(specifier, culture));
+ // Displays: 16 325,63
+
+ specifier = "P";
+ culture = CultureInfo.InvariantCulture;
+ Console.WriteLine((value / 10000).ToString(specifier, culture));
+ // Displays: 163.26 %
+ culture = CultureInfo.CreateSpecificCulture("ar-EG");
+ Console.WriteLine((value / 10000).ToString(specifier, culture));
+ // Displays: 163.256 %
+ //
+ }
}
diff --git a/snippets/csharp/System/Single/ToString/ToString7.cs b/snippets/csharp/System/Single/ToString/ToString7.cs
index bef287d882e..50919b4bab4 100644
--- a/snippets/csharp/System/Single/ToString/ToString7.cs
+++ b/snippets/csharp/System/Single/ToString/ToString7.cs
@@ -3,16 +3,16 @@
public class Example
{
- public static void Main()
- {
- Double number = 1764.3789;
-
- // Format as a currency value.
- Console.WriteLine(number.ToString("C"));
-
- // Format as a numeric value with 3 decimal places.
- Console.WriteLine(number.ToString("N3"));
- }
+ public static void Main()
+ {
+ double number = 1764.3789;
+
+ // Format as a currency value.
+ Console.WriteLine(number.ToString("C"));
+
+ // Format as a numeric value with 3 decimal places.
+ Console.WriteLine(number.ToString("N3"));
+ }
}
// The example displays the following output:
// $1,764.38
diff --git a/snippets/csharp/System/Single/TryParse/tryparse1.cs b/snippets/csharp/System/Single/TryParse/tryparse1.cs
index a04439a3ead..ae03065cb59 100644
--- a/snippets/csharp/System/Single/TryParse/tryparse1.cs
+++ b/snippets/csharp/System/Single/TryParse/tryparse1.cs
@@ -2,100 +2,100 @@
public class Class1
{
- public static void Main()
- {
- DefaultTryParse();
- Console.WriteLine("----------");
- TryParseWithConstraints();
- }
+ public static void Main()
+ {
+ DefaultTryParse();
+ Console.WriteLine("----------");
+ TryParseWithConstraints();
+ }
- private static void DefaultTryParse()
- {
- //
- string value;
- float number;
+ private static void DefaultTryParse()
+ {
+ //
+ string value;
+ float number;
- // Parse a floating-point value with a thousands separator.
- value = "1,643.57";
- if (Single.TryParse(value, out number))
- Console.WriteLine(number);
- else
- Console.WriteLine("Unable to parse '{0}'.", value);
+ // Parse a floating-point value with a thousands separator.
+ value = "1,643.57";
+ if (float.TryParse(value, out number))
+ Console.WriteLine(number);
+ else
+ Console.WriteLine($"Unable to parse '{value}'.");
- // Parse a floating-point value with a currency symbol and a
- // thousands separator.
- value = "$1,643.57";
- if (Single.TryParse(value, out number))
- Console.WriteLine(number);
- else
- Console.WriteLine("Unable to parse '{0}'.", value);
+ // Parse a floating-point value with a currency symbol and a
+ // thousands separator.
+ value = "$1,643.57";
+ if (float.TryParse(value, out number))
+ Console.WriteLine(number);
+ else
+ Console.WriteLine($"Unable to parse '{value}'.");
- // Parse value in exponential notation.
- value = "-1.643e6";
- if (Single.TryParse(value, out number))
- Console.WriteLine(number);
- else
- Console.WriteLine("Unable to parse '{0}'.", value);
+ // Parse value in exponential notation.
+ value = "-1.643e6";
+ if (float.TryParse(value, out number))
+ Console.WriteLine(number);
+ else
+ Console.WriteLine($"Unable to parse '{value}'.");
- // Parse a negative integer value.
- value = "-168934617882109132";
- if (Single.TryParse(value, out number))
- Console.WriteLine(number);
- else
- Console.WriteLine("Unable to parse '{0}'.", value);
- // The example displays the following output:
- // 1643.57
- // Unable to parse '$1,643.57'.
- // -164300
- // -1.689346E+17
- //
- }
+ // Parse a negative integer value.
+ value = "-168934617882109132";
+ if (float.TryParse(value, out number))
+ Console.WriteLine(number);
+ else
+ Console.WriteLine($"Unable to parse '{value}'.");
+ // The example displays the following output:
+ // 1643.57
+ // Unable to parse '$1,643.57'.
+ // -164300
+ // -1.689346E+17
+ //
+ }
- private static void TryParseWithConstraints()
- {
- //
- string value;
- System.Globalization.NumberStyles style;
- System.Globalization.CultureInfo culture;
- float number;
+ private static void TryParseWithConstraints()
+ {
+ //
+ string value;
+ System.Globalization.NumberStyles style;
+ System.Globalization.CultureInfo culture;
+ float number;
- // Parse currency value using en-GB culture.
- value = "£1,097.63";
- style = System.Globalization.NumberStyles.Number |
- System.Globalization.NumberStyles.AllowCurrencySymbol;
- culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
- if (Single.TryParse(value, style, culture, out number))
- Console.WriteLine("Converted '{0}' to {1}.", value, number);
- else
- Console.WriteLine("Unable to convert '{0}'.", value);
+ // Parse currency value using en-GB culture.
+ value = "£1,097.63";
+ style = System.Globalization.NumberStyles.Number |
+ System.Globalization.NumberStyles.AllowCurrencySymbol;
+ culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
+ if (float.TryParse(value, style, culture, out number))
+ Console.WriteLine($"Converted '{value}' to {number}.");
+ else
+ Console.WriteLine($"Unable to convert '{value}'.");
- value = "1345,978";
- style = System.Globalization.NumberStyles.AllowDecimalPoint;
- culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
- if (Single.TryParse(value, style, culture, out number))
- Console.WriteLine("Converted '{0}' to {1}.", value, number);
- else
- Console.WriteLine("Unable to convert '{0}'.", value);
+ value = "1345,978";
+ style = System.Globalization.NumberStyles.AllowDecimalPoint;
+ culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
+ if (float.TryParse(value, style, culture, out number))
+ Console.WriteLine($"Converted '{value}' to {number}.");
+ else
+ Console.WriteLine($"Unable to convert '{value}'.");
- value = "1.345,978";
- style = System.Globalization.NumberStyles.AllowDecimalPoint |
- System.Globalization.NumberStyles.AllowThousands;
- culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES");
- if (Single.TryParse(value, style, culture, out number))
- Console.WriteLine("Converted '{0}' to {1}.", value, number);
- else
- Console.WriteLine("Unable to convert '{0}'.", value);
+ value = "1.345,978";
+ style = System.Globalization.NumberStyles.AllowDecimalPoint |
+ System.Globalization.NumberStyles.AllowThousands;
+ culture = System.Globalization.CultureInfo.CreateSpecificCulture("es-ES");
+ if (float.TryParse(value, style, culture, out number))
+ Console.WriteLine($"Converted '{value}' to {number}.");
+ else
+ Console.WriteLine($"Unable to convert '{value}'.");
- value = "1 345,978";
- if (Single.TryParse(value, style, culture, out number))
- Console.WriteLine("Converted '{0}' to {1}.", value, number);
- else
- Console.WriteLine("Unable to convert '{0}'.", value);
- // The example displays the following output:
- // Converted '£1,097.63' to 1097.63.
- // Converted '1345,978' to 1345.978.
- // Converted '1.345,978' to 1345.978.
- // Unable to convert '1 345,978'.
- //
- }
+ value = "1 345,978";
+ if (float.TryParse(value, style, culture, out number))
+ Console.WriteLine($"Converted '{value}' to {number}.");
+ else
+ Console.WriteLine($"Unable to convert '{value}'.");
+ // The example displays the following output:
+ // Converted '£1,097.63' to 1097.63.
+ // Converted '1345,978' to 1345.978.
+ // Converted '1.345,978' to 1345.978.
+ // Unable to convert '1 345,978'.
+ //
+ }
}
diff --git a/snippets/csharp/System/Span.Enumerator/Program.cs b/snippets/csharp/System/Span.Enumerator/Program.cs
index 02899297953..b6a091df094 100644
--- a/snippets/csharp/System/Span.Enumerator/Program.cs
+++ b/snippets/csharp/System/Span.Enumerator/Program.cs
@@ -10,9 +10,9 @@ static void Main()
new Random(42).NextBytes(_array);
Span span = _array;
- Task.Run( () => ClearContents() );
+ Task.Run(() => ClearContents());
- EnumerateSpan(span);
+ EnumerateSpan(span);
}
public static void ClearContents()
@@ -20,7 +20,7 @@ public static void ClearContents()
Task.Delay(20).Wait();
lock (_array)
{
- Array.Clear(_array, 0, _array.Length);
+ Array.Clear(_array, 0, _array.Length);
}
}
@@ -38,4 +38,4 @@ public static void EnumerateSpan(Span span)
// 23
// 186
// 0
-// 0
\ No newline at end of file
+// 0
diff --git a/snippets/csharp/System/Span.Enumerator/Program2.cs b/snippets/csharp/System/Span.Enumerator/Program2.cs
index d53b5c46324..c475bb77a87 100644
--- a/snippets/csharp/System/Span.Enumerator/Program2.cs
+++ b/snippets/csharp/System/Span.Enumerator/Program2.cs
@@ -10,7 +10,7 @@ static void Main()
new Random(42).NextBytes(_array);
Span span = _array;
- Task.Run( () => ClearContents() );
+ Task.Run(() => ClearContents());
EnumerateSpan(span);
}
@@ -20,7 +20,7 @@ public static void ClearContents()
Task.Delay(20).Wait();
lock (_array)
{
- Array.Clear(_array, 0, _array.Length);
+ Array.Clear(_array, 0, _array.Length);
}
}
diff --git a/snippets/csharp/System/Span/Overview/program.cs b/snippets/csharp/System/Span/Overview/program.cs
index 51beba48d5e..4fff2f1868e 100644
--- a/snippets/csharp/System/Span/Overview/program.cs
+++ b/snippets/csharp/System/Span/Overview/program.cs
@@ -28,7 +28,7 @@ private static void CreateSpanFromArray()
arraySpan[ctr] = data++;
int arraySum = 0;
- foreach (var value in array)
+ foreach (byte value in array)
arraySum += value;
Console.WriteLine($"The sum is {arraySum}");
@@ -44,14 +44,14 @@ private static void CreateSpanFromNativeMemory()
Span nativeSpan;
unsafe
{
- nativeSpan = new Span(native.ToPointer(), 100);
+ nativeSpan = new(native.ToPointer(), 100);
}
byte data = 0;
for (int ctr = 0; ctr < nativeSpan.Length; ctr++)
nativeSpan[ctr] = data++;
int nativeSum = 0;
- foreach (var value in nativeSpan)
+ foreach (byte value in nativeSpan)
nativeSum += value;
Console.WriteLine($"The sum is {nativeSum}");
@@ -70,7 +70,7 @@ private static void CreateSpanFromStack()
stackSpan[ctr] = data++;
int stackSum = 0;
- foreach (var value in stackSpan)
+ foreach (byte value in stackSpan)
stackSum += value;
Console.WriteLine($"The sum is {stackSum}");
@@ -96,7 +96,7 @@ public static void WorkWithSpans()
Span nativeSpan;
unsafe
{
- nativeSpan = new Span(native.ToPointer(), 100);
+ nativeSpan = new(native.ToPointer(), 100);
}
InitializeSpan(nativeSpan);
@@ -121,7 +121,7 @@ public static void InitializeSpan(Span span)
public static int ComputeSum(Span span)
{
int sum = 0;
- foreach (var value in span)
+ foreach (byte value in span)
sum += value;
return sum;
diff --git a/snippets/csharp/System/Span/Slice/Program.cs b/snippets/csharp/System/Span/Slice/Program.cs
index 4bd2e3d18d4..f959f0f9f26 100644
--- a/snippets/csharp/System/Span/Slice/Program.cs
+++ b/snippets/csharp/System/Span/Slice/Program.cs
@@ -1,12 +1,12 @@
using System;
-var array = new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
+int[] array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
var slice = new Span(array, 2, 5);
for (int ctr = 0; ctr < slice.Length; ctr++)
slice[ctr] *= 2;
// Examine the original array values.
-foreach (var value in array)
+foreach (int value in array)
Console.Write($"{value} ");
Console.WriteLine();
diff --git a/snippets/csharp/System/Span/Slice/Program2.cs b/snippets/csharp/System/Span/Slice/Program2.cs
index 75bfaeff52a..704b362b732 100644
--- a/snippets/csharp/System/Span/Slice/Program2.cs
+++ b/snippets/csharp/System/Span/Slice/Program2.cs
@@ -5,7 +5,7 @@ class Program2
static void Run()
{
string contentLength = "Content-Length: 132";
- var length = GetContentLength(contentLength.ToCharArray());
+ int length = GetContentLength(contentLength.ToCharArray());
Console.WriteLine($"Content length: {length}");
}
diff --git a/snippets/csharp/System/StackOverflowException/Overview/example1a.cs b/snippets/csharp/System/StackOverflowException/Overview/example1a.cs
index d71ade38be9..b39da408413 100644
--- a/snippets/csharp/System/StackOverflowException/Overview/example1a.cs
+++ b/snippets/csharp/System/StackOverflowException/Overview/example1a.cs
@@ -3,27 +3,27 @@
public class Example
{
- private const int MAX_RECURSIVE_CALLS = 1000;
- static int ctr = 0;
-
- public static void Main()
- {
- Example ex = new Example();
- ex.Execute();
- Console.WriteLine("\nThe call counter: {0}", ctr);
- }
+ private const int MAX_RECURSIVE_CALLS = 1000;
+ static int ctr = 0;
- private void Execute()
- {
- ctr++;
- if (ctr % 50 == 0)
- Console.WriteLine("Call number {0} to the Execute method", ctr);
-
- if (ctr <= MAX_RECURSIVE_CALLS)
- Execute();
-
- ctr--;
- }
+ public static void Main()
+ {
+ Example ex = new();
+ ex.Execute();
+ Console.WriteLine($"\nThe call counter: {ctr}");
+ }
+
+ private void Execute()
+ {
+ ctr++;
+ if (ctr % 50 == 0)
+ Console.WriteLine($"Call number {ctr} to the Execute method");
+
+ if (ctr <= MAX_RECURSIVE_CALLS)
+ Execute();
+
+ ctr--;
+ }
}
// The example displays the following output:
// Call number 50 to the Execute method
From 11b0a69b1a6b22da0c9c108f21c9e14d361e12c3 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Thu, 13 Aug 2026 14:12:21 -0700
Subject: [PATCH 2/9] Update code modernization skill (#12983)
---
.github/skills/csharp-snippet-modernization/SKILL.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/.github/skills/csharp-snippet-modernization/SKILL.md b/.github/skills/csharp-snippet-modernization/SKILL.md
index 1e693a6f124..eeffbf9e23f 100644
--- a/.github/skills/csharp-snippet-modernization/SKILL.md
+++ b/.github/skills/csharp-snippet-modernization/SKILL.md
@@ -23,8 +23,8 @@ Apply these changes when they preserve behavior and sample clarity:
- Use top-level statements where possible.
- Use C# built-in aliases, such as `string`, `int`, and `bool`, instead of
- framework type names.
-- Use target-typed `new` when the target type is evident.
+ framework type names. Use `nint` and `nuint` for `IntPtr` and `UIntPtr`.
+- Remove calls to `ToString()` when the result is used in a string context, unless the call is the subject of the snippet.
- Use string interpolation instead of composite formatting, unless it makes the code harder to read
or the composite-format overload is the subject of the snippet. For example, keep composite
formatting when the arguments are complex:
@@ -34,8 +34,8 @@ Apply these changes when they preserve behavior and sample clarity:
timeZoneTime.DateTime);
```
- Use raw string literals (or interpolated raw string literals) for paragraph-style output.
-- Use object and collection initializers when evaluation order and behavior
- remain unchanged.
+- Use target-typed `new` when the target type is evident.
+- Use collection expressions to initialize collections and arrays wherever possible.
- Convert eligible value-producing `switch` statements to switch expressions.
- Use auto-implemented properties instead of defining a separate field.
- Use expression-bodied members for simple single-expression members. If the line gets too long, for example, a method signature with a type parameter constraint, place the expression body on a new line:
From 1962e74e8f15f4b2e36c12f7e97492d84f5b1f17 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Thu, 13 Aug 2026 16:10:57 -0700
Subject: [PATCH 3/9] Modernize C# snippets - Comparison{T}, System/L-O*
(#12968)
---
.../System/ComparisonT/Overview/Program.cs | 2 +
.../ComparisonT/Overview/Project.csproj | 8 +
.../ComparisonT/Overview/comparisont1.cs | 95 +++++-----
.../System/ComparisonT/Overview/source.cs | 26 +--
snippets/csharp/System/LazyT/.ctor/Program.cs | 6 +
.../csharp/System/LazyT/.ctor/Project.csproj | 8 +
snippets/csharp/System/LazyT/.ctor/example.cs | 17 +-
.../csharp/System/LazyT/.ctor/example1.cs | 13 +-
.../csharp/System/LazyT/.ctor/example2.cs | 20 +-
.../csharp/System/LazyT/.ctor/example3.cs | 19 +-
.../csharp/System/LazyT/.ctor/example4.cs | 27 ++-
.../csharp/System/LazyT/.ctor/example5.cs | 22 +--
.../csharp/System/LazyT/Overview/Program.cs | 2 +
.../System/LazyT/Overview/Project.csproj | 8 +
.../csharp/System/LazyT/Overview/example.cs | 17 +-
.../csharp/System/LazyT/Overview/lambda.cs | 17 +-
snippets/csharp/System/Math/Abs/Abs1.cs | 32 ++--
snippets/csharp/System/Math/Abs/Program.cs | 7 +
.../csharp/System/Math/Abs/Project.csproj | 8 +
snippets/csharp/System/Math/Abs/abs2.cs | 36 ++--
snippets/csharp/System/Math/Abs/abs3.cs | 47 ++---
snippets/csharp/System/Math/Abs/abs4.cs | 47 ++---
snippets/csharp/System/Math/Abs/abs5.cs | 47 ++---
snippets/csharp/System/Math/Abs/abs6.cs | 45 ++---
snippets/csharp/System/Math/Abs/abs7.cs | 36 ++--
snippets/csharp/System/Math/Atan/atan.cs | 58 +++---
snippets/csharp/System/Math/BigMul/bigmul.cs | 16 +-
.../csharp/System/Math/Ceiling/Ceiling1.cs | 86 +++++----
snippets/csharp/System/Math/Cos/sincos.cs | 62 +++----
snippets/csharp/System/Math/Cosh/sinhcosh.cs | 38 ++--
snippets/csharp/System/Math/DivRem/Program.cs | 2 +
.../csharp/System/Math/DivRem/Project.csproj | 8 +
snippets/csharp/System/Math/DivRem/divrem1.cs | 37 ++--
snippets/csharp/System/Math/DivRem/divrem2.cs | 37 ++--
snippets/csharp/System/Math/E/efield.cs | 14 +-
snippets/csharp/System/Math/Exp/exp.cs | 20 +-
.../Math/IEEERemainder/ieeeremainder1.cs | 44 ++---
snippets/csharp/System/Math/Log10/log10.cs | 15 +-
snippets/csharp/System/Math/LogMethod/log1.cs | 32 ++--
.../csharp/System/Math/LogMethod/loggen.cs | 18 +-
snippets/csharp/System/Math/Max/max.cs | 22 +--
snippets/csharp/System/Math/Min/min.cs | 22 +--
.../csharp/System/Math/Overview/mathsample.cs | 120 ++++++------
snippets/csharp/System/Math/Pow/pow1.cs | 84 ++++-----
snippets/csharp/System/Math/Round/Program.cs | 7 +
.../csharp/System/Math/Round/Project.csproj | 8 +
snippets/csharp/System/Math/Round/round2.cs | 30 +--
snippets/csharp/System/Math/Round/round3.cs | 14 +-
snippets/csharp/System/Math/Round/round4.cs | 33 ++--
snippets/csharp/System/Math/Round/round5.cs | 32 ++--
.../csharp/System/Math/Round/rounddecimal1.cs | 32 ++--
snippets/csharp/System/Math/Round/source.cs | 18 +-
snippets/csharp/System/Math/Round/source1.cs | 24 +--
snippets/csharp/System/Math/Sign/sign.cs | 18 +-
snippets/csharp/System/Math/Sqrt/sqrt1.cs | 42 ++---
snippets/csharp/System/Math/Tanh/tanh.cs | 28 ++-
.../csharp/System/Math/Truncate/Truncate1.cs | 42 ++---
.../Overview/MissingMethodException.cs | 18 +-
.../Overview/delegatestring.cs | 171 +++++++++---------
.../Overview/program.cs | 30 +--
.../Overview/BadState1.cs | 6 +-
.../Overview/TestProp1.cs | 11 +-
.../Overview/TestProp2.cs | 11 +-
.../NullReferenceException/Overview/Array1.cs | 5 +-
.../NullReferenceException/Overview/Array2.cs | 6 +-
.../NullReferenceException/Overview/Chain1.cs | 2 +-
.../NullReferenceException/Overview/Chain2.cs | 2 +-
.../Overview/example2.cs | 5 +-
.../Overview/example3.cs | 9 +-
.../Overview/nullreturn2.cs | 7 +-
.../System/Nullable/GetUnderlyingType/gut.cs | 31 ++--
snippets/csharp/System/NullableT/Equals/eq.cs | 50 ++---
.../NullableT/GetValueOrDefault/gvod.cs | 90 +++++----
.../System/NullableT/HasValue/hasvalue2.cs | 45 ++---
.../csharp/System/NullableT/Overview/tarow.cs | 75 ++++----
.../csharp/System/NullableT/ToString/ts.cs | 32 ++--
.../System/NullableT/op_Explicit/explicit1.cs | 18 +-
.../csharp/System/Object/Equals/equals2.cs | 39 ++--
.../csharp/System/Object/Equals/equals3.cs | 92 +++++-----
.../csharp/System/Object/Equals/equals4.cs | 55 ++----
.../csharp/System/Object/Equals/equals_ref.cs | 38 ++--
.../System/Object/Equals/equals_static2.cs | 78 ++++----
.../System/Object/Equals/equals_val1.cs | 26 +--
.../System/Object/Equals/equals_val2.cs | 30 ++-
.../System/Object/Equals/equalsoverride.cs | 49 +++--
.../csharp/System/Object/Equals/equalssb1.cs | 22 +--
.../System/Object/Finalize/finalize1.cs | 41 ++---
.../System/Object/Finalize/finalize_safe.cs | 8 +-
.../System/Object/GetHashCode/direct1.cs | 55 +++---
.../System/Object/GetHashCode/shift1.cs | 31 ++--
.../csharp/System/Object/GetHashCode/xor1.cs | 31 ++--
.../csharp/System/Object/GetHashCode/xor2.cs | 25 ++-
.../System/Object/GetType/GetTypeEx2.cs | 60 +++---
.../csharp/System/Object/GetType/Program.cs | 3 +
.../System/Object/GetType/Project.csproj | 8 +
.../csharp/System/Object/GetType/gettype.cs | 28 +--
.../csharp/System/Object/GetType/gettype1.cs | 30 ++-
.../MemberwiseClone/memberwiseclone1.cs | 16 +-
.../csharp/System/Object/Overview/ObjectX.cs | 29 +--
.../System/Object/ReferenceEquals/Program.cs | 3 +
.../Object/ReferenceEquals/Project.csproj | 8 +
.../Object/ReferenceEquals/referenceequals.cs | 35 ++--
.../ReferenceEquals/referenceequals4.cs | 24 +--
.../ReferenceEquals/referenceequalsa.cs | 42 ++---
.../csharp/System/Object/ToString/array1.cs | 24 +--
.../System/Object/ToString/customize1.cs | 43 +++--
.../System/Object/ToString/customize2.cs | 63 +++----
.../System/Object/ToString/tostring1.cs | 18 +-
.../System/Object/ToString/tostring2.cs | 16 +-
.../System/Object/ToString/tostring3.cs | 22 +--
.../Object/ToString/tostringoverload1.cs | 95 +++++-----
.../Object/ToString/tostringoverload2.cs | 21 ++-
.../Overview/dispose1.cs | 23 +--
.../Overview/objdispexc.cs | 28 +--
.../IsError/obsoleteattribute_message.cs | 72 ++++----
.../ObsoleteAttribute/Overview/Project.csproj | 8 +
.../Overview/obsoleteattributeex1.cs | 65 +++----
.../Overview/snippets.5000.json | 10 +
.../System/OperatingSystem/Clone/clone.cs | 32 ++--
.../OperatingSystem/Overview/osinfo1.cs | 24 +--
.../OperatingSystem/Platform/plat_ver.cs | 45 +++--
.../System/OperatingSystem/ServicePack/sp.cs | 8 +-
.../OperatingSystem/ToString/ctor_tostr.cs | 40 ++--
.../OperatingSystem/VersionString/osvs.cs | 10 +-
.../OutOfMemoryException/Overview/Program.cs | 4 +
.../Overview/Project.csproj | 8 +
.../OutOfMemoryException/Overview/data1.cs | 53 +++---
.../OutOfMemoryException/Overview/data2.cs | 71 ++++----
.../Overview/failfast1.cs | 47 ++---
.../Overview/sb_example1.cs | 26 +--
.../OverflowException/Overview/arithmetic1.cs | 117 ++++++------
xml/System/ObsoleteAttribute.xml | 11 +-
132 files changed, 2058 insertions(+), 2151 deletions(-)
create mode 100644 snippets/csharp/System/ComparisonT/Overview/Program.cs
create mode 100644 snippets/csharp/System/ComparisonT/Overview/Project.csproj
create mode 100644 snippets/csharp/System/LazyT/.ctor/Program.cs
create mode 100644 snippets/csharp/System/LazyT/.ctor/Project.csproj
create mode 100644 snippets/csharp/System/LazyT/Overview/Program.cs
create mode 100644 snippets/csharp/System/LazyT/Overview/Project.csproj
create mode 100644 snippets/csharp/System/Math/Abs/Program.cs
create mode 100644 snippets/csharp/System/Math/Abs/Project.csproj
create mode 100644 snippets/csharp/System/Math/DivRem/Program.cs
create mode 100644 snippets/csharp/System/Math/DivRem/Project.csproj
create mode 100644 snippets/csharp/System/Math/Round/Program.cs
create mode 100644 snippets/csharp/System/Math/Round/Project.csproj
create mode 100644 snippets/csharp/System/Object/GetType/Program.cs
create mode 100644 snippets/csharp/System/Object/GetType/Project.csproj
create mode 100644 snippets/csharp/System/Object/ReferenceEquals/Program.cs
create mode 100644 snippets/csharp/System/Object/ReferenceEquals/Project.csproj
create mode 100644 snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj
create mode 100644 snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json
create mode 100644 snippets/csharp/System/OutOfMemoryException/Overview/Program.cs
create mode 100644 snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj
diff --git a/snippets/csharp/System/ComparisonT/Overview/Program.cs b/snippets/csharp/System/ComparisonT/Overview/Program.cs
new file mode 100644
index 00000000000..fa4c677450d
--- /dev/null
+++ b/snippets/csharp/System/ComparisonT/Overview/Program.cs
@@ -0,0 +1,2 @@
+ComparisonTOverviewExample1.Run();
+ComparisonTOverviewExample2.Run();
diff --git a/snippets/csharp/System/ComparisonT/Overview/Project.csproj b/snippets/csharp/System/ComparisonT/Overview/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/ComparisonT/Overview/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs b/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs
index fbc3ab48f1e..1155811397d 100644
--- a/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs
+++ b/snippets/csharp/System/ComparisonT/Overview/comparisont1.cs
@@ -3,75 +3,62 @@
public class CityInfo
{
- string cityName;
- string countryName;
- int pop2010;
+ string cityName;
+ string countryName;
+ int pop2010;
- public CityInfo(string name, string country, int pop2010)
- {
- this.cityName = name;
- this.countryName = country;
- this.pop2010 = pop2010;
- }
+ public CityInfo(string name, string country, int pop2010)
+ {
+ this.cityName = name;
+ this.countryName = country;
+ this.pop2010 = pop2010;
+ }
- public string City
- { get { return this.cityName; } }
+ public string City => this.cityName;
- public string Country
- { get { return this.countryName; } }
+ public string Country => this.countryName;
- public int Population
- { get { return this.pop2010; } }
+ public int Population => this.pop2010;
- public static int CompareByName(CityInfo city1, CityInfo city2)
- {
- return String.Compare(city1.City, city2.City);
- }
+ public static int CompareByName(CityInfo city1, CityInfo city2) => string.Compare(city1.City, city2.City);
- public static int CompareByPopulation(CityInfo city1, CityInfo city2)
- {
- return city1.Population.CompareTo(city2.Population);
- }
+ public static int CompareByPopulation(CityInfo city1, CityInfo city2) => city1.Population.CompareTo(city2.Population);
- public static int CompareByNames(CityInfo city1, CityInfo city2)
- {
- return String.Compare(city1.Country + city1.City, city2.Country + city2.City);
- }
+ public static int CompareByNames(CityInfo city1, CityInfo city2) => string.Compare(city1.Country + city1.City, city2.Country + city2.City);
}
-public class Example
+public class ComparisonTOverviewExample1
{
- public static void Main()
- {
- CityInfo NYC = new CityInfo("New York City", "United States of America", 8175133 );
- CityInfo Det = new CityInfo("Detroit", "United States of America", 713777);
- CityInfo Paris = new CityInfo("Paris", "France", 2193031);
- CityInfo[] cities = { NYC, Det, Paris };
- // Display ordered array.
- DisplayArray(cities);
+ public static void Run()
+ {
+ CityInfo NYC = new("New York City", "United States of America", 8175133);
+ CityInfo Det = new("Detroit", "United States of America", 713777);
+ CityInfo Paris = new("Paris", "France", 2193031);
+ CityInfo[] cities = { NYC, Det, Paris };
+ // Display ordered array.
+ DisplayArray(cities);
- // Sort array by city name.
- Array.Sort(cities, CityInfo.CompareByName);
- DisplayArray(cities);
+ // Sort array by city name.
+ Array.Sort(cities, CityInfo.CompareByName);
+ DisplayArray(cities);
- // Sort array by population.
- Array.Sort(cities, CityInfo.CompareByPopulation);
- DisplayArray(cities);
+ // Sort array by population.
+ Array.Sort(cities, CityInfo.CompareByPopulation);
+ DisplayArray(cities);
- // Sort array by country + city name.
- Array.Sort(cities, CityInfo.CompareByNames);
- DisplayArray(cities);
- }
+ // Sort array by country + city name.
+ Array.Sort(cities, CityInfo.CompareByNames);
+ DisplayArray(cities);
+ }
- private static void DisplayArray(CityInfo[] cities)
- {
- Console.WriteLine("{0,-20} {1,-25} {2,10}", "City", "Country", "Population");
- foreach (var city in cities)
- Console.WriteLine("{0,-20} {1,-25} {2,10:N0}", city.City,
- city.Country, city.Population);
+ private static void DisplayArray(CityInfo[] cities)
+ {
+ Console.WriteLine($"{"City",-20} {"Country",-25} {"Population",10}");
+ foreach (var city in cities)
+ Console.WriteLine($"{city.City,-20} {city.Country,-25} {city.Population,10:N0}");
- Console.WriteLine();
- }
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// City Country Population
diff --git a/snippets/csharp/System/ComparisonT/Overview/source.cs b/snippets/csharp/System/ComparisonT/Overview/source.cs
index 4ffc0ed59bb..ded501522c8 100644
--- a/snippets/csharp/System/ComparisonT/Overview/source.cs
+++ b/snippets/csharp/System/ComparisonT/Overview/source.cs
@@ -2,7 +2,7 @@
using System;
using System.Collections.Generic;
-public class Example
+public class ComparisonTOverviewExample2
{
private static int CompareDinosByLength(string x, string y)
{
@@ -26,7 +26,7 @@ private static int CompareDinosByLength(string x, string y)
// If x is not null...
//
if (y == null)
- // ...and y is null, x is greater.
+ // ...and y is null, x is greater.
{
return 1;
}
@@ -55,15 +55,17 @@ private static int CompareDinosByLength(string x, string y)
}
}
- public static void Main()
+ public static void Run()
{
- List dinosaurs = new List();
- dinosaurs.Add("Pachycephalosaurus");
- dinosaurs.Add("Amargasaurus");
- dinosaurs.Add("");
- dinosaurs.Add(null);
- dinosaurs.Add("Mamenchisaurus");
- dinosaurs.Add("Deinonychus");
+ List dinosaurs = new()
+ {
+ "Pachycephalosaurus",
+ "Amargasaurus",
+ "",
+ null,
+ "Mamenchisaurus",
+ "Deinonychus"
+ };
Display(dinosaurs);
Console.WriteLine("\nSort with generic Comparison delegate:");
@@ -74,12 +76,12 @@ public static void Main()
private static void Display(List list)
{
Console.WriteLine();
- foreach( string s in list )
+ foreach (string s in list)
{
if (s == null)
Console.WriteLine("(null)");
else
- Console.WriteLine("\"{0}\"", s);
+ Console.WriteLine($"\"{s}\"");
}
}
}
diff --git a/snippets/csharp/System/LazyT/.ctor/Program.cs b/snippets/csharp/System/LazyT/.ctor/Program.cs
new file mode 100644
index 00000000000..18d5981ecf8
--- /dev/null
+++ b/snippets/csharp/System/LazyT/.ctor/Program.cs
@@ -0,0 +1,6 @@
+LazyCtorExample1.Run();
+LazyCtorExample2.Run();
+LazyCtorExample3.Run();
+LazyCtorExample4.Run();
+LazyCtorExample5.Run();
+LazyCtorExample6.Run();
diff --git a/snippets/csharp/System/LazyT/.ctor/Project.csproj b/snippets/csharp/System/LazyT/.ctor/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/LazyT/.ctor/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/LazyT/.ctor/example.cs b/snippets/csharp/System/LazyT/.ctor/example.cs
index 53baccaab31..910c9e28ba5 100644
--- a/snippets/csharp/System/LazyT/.ctor/example.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example.cs
@@ -1,12 +1,13 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample1;
-class Program
+class LazyCtorExample1
{
static Lazy lazyLargeObject = null;
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -25,7 +26,7 @@ static void Main()
Console.ReadLine();
// Create and start 3 threads, passing the same blocking event to all of them.
- ManualResetEvent startingGate = new ManualResetEvent(false);
+ ManualResetEvent startingGate = new(false);
Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) };
foreach (Thread t in threads)
{
@@ -49,7 +50,7 @@ static void Main()
static void ThreadProc(object state)
{
// Wait for the signal.
- ManualResetEvent waitForStart = (ManualResetEvent) state;
+ ManualResetEvent waitForStart = (ManualResetEvent)state;
waitForStart.WaitOne();
//
@@ -62,7 +63,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
@@ -71,12 +72,12 @@ static void ThreadProc(object state)
}
}
-class LargeObject
+class LargeObjectCtorExample1
{
int initBy = 0;
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
- public LargeObject()
+ public LargeObjectCtorExample1()
{
initBy = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("LargeObject was created on thread id {0}.", initBy);
diff --git a/snippets/csharp/System/LazyT/.ctor/example1.cs b/snippets/csharp/System/LazyT/.ctor/example1.cs
index d05e301ad74..d7938abc811 100644
--- a/snippets/csharp/System/LazyT/.ctor/example1.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example1.cs
@@ -1,12 +1,13 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample2;
-class Program
+class LazyCtorExample2
{
static Lazy lazyLargeObject = null;
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -34,13 +35,9 @@ static void Main()
}
}
-class LargeObject
+class LargeObjectCtorExample2
{
- public LargeObject()
- {
- Console.WriteLine("LargeObject was created on thread id {0}.",
- Thread.CurrentThread.ManagedThreadId);
- }
+ public LargeObjectCtorExample2() => Console.WriteLine($"LargeObject was created on thread id {Thread.CurrentThread.ManagedThreadId}.");
public long[] Data = new long[100000000];
}
diff --git a/snippets/csharp/System/LazyT/.ctor/example2.cs b/snippets/csharp/System/LazyT/.ctor/example2.cs
index 94f0bac084e..b2e3f48919e 100644
--- a/snippets/csharp/System/LazyT/.ctor/example2.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example2.cs
@@ -1,19 +1,17 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample3;
-class Program
+class LazyCtorExample3
{
static Lazy lazyLargeObject = null;
//
- static LargeObject InitLargeObject()
- {
- return new LargeObject();
- }
+ static LargeObject InitLargeObject() => new LargeObject();
//
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -58,7 +56,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
@@ -67,20 +65,20 @@ static void ThreadProc(object state)
}
catch (ApplicationException aex)
{
- Console.WriteLine("Exception: {0}", aex.Message);
+ Console.WriteLine($"Exception: {aex.Message}");
}
//
}
}
-class LargeObject
+class LargeObjectCtorExample3
{
int initBy = 0;
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
//
static int instanceCount = 0;
- public LargeObject()
+ public LargeObjectCtorExample3()
{
if (1 == Interlocked.Increment(ref instanceCount))
{
diff --git a/snippets/csharp/System/LazyT/.ctor/example3.cs b/snippets/csharp/System/LazyT/.ctor/example3.cs
index 634f125726b..2588d098243 100644
--- a/snippets/csharp/System/LazyT/.ctor/example3.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example3.cs
@@ -1,19 +1,17 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample4;
-class Program
+class LazyCtorExample4
{
static Lazy lazyLargeObject = null;
//
- static LargeObject InitLargeObject()
- {
- return new LargeObject();
- }
+ static LargeObject InitLargeObject() => new LargeObject();
//
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -40,7 +38,7 @@ static void Main()
}
catch (ApplicationException aex)
{
- Console.WriteLine("Exception: {0}", aex.Message);
+ Console.WriteLine($"Exception: {aex.Message}");
}
}
//
@@ -50,11 +48,11 @@ static void Main()
}
}
-class LargeObject
+class LargeObjectCtorExample4
{
//
static bool pleaseThrow = true;
- public LargeObject()
+ public LargeObjectCtorExample4()
{
if (pleaseThrow)
{
@@ -62,8 +60,7 @@ public LargeObject()
throw new ApplicationException("Throw only ONCE.");
}
- Console.WriteLine("LargeObject was created on thread id {0}.",
- Thread.CurrentThread.ManagedThreadId);
+ Console.WriteLine($"LargeObject was created on thread id {Thread.CurrentThread.ManagedThreadId}.");
}
//
public long[] Data = new long[100000000];
diff --git a/snippets/csharp/System/LazyT/.ctor/example4.cs b/snippets/csharp/System/LazyT/.ctor/example4.cs
index 768f57b38ea..6c97044e88e 100644
--- a/snippets/csharp/System/LazyT/.ctor/example4.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example4.cs
@@ -1,8 +1,9 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample5;
-class Program
+class LazyCtorExample5
{
static Lazy lazyLargeObject = null;
@@ -14,14 +15,13 @@ static LargeObject InitLargeObject()
if (1 == Interlocked.Increment(ref instanceCount))
{
throw new ApplicationException(
- String.Format("Lazy initialization function failed on thread {0}.",
- Thread.CurrentThread.ManagedThreadId));
+ $"Lazy initialization function failed on thread {Thread.CurrentThread.ManagedThreadId}.");
}
return new LargeObject(Thread.CurrentThread.ManagedThreadId);
}
//
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -31,7 +31,7 @@ static void Main()
//
// Create and start 3 threads, passing the same blocking event to all of them.
- ManualResetEvent startingGate = new ManualResetEvent(false);
+ ManualResetEvent startingGate = new(false);
Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) };
foreach (Thread t in threads)
{
@@ -64,7 +64,7 @@ static void Main()
static void ThreadProc(object state)
{
// Wait for the signal.
- ManualResetEvent waitForStart = (ManualResetEvent) state;
+ ManualResetEvent waitForStart = (ManualResetEvent)state;
waitForStart.WaitOne();
//
@@ -79,7 +79,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("LargeObject was initialized by thread {0}; last used by thread {1}.",
@@ -88,28 +88,25 @@ static void ThreadProc(object state)
}
catch (ApplicationException ex)
{
- Console.WriteLine("ApplicationException: {0}", ex.Message);
+ Console.WriteLine($"ApplicationException: {ex.Message}");
}
//
}
}
-class LargeObject
+class LargeObjectCtorExample5
{
int initBy = -1;
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
//
- public LargeObject(int initializedBy)
+ public LargeObjectCtorExample5(int initializedBy)
{
initBy = initializedBy;
Console.WriteLine("Constructor: Instance initializing on thread {0}", initBy);
}
- ~LargeObject()
- {
- Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy);
- }
+ ~LargeObjectCtorExample5() => Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy);
//
public long[] Data = new long[100000000];
diff --git a/snippets/csharp/System/LazyT/.ctor/example5.cs b/snippets/csharp/System/LazyT/.ctor/example5.cs
index 8e3403efd25..b6335414466 100644
--- a/snippets/csharp/System/LazyT/.ctor/example5.cs
+++ b/snippets/csharp/System/LazyT/.ctor/example5.cs
@@ -1,12 +1,13 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectCtorExample6;
-class Program
+class LazyCtorExample6
{
static Lazy lazyLargeObject = null;
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -15,7 +16,7 @@ static void Main()
//
// Create and start 3 threads, passing the same blocking event to all of them.
- ManualResetEvent startingGate = new ManualResetEvent(false);
+ ManualResetEvent startingGate = new(false);
Thread[] threads = { new Thread(ThreadProc), new Thread(ThreadProc), new Thread(ThreadProc) };
foreach (Thread t in threads)
{
@@ -49,7 +50,7 @@ static void Main()
static void ThreadProc(object state)
{
// Wait for the signal.
- ManualResetEvent waitForStart = (ManualResetEvent) state;
+ ManualResetEvent waitForStart = (ManualResetEvent)state;
waitForStart.WaitOne();
//
@@ -63,7 +64,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("LargeObject was initialized by thread {0}; last used by thread {1}.",
@@ -72,22 +73,19 @@ static void ThreadProc(object state)
}
}
-class LargeObject
+class LargeObjectCtorExample6
{
int initBy = -1;
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
//
- public LargeObject()
+ public LargeObjectCtorExample6()
{
initBy = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Constructor: Instance initializing on thread {0}", initBy);
}
- ~LargeObject()
- {
- Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy);
- }
+ ~LargeObjectCtorExample6() => Console.WriteLine("Finalizer: Instance was initialized on {0}", initBy);
//
public long[] Data = new long[100000000];
diff --git a/snippets/csharp/System/LazyT/Overview/Program.cs b/snippets/csharp/System/LazyT/Overview/Program.cs
new file mode 100644
index 00000000000..22896b8011d
--- /dev/null
+++ b/snippets/csharp/System/LazyT/Overview/Program.cs
@@ -0,0 +1,2 @@
+LazyOverviewExample1.Run();
+LazyOverviewExample2.Run();
diff --git a/snippets/csharp/System/LazyT/Overview/Project.csproj b/snippets/csharp/System/LazyT/Overview/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/LazyT/Overview/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/LazyT/Overview/example.cs b/snippets/csharp/System/LazyT/Overview/example.cs
index a5be10f8635..c61c673e31a 100644
--- a/snippets/csharp/System/LazyT/Overview/example.cs
+++ b/snippets/csharp/System/LazyT/Overview/example.cs
@@ -1,21 +1,22 @@
//
using System;
using System.Threading;
+using LargeObject = LargeObjectOverviewExample1;
-class Program
+class LazyOverviewExample1
{
static Lazy lazyLargeObject = null;
//
static LargeObject InitLargeObject()
{
- LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
+ LargeObject large = new(Thread.CurrentThread.ManagedThreadId);
// Perform additional initialization here.
return large;
}
//
- static void Main()
+ public static void Run()
{
// The lazy initializer is created here. LargeObject is not created until the
// ThreadProc method executes.
@@ -38,7 +39,7 @@ static void Main()
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
- threads[i] = new Thread(ThreadProc);
+ threads[i] = new(ThreadProc);
threads[i].Start();
}
@@ -60,7 +61,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
@@ -70,13 +71,13 @@ static void ThreadProc(object state)
}
}
-class LargeObject
+class LargeObjectOverviewExample1
{
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
//
int initBy = 0;
- public LargeObject(int initializedBy)
+ public LargeObjectOverviewExample1(int initializedBy)
{
initBy = initializedBy;
Console.WriteLine("LargeObject was created on thread id {0}.", initBy);
diff --git a/snippets/csharp/System/LazyT/Overview/lambda.cs b/snippets/csharp/System/LazyT/Overview/lambda.cs
index 2067f9837bd..e9939c4b39a 100644
--- a/snippets/csharp/System/LazyT/Overview/lambda.cs
+++ b/snippets/csharp/System/LazyT/Overview/lambda.cs
@@ -1,16 +1,17 @@
using System;
using System.Threading;
+using LargeObject = LargeObjectOverviewExample2;
-class Program
+class LazyOverviewExample2
{
static Lazy lazyLargeObject = null;
- static void Main()
+ public static void Run()
{
//
lazyLargeObject = new Lazy(() =>
{
- LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
+ LargeObject large = new(Thread.CurrentThread.ManagedThreadId);
// Perform additional initialization here.
return large;
});
@@ -25,7 +26,7 @@ static void Main()
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
- threads[i] = new Thread(ThreadProc);
+ threads[i] = new(ThreadProc);
threads[i].Start();
}
@@ -46,7 +47,7 @@ static void ThreadProc(object state)
// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
// object after creation. You must lock the object before accessing it,
// unless the type is thread safe. (LargeObject is not thread safe.)
- lock(large)
+ lock (large)
{
large.Data[0] = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
@@ -55,12 +56,12 @@ static void ThreadProc(object state)
}
}
-class LargeObject
+class LargeObjectOverviewExample2
{
- public int InitializedBy { get { return initBy; } }
+ public int InitializedBy => initBy;
int initBy = 0;
- public LargeObject(int initializedBy)
+ public LargeObjectOverviewExample2(int initializedBy)
{
initBy = initializedBy;
Console.WriteLine("LargeObject was created on thread id {0}.", initBy);
diff --git a/snippets/csharp/System/Math/Abs/Abs1.cs b/snippets/csharp/System/Math/Abs/Abs1.cs
index a8a3403f890..91ebdcecb62 100644
--- a/snippets/csharp/System/Math/Abs/Abs1.cs
+++ b/snippets/csharp/System/Math/Abs/Abs1.cs
@@ -1,21 +1,21 @@
using System;
-public class Example
+public class MathAbsExample1
{
- public static void Main()
- {
- //
- decimal[] decimals = { Decimal.MaxValue, 12.45M, 0M, -19.69M,
- Decimal.MinValue };
- foreach (decimal value in decimals)
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ public static void Run()
+ {
+ //
+ decimal[] decimals = { decimal.MaxValue, 12.45M, 0M, -19.69M,
+ decimal.MinValue };
+ foreach (decimal value in decimals)
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- // The example displays the following output:
- // Abs(79228162514264337593543950335) = 79228162514264337593543950335
- // Abs(12.45) = 12.45
- // Abs(0) = 0
- // Abs(-19.69) = 19.69
- // Abs(-79228162514264337593543950335) = 79228162514264337593543950335
- //
- }
+ // The example displays the following output:
+ // Abs(79228162514264337593543950335) = 79228162514264337593543950335
+ // Abs(12.45) = 12.45
+ // Abs(0) = 0
+ // Abs(-19.69) = 19.69
+ // Abs(-79228162514264337593543950335) = 79228162514264337593543950335
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/Program.cs b/snippets/csharp/System/Math/Abs/Program.cs
new file mode 100644
index 00000000000..98ae5302805
--- /dev/null
+++ b/snippets/csharp/System/Math/Abs/Program.cs
@@ -0,0 +1,7 @@
+MathAbsExample1.Run();
+MathAbsExample2.Run();
+MathAbsExample3.Run();
+MathAbsExample4.Run();
+MathAbsExample5.Run();
+MathAbsExample6.Run();
+MathAbsExample7.Run();
diff --git a/snippets/csharp/System/Math/Abs/Project.csproj b/snippets/csharp/System/Math/Abs/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/Math/Abs/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/Math/Abs/abs2.cs b/snippets/csharp/System/Math/Abs/abs2.cs
index 5c5bca5462a..bd0869db31e 100644
--- a/snippets/csharp/System/Math/Abs/abs2.cs
+++ b/snippets/csharp/System/Math/Abs/abs2.cs
@@ -1,23 +1,23 @@
using System;
-public class Example
+public class MathAbsExample2
{
- public static void Main()
- {
- //
- double[] doubles = { Double.MaxValue, 16.354e-17, 15.098123, 0,
- -19.069713, -15.058e18, Double.MinValue };
- foreach (double value in doubles)
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ public static void Run()
+ {
+ //
+ double[] doubles = { double.MaxValue, 16.354e-17, 15.098123, 0,
+ -19.069713, -15.058e18, double.MinValue };
+ foreach (double value in doubles)
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- // The example displays the following output:
- // Abs(1.79769313486232E+308) = 1.79769313486232E+308
- // Abs(1.6354E-16) = 1.6354E-16
- // Abs(15.098123) = 15.098123
- // Abs(0) = 0
- // Abs(-19.069713) = 19.069713
- // Abs(-1.5058E+19) = 1.5058E+19
- // Abs(-1.79769313486232E+308) = 1.79769313486232E+308
- //
- }
+ // The example displays the following output:
+ // Abs(1.79769313486232E+308) = 1.79769313486232E+308
+ // Abs(1.6354E-16) = 1.6354E-16
+ // Abs(15.098123) = 15.098123
+ // Abs(0) = 0
+ // Abs(-19.069713) = 19.069713
+ // Abs(-1.5058E+19) = 1.5058E+19
+ // Abs(-1.79769313486232E+308) = 1.79769313486232E+308
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/abs3.cs b/snippets/csharp/System/Math/Abs/abs3.cs
index b37c617cd7a..28275eb681c 100644
--- a/snippets/csharp/System/Math/Abs/abs3.cs
+++ b/snippets/csharp/System/Math/Abs/abs3.cs
@@ -1,28 +1,29 @@
using System;
-public class Example
+public class MathAbsExample3
{
- public static void Main()
- {
- //
- short[] values = { Int16.MaxValue, 10328, 0, -1476, Int16.MinValue };
- foreach (short value in values)
- {
- try {
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- }
- catch (OverflowException) {
- Console.WriteLine("Unable to calculate the absolute value of {0}.",
- value);
- }
- }
+ public static void Run()
+ {
+ //
+ short[] values = { short.MaxValue, 10328, 0, -1476, short.MinValue };
+ foreach (short value in values)
+ {
+ try
+ {
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Unable to calculate the absolute value of {value}.");
+ }
+ }
- // The example displays the following output:
- // Abs(32767) = 32767
- // Abs(10328) = 10328
- // Abs(0) = 0
- // Abs(-1476) = 1476
- // Unable to calculate the absolute value of -32768.
- //
- }
+ // The example displays the following output:
+ // Abs(32767) = 32767
+ // Abs(10328) = 10328
+ // Abs(0) = 0
+ // Abs(-1476) = 1476
+ // Unable to calculate the absolute value of -32768.
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/abs4.cs b/snippets/csharp/System/Math/Abs/abs4.cs
index dea56d9505d..e3138e4b8ae 100644
--- a/snippets/csharp/System/Math/Abs/abs4.cs
+++ b/snippets/csharp/System/Math/Abs/abs4.cs
@@ -1,28 +1,29 @@
using System;
-public class Example
+public class MathAbsExample4
{
- public static void Main()
- {
- //
- int[] values = { Int32.MaxValue, 16921, 0, -804128, Int32.MinValue };
- foreach (int value in values)
- {
- try {
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- }
- catch (OverflowException) {
- Console.WriteLine("Unable to calculate the absolute value of {0}.",
- value);
- }
- }
+ public static void Run()
+ {
+ //
+ int[] values = { int.MaxValue, 16921, 0, -804128, int.MinValue };
+ foreach (int value in values)
+ {
+ try
+ {
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Unable to calculate the absolute value of {value}.");
+ }
+ }
- // The example displays the following output:
- // Abs(2147483647) = 2147483647
- // Abs(16921) = 16921
- // Abs(0) = 0
- // Abs(-804128) = 804128
- // Unable to calculate the absolute value of -2147483648.
- //
- }
+ // The example displays the following output:
+ // Abs(2147483647) = 2147483647
+ // Abs(16921) = 16921
+ // Abs(0) = 0
+ // Abs(-804128) = 804128
+ // Unable to calculate the absolute value of -2147483648.
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/abs5.cs b/snippets/csharp/System/Math/Abs/abs5.cs
index 99dd0159d3a..410a8ef34b6 100644
--- a/snippets/csharp/System/Math/Abs/abs5.cs
+++ b/snippets/csharp/System/Math/Abs/abs5.cs
@@ -1,28 +1,29 @@
using System;
-public class Example
+public class MathAbsExample5
{
- public static void Main()
- {
- //
- long[] values = { Int64.MaxValue, 109013, 0, -6871982, Int64.MinValue };
- foreach (long value in values)
- {
- try {
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- }
- catch (OverflowException) {
- Console.WriteLine("Unable to calculate the absolute value of {0}.",
- value);
- }
- }
+ public static void Run()
+ {
+ //
+ long[] values = { long.MaxValue, 109013, 0, -6871982, long.MinValue };
+ foreach (long value in values)
+ {
+ try
+ {
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Unable to calculate the absolute value of {value}.");
+ }
+ }
- // The example displays the following output:
- // Abs(9223372036854775807) = 9223372036854775807
- // Abs(109013) = 109013
- // Abs(0) = 0
- // Abs(-6871982) = 6871982
- // Unable to calculate the absolute value of -9223372036854775808.
- //
- }
+ // The example displays the following output:
+ // Abs(9223372036854775807) = 9223372036854775807
+ // Abs(109013) = 109013
+ // Abs(0) = 0
+ // Abs(-6871982) = 6871982
+ // Unable to calculate the absolute value of -9223372036854775808.
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/abs6.cs b/snippets/csharp/System/Math/Abs/abs6.cs
index ab5cf586f80..b617e930716 100644
--- a/snippets/csharp/System/Math/Abs/abs6.cs
+++ b/snippets/csharp/System/Math/Abs/abs6.cs
@@ -1,28 +1,29 @@
using System;
-public class Example
+public class MathAbsExample6
{
- public static void Main()
+ public static void Run()
{
- //
- sbyte[] values = { SByte.MaxValue, 98, 0, -32, SByte.MinValue };
- foreach (sbyte value in values)
- {
- try {
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- }
- catch (OverflowException) {
- Console.WriteLine("Unable to calculate the absolute value of {0}.",
- value);
- }
- }
+ //
+ sbyte[] values = { sbyte.MaxValue, 98, 0, -32, sbyte.MinValue };
+ foreach (sbyte value in values)
+ {
+ try
+ {
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Unable to calculate the absolute value of {value}.");
+ }
+ }
- // The example displays the following output:
- // Abs(127) = 127
- // Abs(98) = 98
- // Abs(0) = 0
- // Abs(-32) = 32
- // Unable to calculate the absolute value of -128.
- //
- }
+ // The example displays the following output:
+ // Abs(127) = 127
+ // Abs(98) = 98
+ // Abs(0) = 0
+ // Abs(-32) = 32
+ // Unable to calculate the absolute value of -128.
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Abs/abs7.cs b/snippets/csharp/System/Math/Abs/abs7.cs
index 7ea386cde58..b2d0c1b70b4 100644
--- a/snippets/csharp/System/Math/Abs/abs7.cs
+++ b/snippets/csharp/System/Math/Abs/abs7.cs
@@ -1,23 +1,23 @@
using System;
-public class Example
+public class MathAbsExample7
{
- public static void Main()
- {
- //
- float[] values= { Single.MaxValue, 16.354e-12F, 15.098123F, 0F,
- -19.069713F, -15.058e17F, Single.MinValue };
- foreach (float value in values)
- Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
+ public static void Run()
+ {
+ //
+ float[] values = { float.MaxValue, 16.354e-12F, 15.098123F, 0F,
+ -19.069713F, -15.058e17F, float.MinValue };
+ foreach (float value in values)
+ Console.WriteLine($"Abs({value}) = {Math.Abs(value)}");
- // The example displays the following output:
- // Abs(3.402823E+38) = 3.402823E+38
- // Abs(1.6354E-11) = 1.6354E-11
- // Abs(15.09812) = 15.09812
- // Abs(0) = 0
- // Abs(-19.06971) = 19.06971
- // Abs(-1.5058E+18) = 1.5058E+18
- // Abs(-3.402823E+38) = 3.402823E+38
- //
- }
+ // The example displays the following output:
+ // Abs(3.402823E+38) = 3.402823E+38
+ // Abs(1.6354E-11) = 1.6354E-11
+ // Abs(15.09812) = 15.09812
+ // Abs(0) = 0
+ // Abs(-19.06971) = 19.06971
+ // Abs(-1.5058E+18) = 1.5058E+18
+ // Abs(-3.402823E+38) = 3.402823E+38
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Atan/atan.cs b/snippets/csharp/System/Math/Atan/atan.cs
index 0880e906d89..b50dacd3be6 100644
--- a/snippets/csharp/System/Math/Atan/atan.cs
+++ b/snippets/csharp/System/Math/Atan/atan.cs
@@ -8,34 +8,34 @@ class Sample
{
public static void Main()
{
- double x = 1.0;
- double y = 2.0;
- double angle;
- double radians;
- double result;
-
-// Calculate the tangent of 30 degrees.
- angle = 30;
- radians = angle * (Math.PI/180);
- result = Math.Tan(radians);
- Console.WriteLine("The tangent of 30 degrees is {0}.", result);
-
-// Calculate the arctangent of the previous tangent.
- radians = Math.Atan(result);
- angle = radians * (180/Math.PI);
- Console.WriteLine("The previous tangent is equivalent to {0} degrees.", angle);
-
-// Calculate the arctangent of an angle.
- String line1 = "{0}The arctangent of the angle formed by the x-axis and ";
- String line2 = "a vector to point ({0},{1}) is {2}, ";
- String line3 = "which is equivalent to {0} degrees.";
-
- radians = Math.Atan2(y, x);
- angle = radians * (180/Math.PI);
-
- Console.WriteLine(line1, Environment.NewLine);
- Console.WriteLine(line2, x, y, radians);
- Console.WriteLine(line3, angle);
+ double x = 1.0;
+ double y = 2.0;
+ double angle;
+ double radians;
+ double result;
+
+ // Calculate the tangent of 30 degrees.
+ angle = 30;
+ radians = angle * (Math.PI / 180);
+ result = Math.Tan(radians);
+ Console.WriteLine($"The tangent of 30 degrees is {result}.");
+
+ // Calculate the arctangent of the previous tangent.
+ radians = Math.Atan(result);
+ angle = radians * (180 / Math.PI);
+ Console.WriteLine($"The previous tangent is equivalent to {angle} degrees.");
+
+ // Calculate the arctangent of an angle.
+ string line1 = "{0}The arctangent of the angle formed by the x-axis and ";
+ string line2 = "a vector to point ({0},{1}) is {2}, ";
+ string line3 = "which is equivalent to {0} degrees.";
+
+ radians = Math.Atan2(y, x);
+ angle = radians * (180 / Math.PI);
+
+ Console.WriteLine(line1, Environment.NewLine);
+ Console.WriteLine(line2, x, y, radians);
+ Console.WriteLine(line3, angle);
}
}
/*
@@ -48,4 +48,4 @@ The arctangent of the angle formed by the x-axis and
a vector to point (1,2) is 1.10714871779409,
which is equivalent to 63.434948822922 degrees.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Math/BigMul/bigmul.cs b/snippets/csharp/System/Math/BigMul/bigmul.cs
index 22b26ca9855..77bfae833d3 100644
--- a/snippets/csharp/System/Math/BigMul/bigmul.cs
+++ b/snippets/csharp/System/Math/BigMul/bigmul.cs
@@ -6,13 +6,13 @@ class Sample
{
public static void Main()
{
- int int1 = Int32.MaxValue;
- int int2 = Int32.MaxValue;
- long longResult;
-//
- longResult = Math.BigMul(int1, int2);
- Console.WriteLine("Calculate the product of two Int32 values:");
- Console.WriteLine("{0} * {1} = {2}", int1, int2, longResult);
+ int int1 = int.MaxValue;
+ int int2 = int.MaxValue;
+ long longResult;
+ //
+ longResult = Math.BigMul(int1, int2);
+ Console.WriteLine("Calculate the product of two Int32 values:");
+ Console.WriteLine($"{int1} * {int2} = {longResult}");
}
}
/*
@@ -20,4 +20,4 @@ public static void Main()
Calculate the product of two Int32 values:
2147483647 * 2147483647 = 4611686014132420609
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Math/Ceiling/Ceiling1.cs b/snippets/csharp/System/Math/Ceiling/Ceiling1.cs
index 0a49c4ecf24..e86a94c6527 100644
--- a/snippets/csharp/System/Math/Ceiling/Ceiling1.cs
+++ b/snippets/csharp/System/Math/Ceiling/Ceiling1.cs
@@ -2,50 +2,48 @@
public class Class1
{
- public static void Main()
- {
- CeilingWithDecimal();
- Console.WriteLine();
- CeilingWithDouble();
- }
+ public static void Main()
+ {
+ CeilingWithDecimal();
+ Console.WriteLine();
+ CeilingWithDouble();
+ }
- private static void CeilingWithDecimal()
- {
- //
- decimal[] values = {7.03m, 7.64m, 0.12m, -0.12m, -7.1m, -7.6m};
- Console.WriteLine(" Value Ceiling Floor\n");
- foreach (decimal value in values)
- Console.WriteLine("{0,7} {1,16} {2,14}",
- value, Math.Ceiling(value), Math.Floor(value));
- // The example displays the following output to the console:
- // Value Ceiling Floor
- //
- // 7.03 8 7
- // 7.64 8 7
- // 0.12 1 0
- // -0.12 0 -1
- // -7.1 -7 -8
- // -7.6 -7 -8
- //
- }
+ private static void CeilingWithDecimal()
+ {
+ //
+ decimal[] values = { 7.03m, 7.64m, 0.12m, -0.12m, -7.1m, -7.6m };
+ Console.WriteLine(" Value Ceiling Floor\n");
+ foreach (decimal value in values)
+ Console.WriteLine($"{value,7} {Math.Ceiling(value),16} {Math.Floor(value),14}");
+ // The example displays the following output to the console:
+ // Value Ceiling Floor
+ //
+ // 7.03 8 7
+ // 7.64 8 7
+ // 0.12 1 0
+ // -0.12 0 -1
+ // -7.1 -7 -8
+ // -7.6 -7 -8
+ //
+ }
- private static void CeilingWithDouble()
- {
- //
- double[] values = {7.03, 7.64, 0.12, -0.12, -7.1, -7.6};
- Console.WriteLine(" Value Ceiling Floor\n");
- foreach (double value in values)
- Console.WriteLine("{0,7} {1,16} {2,14}",
- value, Math.Ceiling(value), Math.Floor(value));
- // The example displays the following output to the console:
- // Value Ceiling Floor
- //
- // 7.03 8 7
- // 7.64 8 7
- // 0.12 1 0
- // -0.12 0 -1
- // -7.1 -7 -8
- // -7.6 -7 -8
- //
- }
+ private static void CeilingWithDouble()
+ {
+ //
+ double[] values = { 7.03, 7.64, 0.12, -0.12, -7.1, -7.6 };
+ Console.WriteLine(" Value Ceiling Floor\n");
+ foreach (double value in values)
+ Console.WriteLine($"{value,7} {Math.Ceiling(value),16} {Math.Floor(value),14}");
+ // The example displays the following output to the console:
+ // Value Ceiling Floor
+ //
+ // 7.03 8 7
+ // 7.64 8 7
+ // 0.12 1 0
+ // -0.12 0 -1
+ // -7.1 -7 -8
+ // -7.6 -7 -8
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Cos/sincos.cs b/snippets/csharp/System/Math/Cos/sincos.cs
index 6fdf596ae5c..3253a3b016f 100644
--- a/snippets/csharp/System/Math/Cos/sincos.cs
+++ b/snippets/csharp/System/Math/Cos/sincos.cs
@@ -10,14 +10,14 @@ public static void Main()
Console.WriteLine(
"This example of trigonometric " +
"Math.Sin( double ), Math.Cos( double ), and Math.SinCos( double )\n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Convert selected values for X to radians \n" +
- "and evaluate these trigonometric identities:" );
- Console.WriteLine( " sin^2(X) + cos^2(X) == 1\n" +
- " sin(2 * X) == 2 * sin(X) * cos(X)" );
- Console.WriteLine( " cos(2 * X) == cos^2(X) - sin^2(X)" );
- Console.WriteLine( " cos(2 * X) == cos^2(X) - sin^2(X)" );
+ "and evaluate these trigonometric identities:");
+ Console.WriteLine(" sin^2(X) + cos^2(X) == 1\n" +
+ " sin(2 * X) == 2 * sin(X) * cos(X)");
+ Console.WriteLine(" cos(2 * X) == cos^2(X) - sin^2(X)");
+ Console.WriteLine(" cos(2 * X) == cos^2(X) - sin^2(X)");
UseSineCosine(15.0);
UseSineCosine(30.0);
@@ -25,16 +25,16 @@ public static void Main()
Console.WriteLine(
"\nConvert selected values for X and Y to radians \n" +
- "and evaluate these trigonometric identities:" );
- Console.WriteLine( " sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y)" );
- Console.WriteLine( " cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y)" );
+ "and evaluate these trigonometric identities:");
+ Console.WriteLine(" sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y)");
+ Console.WriteLine(" cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y)");
UseTwoAngles(15.0, 30.0);
UseTwoAngles(30.0, 45.0);
Console.WriteLine(
"\nWhen you have calls to sin(X) and cos(X) they \n" +
- "can be replaced with a single call to sincos(x):" );
+ "can be replaced with a single call to sincos(x):");
UseCombinedSineCosine(15.0);
UseCombinedSineCosine(30.0);
@@ -48,21 +48,15 @@ static void UseCombinedSineCosine(double degrees)
(double sinAngle, double cosAngle) = Math.SinCos(angle);
// Evaluate sin^2(X) + cos^2(X) == 1.
- Console.WriteLine(
- "\n Math.SinCos({0} deg) == ({1:E16}, {2:E16})",
- degrees, sinAngle, cosAngle);
- Console.WriteLine(
- "(double sin, double cos) = Math.SinCos({0} deg)",
- degrees );
- Console.WriteLine(
- "sin^2 + cos^2 == {0:E16}",
- sinAngle * sinAngle + cosAngle * cosAngle );
+ Console.WriteLine($"\n Math.SinCos({degrees} deg) == ({sinAngle:E16}, {cosAngle:E16})");
+ Console.WriteLine($"(double sin, double cos) = Math.SinCos({degrees} deg)");
+ Console.WriteLine($"sin^2 + cos^2 == {sinAngle * sinAngle + cosAngle * cosAngle:E16}");
}
// Evaluate trigonometric identities with a given angle.
static void UseSineCosine(double degrees)
{
- double angle = Math.PI * degrees / 180.0;
+ double angle = Math.PI * degrees / 180.0;
double sinAngle = Math.Sin(angle);
double cosAngle = Math.Cos(angle);
@@ -70,33 +64,29 @@ static void UseSineCosine(double degrees)
Console.WriteLine(
"\n Math.Sin({0} deg) == {1:E16}\n" +
" Math.Cos({0} deg) == {2:E16}",
- degrees, Math.Sin(angle), Math.Cos(angle) );
+ degrees, Math.Sin(angle), Math.Cos(angle));
Console.WriteLine(
"(Math.Sin({0} deg))^2 + (Math.Cos({0} deg))^2 == {1:E16}",
- degrees, sinAngle * sinAngle + cosAngle * cosAngle );
+ degrees, sinAngle * sinAngle + cosAngle * cosAngle);
// Evaluate sin(2 * X) == 2 * sin(X) * cos(X).
- Console.WriteLine(
- " Math.Sin({0} deg) == {1:E16}",
- 2.0 * degrees, Math.Sin(2.0 * angle) );
+ Console.WriteLine($" Math.Sin({2.0 * degrees} deg) == {Math.Sin(2.0 * angle):E16}");
Console.WriteLine(
" 2 * Math.Sin({0} deg) * Math.Cos({0} deg) == {1:E16}",
- degrees, 2.0 * sinAngle * cosAngle );
+ degrees, 2.0 * sinAngle * cosAngle);
// Evaluate cos(2 * X) == cos^2(X) - sin^2(X).
- Console.WriteLine(
- " Math.Cos({0} deg) == {1:E16}",
- 2.0 * degrees, Math.Cos(2.0 * angle) );
+ Console.WriteLine($" Math.Cos({2.0 * degrees} deg) == {Math.Cos(2.0 * angle):E16}");
Console.WriteLine(
"(Math.Cos({0} deg))^2 - (Math.Sin({0} deg))^2 == {1:E16}",
- degrees, cosAngle * cosAngle - sinAngle * sinAngle );
+ degrees, cosAngle * cosAngle - sinAngle * sinAngle);
}
// Evaluate trigonometric identities that are functions of two angles.
static void UseTwoAngles(double degreesX, double degreesY)
{
- double angleX = Math.PI * degreesX / 180.0;
- double angleY = Math.PI * degreesY / 180.0;
+ double angleX = Math.PI * degreesX / 180.0;
+ double angleY = Math.PI * degreesY / 180.0;
// Evaluate sin(X + Y) == sin(X) * cos(Y) + cos(X) * sin(Y).
Console.WriteLine(
@@ -104,9 +94,7 @@ static void UseTwoAngles(double degreesX, double degreesY)
" Math.Cos({0} deg) * Math.Sin({1} deg) == {2:E16}",
degreesX, degreesY, Math.Sin(angleX) * Math.Cos(angleY) +
Math.Cos(angleX) * Math.Sin(angleY));
- Console.WriteLine(
- " Math.Sin({0} deg) == {1:E16}",
- degreesX + degreesY, Math.Sin(angleX + angleY));
+ Console.WriteLine($" Math.Sin({degreesX + degreesY} deg) == {Math.Sin(angleX + angleY):E16}");
// Evaluate cos(X + Y) == cos(X) * cos(Y) - sin(X) * sin(Y).
Console.WriteLine(
@@ -114,9 +102,7 @@ static void UseTwoAngles(double degreesX, double degreesY)
" Math.Sin({0} deg) * Math.Sin({1} deg) == {2:E16}",
degreesX, degreesY, Math.Cos(angleX) * Math.Cos(angleY) -
Math.Sin(angleX) * Math.Sin(angleY));
- Console.WriteLine(
- " Math.Cos({0} deg) == {1:E16}",
- degreesX + degreesY, Math.Cos(angleX + angleY));
+ Console.WriteLine($" Math.Cos({degreesX + degreesY} deg) == {Math.Cos(angleX + angleY):E16}");
}
}
diff --git a/snippets/csharp/System/Math/Cosh/sinhcosh.cs b/snippets/csharp/System/Math/Cosh/sinhcosh.cs
index 8649d0dcebb..d05396059d1 100644
--- a/snippets/csharp/System/Math/Cosh/sinhcosh.cs
+++ b/snippets/csharp/System/Math/Cosh/sinhcosh.cs
@@ -10,14 +10,14 @@ public static void Main()
Console.WriteLine(
"This example of hyperbolic Math.Sinh( double ) " +
"and Math.Cosh( double )\n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Evaluate these hyperbolic identities " +
- "with selected values for X:" );
+ "with selected values for X:");
Console.WriteLine(
" cosh^2(X) - sinh^2(X) == 1\n" +
- " sinh(2 * X) == 2 * sinh(X) * cosh(X)" );
- Console.WriteLine( " cosh(2 * X) == cosh^2(X) + sinh^2(X)" );
+ " sinh(2 * X) == 2 * sinh(X) * cosh(X)");
+ Console.WriteLine(" cosh(2 * X) == cosh^2(X) + sinh^2(X)");
UseSinhCosh(0.1);
UseSinhCosh(1.2);
@@ -25,11 +25,11 @@ public static void Main()
Console.WriteLine(
"\nEvaluate these hyperbolic identities " +
- "with selected values for X and Y:" );
+ "with selected values for X and Y:");
Console.WriteLine(
- " sinh(X + Y) == sinh(X) * cosh(Y) + cosh(X) * sinh(Y)" );
+ " sinh(X + Y) == sinh(X) * cosh(Y) + cosh(X) * sinh(Y)");
Console.WriteLine(
- " cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y)" );
+ " cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y)");
UseTwoArgs(0.1, 1.2);
UseTwoArgs(1.2, 4.9);
@@ -45,26 +45,22 @@ static void UseSinhCosh(double arg)
Console.WriteLine(
"\n Math.Sinh({0}) == {1:E16}\n" +
" Math.Cosh({0}) == {2:E16}",
- arg, Math.Sinh(arg), Math.Cosh(arg) );
+ arg, Math.Sinh(arg), Math.Cosh(arg));
Console.WriteLine(
"(Math.Cosh({0}))^2 - (Math.Sinh({0}))^2 == {1:E16}",
- arg, coshArg * coshArg - sinhArg * sinhArg );
+ arg, coshArg * coshArg - sinhArg * sinhArg);
// Evaluate sinh(2 * X) == 2 * sinh(X) * cosh(X).
- Console.WriteLine(
- " Math.Sinh({0}) == {1:E16}",
- 2.0 * arg, Math.Sinh(2.0 * arg) );
+ Console.WriteLine($" Math.Sinh({2.0 * arg}) == {Math.Sinh(2.0 * arg):E16}");
Console.WriteLine(
" 2 * Math.Sinh({0}) * Math.Cosh({0}) == {1:E16}",
- arg, 2.0 * sinhArg * coshArg );
+ arg, 2.0 * sinhArg * coshArg);
// Evaluate cosh(2 * X) == cosh^2(X) + sinh^2(X).
- Console.WriteLine(
- " Math.Cosh({0}) == {1:E16}",
- 2.0 * arg, Math.Cosh(2.0 * arg) );
+ Console.WriteLine($" Math.Cosh({2.0 * arg}) == {Math.Cosh(2.0 * arg):E16}");
Console.WriteLine(
"(Math.Cosh({0}))^2 + (Math.Sinh({0}))^2 == {1:E16}",
- arg, coshArg * coshArg + sinhArg * sinhArg );
+ arg, coshArg * coshArg + sinhArg * sinhArg);
}
// Evaluate hyperbolic identities that are functions of two arguments.
@@ -76,9 +72,7 @@ static void UseTwoArgs(double argX, double argY)
" Math.Cosh({0}) * Math.Sinh({1}) == {2:E16}",
argX, argY, Math.Sinh(argX) * Math.Cosh(argY) +
Math.Cosh(argX) * Math.Sinh(argY));
- Console.WriteLine(
- " Math.Sinh({0}) == {1:E16}",
- argX + argY, Math.Sinh(argX + argY));
+ Console.WriteLine($" Math.Sinh({argX + argY}) == {Math.Sinh(argX + argY):E16}");
// Evaluate cosh(X + Y) == cosh(X) * cosh(Y) + sinh(X) * sinh(Y).
Console.WriteLine(
@@ -86,9 +80,7 @@ static void UseTwoArgs(double argX, double argY)
" Math.Sinh({0}) * Math.Sinh({1}) == {2:E16}",
argX, argY, Math.Cosh(argX) * Math.Cosh(argY) +
Math.Sinh(argX) * Math.Sinh(argY));
- Console.WriteLine(
- " Math.Cosh({0}) == {1:E16}",
- argX + argY, Math.Cosh(argX + argY));
+ Console.WriteLine($" Math.Cosh({argX + argY}) == {Math.Cosh(argX + argY):E16}");
}
}
diff --git a/snippets/csharp/System/Math/DivRem/Program.cs b/snippets/csharp/System/Math/DivRem/Program.cs
new file mode 100644
index 00000000000..ee5f6f7ff64
--- /dev/null
+++ b/snippets/csharp/System/Math/DivRem/Program.cs
@@ -0,0 +1,2 @@
+MathDivRemExample1.Run();
+MathDivRemExample2.Run();
diff --git a/snippets/csharp/System/Math/DivRem/Project.csproj b/snippets/csharp/System/Math/DivRem/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/Math/DivRem/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/Math/DivRem/divrem1.cs b/snippets/csharp/System/Math/DivRem/divrem1.cs
index 43a2253f196..7a19186de57 100644
--- a/snippets/csharp/System/Math/DivRem/divrem1.cs
+++ b/snippets/csharp/System/Math/DivRem/divrem1.cs
@@ -1,27 +1,26 @@
//
using System;
-public class Example
+public class MathDivRemExample1
{
- public static void Main()
- {
- // Define several positive and negative dividends.
- int[] dividends = { Int32.MaxValue, 13952, 0, -14032,
- Int32.MinValue };
- // Define one positive and one negative divisor.
- int[] divisors = { 2000, -2000 };
+ public static void Run()
+ {
+ // Define several positive and negative dividends.
+ int[] dividends = { int.MaxValue, 13952, 0, -14032,
+ int.MinValue };
+ // Define one positive and one negative divisor.
+ int[] divisors = { 2000, -2000 };
- foreach (int divisor in divisors)
- {
- foreach (int dividend in dividends)
- {
- int remainder;
- int quotient = Math.DivRem(dividend, divisor, out remainder);
- Console.WriteLine(@"{0:N0} \ {1:N0} = {2:N0}, remainder {3:N0}",
- dividend, divisor, quotient, remainder);
- }
- }
- }
+ foreach (int divisor in divisors)
+ {
+ foreach (int dividend in dividends)
+ {
+ int remainder;
+ int quotient = Math.DivRem(dividend, divisor, out remainder);
+ Console.WriteLine($"{dividend:N0} \\ {divisor:N0} = {quotient:N0}, remainder {remainder:N0}");
+ }
+ }
+ }
}
// The example displays the following output:
// 2,147,483,647 \ 2,000 = 1,073,741, remainder 1,647
diff --git a/snippets/csharp/System/Math/DivRem/divrem2.cs b/snippets/csharp/System/Math/DivRem/divrem2.cs
index 9fddf00056d..80c7dde90c2 100644
--- a/snippets/csharp/System/Math/DivRem/divrem2.cs
+++ b/snippets/csharp/System/Math/DivRem/divrem2.cs
@@ -1,27 +1,26 @@
//
using System;
-public class Example
+public class MathDivRemExample2
{
- public static void Main()
- {
- // Define several positive and negative dividends.
- long[] dividends = { Int64.MaxValue, 13952, 0, -14032,
- Int64.MinValue };
- // Define one positive and one negative divisor.
- long[] divisors = { 2000, -2000 };
+ public static void Run()
+ {
+ // Define several positive and negative dividends.
+ long[] dividends = { long.MaxValue, 13952, 0, -14032,
+ long.MinValue };
+ // Define one positive and one negative divisor.
+ long[] divisors = { 2000, -2000 };
- foreach (long divisor in divisors)
- {
- foreach (long dividend in dividends)
- {
- long remainder;
- long quotient = Math.DivRem(dividend, divisor, out remainder);
- Console.WriteLine(@"{0:N0} \ {1:N0} = {2:N0}, remainder {3:N0}",
- dividend, divisor, quotient, remainder);
- }
- }
- }
+ foreach (long divisor in divisors)
+ {
+ foreach (long dividend in dividends)
+ {
+ long remainder;
+ long quotient = Math.DivRem(dividend, divisor, out remainder);
+ Console.WriteLine($"{dividend:N0} \\ {divisor:N0} = {quotient:N0}, remainder {remainder:N0}");
+ }
+ }
+ }
}
// The example displays the following output:
// 9,223,372,036,854,775,807 \ 2,000 = 4,611,686,018,427,387, remainder 1,807
diff --git a/snippets/csharp/System/Math/E/efield.cs b/snippets/csharp/System/Math/E/efield.cs
index 73050c9fe3d..82eb0c73319 100644
--- a/snippets/csharp/System/Math/E/efield.cs
+++ b/snippets/csharp/System/Math/E/efield.cs
@@ -9,13 +9,13 @@ public static void Main()
Console.WriteLine(
"This example of Math.E == {0:E16}\n" +
"generates the following output.\n",
- Math.E );
+ Math.E);
Console.WriteLine(
- "Define the power series PS(n) = Sum(k->0,n)[1/k!]" );
- Console.WriteLine( " (limit n->infinity)PS(n) == e" );
+ "Define the power series PS(n) = Sum(k->0,n)[1/k!]");
+ Console.WriteLine(" (limit n->infinity)PS(n) == e");
Console.WriteLine(
"Display PS(n) and Math.E - PS(n), " +
- "and stop when delta < 1.0E-15\n" );
+ "and stop when delta < 1.0E-15\n");
CalcPowerSeries();
}
@@ -28,17 +28,17 @@ static void CalcPowerSeries()
// Stop iterating when the series converges,
// and prevent a runaway process.
- for( int n = 0; n < 999 && Math.Abs( Math.E - PS ) > 1.0E-15; n++ )
+ for (int n = 0; n < 999 && Math.Abs(Math.E - PS) > 1.0E-15; n++)
{
// Calculate a running factorial.
- if( n > 0 )
+ if (n > 0)
factorial *= (double)n;
// Calculate and display the power series.
PS += 1.0 / factorial;
Console.WriteLine(
"PS({0:D2}) == {1:E16}, Math.E - PS({0:D2}) == {2:E16}",
- n, PS, Math.E - PS );
+ n, PS, Math.E - PS);
}
}
}
diff --git a/snippets/csharp/System/Math/Exp/exp.cs b/snippets/csharp/System/Math/Exp/exp.cs
index d6d9d593d39..fae76c02a1c 100644
--- a/snippets/csharp/System/Math/Exp/exp.cs
+++ b/snippets/csharp/System/Math/Exp/exp.cs
@@ -8,10 +8,10 @@ public static void Main()
{
Console.WriteLine(
"This example of Math.Exp( double ) " +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Evaluate [e ^ ln(X) == ln(e ^ X) == X] " +
- "with selected values for X:" );
+ "with selected values for X:");
UseLnExp(0.1);
UseLnExp(1.2);
@@ -20,10 +20,10 @@ public static void Main()
Console.WriteLine(
"\nEvaluate these identities with " +
- "selected values for X and Y:" );
- Console.WriteLine( " (e ^ X) * (e ^ Y) == e ^ (X + Y)" );
- Console.WriteLine( " (e ^ X) ^ Y == e ^ (X * Y)" );
- Console.WriteLine( " X ^ Y == e ^ (Y * ln(X))" );
+ "selected values for X and Y:");
+ Console.WriteLine(" (e ^ X) * (e ^ Y) == e ^ (X + Y)");
+ Console.WriteLine(" (e ^ X) ^ Y == e ^ (X * Y)");
+ Console.WriteLine(" X ^ Y == e ^ (Y * ln(X))");
UseTwoArgs(0.1, 1.2);
UseTwoArgs(1.2, 4.9);
@@ -37,7 +37,7 @@ static void UseLnExp(double arg)
Console.WriteLine(
"\n Math.Exp(Math.Log({0})) == {1:E16}\n" +
" Math.Log(Math.Exp({0})) == {2:E16}",
- arg, Math.Exp(Math.Log(arg)), Math.Log(Math.Exp(arg)) );
+ arg, Math.Exp(Math.Log(arg)), Math.Log(Math.Exp(arg)));
}
// Evaluate exponential identities that are functions of two arguments.
@@ -48,21 +48,21 @@ static void UseTwoArgs(double argX, double argY)
"\nMath.Exp({0}) * Math.Exp({1}) == {2:E16}" +
"\n Math.Exp({0} + {1}) == {3:E16}",
argX, argY, Math.Exp(argX) * Math.Exp(argY),
- Math.Exp(argX + argY) );
+ Math.Exp(argX + argY));
// Evaluate (e ^ X) ^ Y == e ^ (X * Y).
Console.WriteLine(
" Math.Pow(Math.Exp({0}), {1}) == {2:E16}" +
"\n Math.Exp({0} * {1}) == {3:E16}",
argX, argY, Math.Pow(Math.Exp(argX), argY),
- Math.Exp(argX * argY) );
+ Math.Exp(argX * argY));
// Evaluate X ^ Y == e ^ (Y * ln(X)).
Console.WriteLine(
" Math.Pow({0}, {1}) == {2:E16}" +
"\nMath.Exp({1} * Math.Log({0})) == {3:E16}",
argX, argY, Math.Pow(argX, argY),
- Math.Exp(argY * Math.Log(argX)) );
+ Math.Exp(argY * Math.Log(argX)));
}
}
diff --git a/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs b/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs
index 9374237b135..8752e9cd3b0 100644
--- a/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs
+++ b/snippets/csharp/System/Math/IEEERemainder/ieeeremainder1.cs
@@ -3,29 +3,29 @@
public class Example
{
- public static void Main()
- {
- Console.WriteLine($"{"IEEERemainder",35} {"Remainder operator",20}");
- ShowRemainders(3, 2);
- ShowRemainders(4, 2);
- ShowRemainders(10, 3);
- ShowRemainders(11, 3);
- ShowRemainders(27, 4);
- ShowRemainders(28, 5);
- ShowRemainders(17.8, 4);
- ShowRemainders(17.8, 4.1);
- ShowRemainders(-16.3, 4.1);
- ShowRemainders(17.8, -4.1);
- ShowRemainders(-17.8, -4.1);
- }
+ public static void Main()
+ {
+ Console.WriteLine($"{"IEEERemainder",35} {"Remainder operator",20}");
+ ShowRemainders(3, 2);
+ ShowRemainders(4, 2);
+ ShowRemainders(10, 3);
+ ShowRemainders(11, 3);
+ ShowRemainders(27, 4);
+ ShowRemainders(28, 5);
+ ShowRemainders(17.8, 4);
+ ShowRemainders(17.8, 4.1);
+ ShowRemainders(-16.3, 4.1);
+ ShowRemainders(17.8, -4.1);
+ ShowRemainders(-17.8, -4.1);
+ }
- private static void ShowRemainders(double number1, double number2)
- {
- var formula = $"{number1} / {number2} = ";
- var ieeeRemainder = Math.IEEERemainder(number1, number2);
- var remainder = number1 % number2;
- Console.WriteLine($"{formula,-16} {ieeeRemainder,18} {remainder,20}");
- }
+ private static void ShowRemainders(double number1, double number2)
+ {
+ string formula = $"{number1} / {number2} = ";
+ double ieeeRemainder = Math.IEEERemainder(number1, number2);
+ double remainder = number1 % number2;
+ Console.WriteLine($"{formula,-16} {ieeeRemainder,18} {remainder,20}");
+ }
}
// The example displays the following output:
//
diff --git a/snippets/csharp/System/Math/Log10/log10.cs b/snippets/csharp/System/Math/Log10/log10.cs
index dbad2eab0c4..e9729e5f344 100644
--- a/snippets/csharp/System/Math/Log10/log10.cs
+++ b/snippets/csharp/System/Math/Log10/log10.cs
@@ -3,15 +3,14 @@
public class Example
{
- public static void Main()
- {
- double[] numbers = {-1, 0, .105, .5, .798, 1, 4, 6.9, 10, 50,
- 100, 500, 1000, Double.MaxValue};
+ public static void Main()
+ {
+ double[] numbers = {-1, 0, .105, .5, .798, 1, 4, 6.9, 10, 50,
+ 100, 500, 1000, double.MaxValue};
- foreach (double number in numbers)
- Console.WriteLine("The base 10 log of {0} is {1}.",
- number, Math.Log10(number));
- }
+ foreach (double number in numbers)
+ Console.WriteLine($"The base 10 log of {number} is {Math.Log10(number)}.");
+ }
}
// The example dislays the following output:
// The base 10 log of -1 is NaN.
diff --git a/snippets/csharp/System/Math/LogMethod/log1.cs b/snippets/csharp/System/Math/LogMethod/log1.cs
index 410533c711a..1900a3f40f3 100644
--- a/snippets/csharp/System/Math/LogMethod/log1.cs
+++ b/snippets/csharp/System/Math/LogMethod/log1.cs
@@ -2,26 +2,24 @@
using System;
public class Example
{
- public static void Main()
- {
- Console.WriteLine(" Evaluate this identity with selected values for X:");
- Console.WriteLine(" ln(x) = 1 / log[X](B)");
- Console.WriteLine();
+ public static void Main()
+ {
+ Console.WriteLine(" Evaluate this identity with selected values for X:");
+ Console.WriteLine(" ln(x) = 1 / log[X](B)");
+ Console.WriteLine();
- double[] XArgs = { 1.2, 4.9, 9.9, 0.1 };
+ double[] XArgs = { 1.2, 4.9, 9.9, 0.1 };
- foreach (double argX in XArgs)
- {
- // Find natural log of argX.
- Console.WriteLine(" Math.Log({0}) = {1:E16}",
- argX, Math.Log(argX));
+ foreach (double argX in XArgs)
+ {
+ // Find natural log of argX.
+ Console.WriteLine($" Math.Log({argX}) = {Math.Log(argX):E16}");
- // Evaluate 1 / log[X](e).
- Console.WriteLine(" 1.0 / Math.Log(e, {0}) = {1:E16}",
- argX, 1.0 / Math.Log(Math.E, argX));
- Console.WriteLine();
- }
- }
+ // Evaluate 1 / log[X](e).
+ Console.WriteLine($" 1.0 / Math.Log(e, {argX}) = {1.0 / Math.Log(Math.E, argX):E16}");
+ Console.WriteLine();
+ }
+ }
}
// This example displays the following output:
// Evaluate this identity with selected values for X:
diff --git a/snippets/csharp/System/Math/LogMethod/loggen.cs b/snippets/csharp/System/Math/LogMethod/loggen.cs
index bf1a7f94139..97f703e8f66 100644
--- a/snippets/csharp/System/Math/LogMethod/loggen.cs
+++ b/snippets/csharp/System/Math/LogMethod/loggen.cs
@@ -9,13 +9,13 @@ public static void Main()
Console.WriteLine(
"This example of Math.Log( double ) and " +
"Math.Log( double, double )\n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Evaluate these identities with " +
- "selected values for X and B (base):" );
- Console.WriteLine( " log(B)[X] == 1 / log(X)[B]" );
- Console.WriteLine( " log(B)[X] == ln[X] / ln[B]" );
- Console.WriteLine( " log(B)[X] == log(B)[e] * ln[X]" );
+ "selected values for X and B (base):");
+ Console.WriteLine(" log(B)[X] == 1 / log(X)[B]");
+ Console.WriteLine(" log(B)[X] == ln[X] / ln[B]");
+ Console.WriteLine(" log(B)[X] == log(B)[e] * ln[X]");
UseBaseAndArg(0.1, 1.2);
UseBaseAndArg(1.2, 4.9);
@@ -31,17 +31,15 @@ static void UseBaseAndArg(double argB, double argX)
"\n Math.Log({1}, {0}) == {2:E16}" +
"\n 1.0 / Math.Log({0}, {1}) == {3:E16}",
argB, argX, Math.Log(argX, argB),
- 1.0 / Math.Log(argB, argX) );
+ 1.0 / Math.Log(argB, argX));
// Evaluate log(B)[X] == ln[X] / ln[B].
Console.WriteLine(
" Math.Log({1}) / Math.Log({0}) == {2:E16}",
- argB, argX, Math.Log(argX) / Math.Log(argB) );
+ argB, argX, Math.Log(argX) / Math.Log(argB));
// Evaluate log(B)[X] == log(B)[e] * ln[X].
- Console.WriteLine(
- "Math.Log(Math.E, {0}) * Math.Log({1}) == {2:E16}",
- argB, argX, Math.Log(Math.E, argB) * Math.Log(argX) );
+ Console.WriteLine($"Math.Log(Math.E, {argB}) * Math.Log({argX}) == {Math.Log(Math.E, argB) * Math.Log(argX):E16}");
}
}
diff --git a/snippets/csharp/System/Math/Max/max.cs b/snippets/csharp/System/Math/Max/max.cs
index f499bab3433..6512795cf44 100644
--- a/snippets/csharp/System/Math/Max/max.cs
+++ b/snippets/csharp/System/Math/Max/max.cs
@@ -8,19 +8,19 @@ public static void Main()
//
string str = "{0}: The greater of {1,3} and {2,3} is {3}.";
- byte xByte1 = 1, xByte2 = 51;
- short xShort1 = -2, xShort2 = 52;
- int xInt1 = -3, xInt2 = 53;
- long xLong1 = -4, xLong2 = 54;
- float xSingle1 = 5.0f, xSingle2 = 55.0f;
- double xDouble1 = 6.0, xDouble2 = 56.0;
- Decimal xDecimal1 = 7m, xDecimal2 = 57m;
+ byte xByte1 = 1, xByte2 = 51;
+ short xShort1 = -2, xShort2 = 52;
+ int xInt1 = -3, xInt2 = 53;
+ long xLong1 = -4, xLong2 = 54;
+ float xSingle1 = 5.0f, xSingle2 = 55.0f;
+ double xDouble1 = 6.0, xDouble2 = 56.0;
+ decimal xDecimal1 = 7m, xDecimal2 = 57m;
// The following types are not CLS-compliant.
- sbyte xSbyte1 = 101, xSbyte2 = 111;
- ushort xUshort1 = 102, xUshort2 = 112;
- uint xUint1 = 103, xUint2 = 113;
- ulong xUlong1 = 104, xUlong2 = 114;
+ sbyte xSbyte1 = 101, xSbyte2 = 111;
+ ushort xUshort1 = 102, xUshort2 = 112;
+ uint xUint1 = 103, xUint2 = 113;
+ ulong xUlong1 = 104, xUlong2 = 114;
Console.WriteLine("Display the greater of two values:\n");
Console.WriteLine(str, "Byte ", xByte1, xByte2, Math.Max(xByte1, xByte2));
diff --git a/snippets/csharp/System/Math/Min/min.cs b/snippets/csharp/System/Math/Min/min.cs
index 9c790bb9a2c..223041e316a 100644
--- a/snippets/csharp/System/Math/Min/min.cs
+++ b/snippets/csharp/System/Math/Min/min.cs
@@ -8,19 +8,19 @@ public static void Main()
//
string str = "{0}: The lesser of {1,3} and {2,3} is {3}.";
- byte xByte1 = 1, xByte2 = 51;
- short xShort1 = -2, xShort2 = 52;
- int xInt1 = -3, xInt2 = 53;
- long xLong1 = -4, xLong2 = 54;
- float xSingle1 = 5.0f, xSingle2 = 55.0f;
- double xDouble1 = 6.0, xDouble2 = 56.0;
- Decimal xDecimal1 = 7m, xDecimal2 = 57m;
+ byte xByte1 = 1, xByte2 = 51;
+ short xShort1 = -2, xShort2 = 52;
+ int xInt1 = -3, xInt2 = 53;
+ long xLong1 = -4, xLong2 = 54;
+ float xSingle1 = 5.0f, xSingle2 = 55.0f;
+ double xDouble1 = 6.0, xDouble2 = 56.0;
+ decimal xDecimal1 = 7m, xDecimal2 = 57m;
// The following types are not CLS-compliant.
- sbyte xSbyte1 = 101, xSbyte2 = 111;
- ushort xUshort1 = 102, xUshort2 = 112;
- uint xUint1 = 103, xUint2 = 113;
- ulong xUlong1 = 104, xUlong2 = 114;
+ sbyte xSbyte1 = 101, xSbyte2 = 111;
+ ushort xUshort1 = 102, xUshort2 = 112;
+ uint xUint1 = 103, xUint2 = 113;
+ ulong xUlong1 = 104, xUlong2 = 114;
Console.WriteLine("Display the lesser of two values:\n");
Console.WriteLine(str, "Byte ", xByte1, xByte2, Math.Min(xByte1, xByte2));
diff --git a/snippets/csharp/System/Math/Overview/mathsample.cs b/snippets/csharp/System/Math/Overview/mathsample.cs
index b8fdb53179e..f9f3a108d7b 100644
--- a/snippets/csharp/System/Math/Overview/mathsample.cs
+++ b/snippets/csharp/System/Math/Overview/mathsample.cs
@@ -6,77 +6,71 @@
namespace MathClassCS
{
- class MathTrapezoidSample
- {
- private double m_longBase;
- private double m_shortBase;
- private double m_leftLeg;
- private double m_rightLeg;
+ class MathTrapezoidSample
+ {
+ private double m_longBase;
+ private double m_shortBase;
+ private double m_leftLeg;
+ private double m_rightLeg;
- public MathTrapezoidSample(double longbase, double shortbase, double leftLeg, double rightLeg)
- {
- m_longBase = Math.Abs(longbase);
- m_shortBase = Math.Abs(shortbase);
- m_leftLeg = Math.Abs(leftLeg);
- m_rightLeg = Math.Abs(rightLeg);
- }
+ public MathTrapezoidSample(double longbase, double shortbase, double leftLeg, double rightLeg)
+ {
+ m_longBase = Math.Abs(longbase);
+ m_shortBase = Math.Abs(shortbase);
+ m_leftLeg = Math.Abs(leftLeg);
+ m_rightLeg = Math.Abs(rightLeg);
+ }
- private double GetRightSmallBase()
- {
- return (Math.Pow(m_rightLeg,2.0) - Math.Pow(m_leftLeg,2.0) + Math.Pow(m_longBase,2.0) + Math.Pow(m_shortBase,2.0) - 2* m_shortBase * m_longBase)/ (2*(m_longBase - m_shortBase));
- }
+ private double GetRightSmallBase() => (Math.Pow(m_rightLeg, 2.0) - Math.Pow(m_leftLeg, 2.0) + Math.Pow(m_longBase, 2.0) + Math.Pow(m_shortBase, 2.0) - 2 * m_shortBase * m_longBase) / (2 * (m_longBase - m_shortBase));
- public double GetHeight()
- {
- double x = GetRightSmallBase();
- return Math.Sqrt(Math.Pow(m_rightLeg,2.0) - Math.Pow(x,2.0));
- }
+ public double GetHeight()
+ {
+ double x = GetRightSmallBase();
+ return Math.Sqrt(Math.Pow(m_rightLeg, 2.0) - Math.Pow(x, 2.0));
+ }
- public double GetSquare()
- {
- return GetHeight() * m_longBase / 2.0;
- }
+ public double GetSquare() => GetHeight() * m_longBase / 2.0;
- public double GetLeftBaseRadianAngle()
- {
- double sinX = GetHeight()/m_leftLeg;
- return Math.Round(Math.Asin(sinX),2);
- }
+ public double GetLeftBaseRadianAngle()
+ {
+ double sinX = GetHeight() / m_leftLeg;
+ return Math.Round(Math.Asin(sinX), 2);
+ }
- public double GetRightBaseRadianAngle()
- {
- double x = GetRightSmallBase();
- double cosX = (Math.Pow(m_rightLeg,2.0) + Math.Pow(x,2.0) - Math.Pow(GetHeight(),2.0))/(2*x*m_rightLeg);
- return Math.Round(Math.Acos(cosX),2);
- }
+ public double GetRightBaseRadianAngle()
+ {
+ double x = GetRightSmallBase();
+ double cosX = (Math.Pow(m_rightLeg, 2.0) + Math.Pow(x, 2.0) - Math.Pow(GetHeight(), 2.0)) / (2 * x * m_rightLeg);
+ return Math.Round(Math.Acos(cosX), 2);
+ }
- public double GetLeftBaseDegreeAngle()
- {
- double x = GetLeftBaseRadianAngle() * 180/ Math.PI;
- return Math.Round(x,2);
- }
+ public double GetLeftBaseDegreeAngle()
+ {
+ double x = GetLeftBaseRadianAngle() * 180 / Math.PI;
+ return Math.Round(x, 2);
+ }
- public double GetRightBaseDegreeAngle()
- {
- double x = GetRightBaseRadianAngle() * 180/ Math.PI;
- return Math.Round(x,2);
- }
+ public double GetRightBaseDegreeAngle()
+ {
+ double x = GetRightBaseRadianAngle() * 180 / Math.PI;
+ return Math.Round(x, 2);
+ }
- static void Main(string[] args)
- {
- MathTrapezoidSample trpz = new MathTrapezoidSample(20.0, 10.0, 8.0, 6.0);
- Console.WriteLine("The trapezoid's bases are 20.0 and 10.0, the trapezoid's legs are 8.0 and 6.0");
- double h = trpz.GetHeight();
- Console.WriteLine("Trapezoid height is: " + h.ToString());
- double dxR = trpz.GetLeftBaseRadianAngle();
- Console.WriteLine("Trapezoid left base angle is: " + dxR.ToString() + " Radians");
- double dyR = trpz.GetRightBaseRadianAngle();
- Console.WriteLine("Trapezoid right base angle is: " + dyR.ToString() + " Radians");
- double dxD = trpz.GetLeftBaseDegreeAngle();
- Console.WriteLine("Trapezoid left base angle is: " + dxD.ToString() + " Degrees");
- double dyD = trpz.GetRightBaseDegreeAngle();
- Console.WriteLine("Trapezoid right base angle is: " + dyD.ToString() + " Degrees");
- }
- }
+ static void Main(string[] args)
+ {
+ MathTrapezoidSample trpz = new(20.0, 10.0, 8.0, 6.0);
+ Console.WriteLine("The trapezoid's bases are 20.0 and 10.0, the trapezoid's legs are 8.0 and 6.0");
+ double h = trpz.GetHeight();
+ Console.WriteLine("Trapezoid height is: " + h.ToString());
+ double dxR = trpz.GetLeftBaseRadianAngle();
+ Console.WriteLine("Trapezoid left base angle is: " + dxR.ToString() + " Radians");
+ double dyR = trpz.GetRightBaseRadianAngle();
+ Console.WriteLine("Trapezoid right base angle is: " + dyR.ToString() + " Radians");
+ double dxD = trpz.GetLeftBaseDegreeAngle();
+ Console.WriteLine("Trapezoid left base angle is: " + dxD.ToString() + " Degrees");
+ double dyD = trpz.GetRightBaseDegreeAngle();
+ Console.WriteLine("Trapezoid right base angle is: " + dyD.ToString() + " Degrees");
+ }
+ }
}
//
diff --git a/snippets/csharp/System/Math/Pow/pow1.cs b/snippets/csharp/System/Math/Pow/pow1.cs
index 06b94f68ca9..b6adceaac81 100644
--- a/snippets/csharp/System/Math/Pow/pow1.cs
+++ b/snippets/csharp/System/Math/Pow/pow1.cs
@@ -2,47 +2,47 @@
public class Example
{
- public static void Main()
- {
- //
- int value = 2;
- for (int power = 0; power <= 32; power++)
- Console.WriteLine($"{value}^{power} = {(long)Math.Pow(value, power):N0} (0x{(long)Math.Pow(value, power):X})");
+ public static void Main()
+ {
+ //
+ int value = 2;
+ for (int power = 0; power <= 32; power++)
+ Console.WriteLine($"{value}^{power} = {(long)Math.Pow(value, power):N0} (0x{(long)Math.Pow(value, power):X})");
- // The example displays the following output:
- // 2^0 = 1 (0x1)
- // 2^1 = 2 (0x2)
- // 2^2 = 4 (0x4)
- // 2^3 = 8 (0x8)
- // 2^4 = 16 (0x10)
- // 2^5 = 32 (0x20)
- // 2^6 = 64 (0x40)
- // 2^7 = 128 (0x80)
- // 2^8 = 256 (0x100)
- // 2^9 = 512 (0x200)
- // 2^10 = 1,024 (0x400)
- // 2^11 = 2,048 (0x800)
- // 2^12 = 4,096 (0x1000)
- // 2^13 = 8,192 (0x2000)
- // 2^14 = 16,384 (0x4000)
- // 2^15 = 32,768 (0x8000)
- // 2^16 = 65,536 (0x10000)
- // 2^17 = 131,072 (0x20000)
- // 2^18 = 262,144 (0x40000)
- // 2^19 = 524,288 (0x80000)
- // 2^20 = 1,048,576 (0x100000)
- // 2^21 = 2,097,152 (0x200000)
- // 2^22 = 4,194,304 (0x400000)
- // 2^23 = 8,388,608 (0x800000)
- // 2^24 = 16,777,216 (0x1000000)
- // 2^25 = 33,554,432 (0x2000000)
- // 2^26 = 67,108,864 (0x4000000)
- // 2^27 = 134,217,728 (0x8000000)
- // 2^28 = 268,435,456 (0x10000000)
- // 2^29 = 536,870,912 (0x20000000)
- // 2^30 = 1,073,741,824 (0x40000000)
- // 2^31 = 2,147,483,648 (0x80000000)
- // 2^32 = 4,294,967,296 (0x100000000)
- //
- }
+ // The example displays the following output:
+ // 2^0 = 1 (0x1)
+ // 2^1 = 2 (0x2)
+ // 2^2 = 4 (0x4)
+ // 2^3 = 8 (0x8)
+ // 2^4 = 16 (0x10)
+ // 2^5 = 32 (0x20)
+ // 2^6 = 64 (0x40)
+ // 2^7 = 128 (0x80)
+ // 2^8 = 256 (0x100)
+ // 2^9 = 512 (0x200)
+ // 2^10 = 1,024 (0x400)
+ // 2^11 = 2,048 (0x800)
+ // 2^12 = 4,096 (0x1000)
+ // 2^13 = 8,192 (0x2000)
+ // 2^14 = 16,384 (0x4000)
+ // 2^15 = 32,768 (0x8000)
+ // 2^16 = 65,536 (0x10000)
+ // 2^17 = 131,072 (0x20000)
+ // 2^18 = 262,144 (0x40000)
+ // 2^19 = 524,288 (0x80000)
+ // 2^20 = 1,048,576 (0x100000)
+ // 2^21 = 2,097,152 (0x200000)
+ // 2^22 = 4,194,304 (0x400000)
+ // 2^23 = 8,388,608 (0x800000)
+ // 2^24 = 16,777,216 (0x1000000)
+ // 2^25 = 33,554,432 (0x2000000)
+ // 2^26 = 67,108,864 (0x4000000)
+ // 2^27 = 134,217,728 (0x8000000)
+ // 2^28 = 268,435,456 (0x10000000)
+ // 2^29 = 536,870,912 (0x20000000)
+ // 2^30 = 1,073,741,824 (0x40000000)
+ // 2^31 = 2,147,483,648 (0x80000000)
+ // 2^32 = 4,294,967,296 (0x100000000)
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Round/Program.cs b/snippets/csharp/System/Math/Round/Program.cs
new file mode 100644
index 00000000000..bb05111e8d3
--- /dev/null
+++ b/snippets/csharp/System/Math/Round/Program.cs
@@ -0,0 +1,7 @@
+MathRoundExample1.Run();
+MathRoundExample2.Run();
+MathRoundExample3.Run();
+MathRoundExample4.Run();
+MathRoundExample5.Run();
+MathRoundExample6.Run();
+Sample.Run();
diff --git a/snippets/csharp/System/Math/Round/Project.csproj b/snippets/csharp/System/Math/Round/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/Math/Round/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/Math/Round/round2.cs b/snippets/csharp/System/Math/Round/round2.cs
index 85f36ef2f3b..b456d432f7b 100644
--- a/snippets/csharp/System/Math/Round/round2.cs
+++ b/snippets/csharp/System/Math/Round/round2.cs
@@ -1,25 +1,25 @@
//
using System;
-public class Example
+public class MathRoundExample1
{
- public static void Main()
- {
- double value = 11.1;
- for (int ctr = 0; ctr <= 5; ctr++)
- value = RoundValueAndAdd(value);
+ public static void Run()
+ {
+ double value = 11.1;
+ for (int ctr = 0; ctr <= 5; ctr++)
+ value = RoundValueAndAdd(value);
- Console.WriteLine();
+ Console.WriteLine();
- value = 11.5;
- RoundValueAndAdd(value);
- }
+ value = 11.5;
+ RoundValueAndAdd(value);
+ }
- private static double RoundValueAndAdd(double value)
- {
- Console.WriteLine("{0} --> {1}", value, Math.Round(value));
- return value + .1;
- }
+ private static double RoundValueAndAdd(double value)
+ {
+ Console.WriteLine($"{value} --> {Math.Round(value)}");
+ return value + .1;
+ }
}
// The example displays the following output:
// 11.1 --> 11
diff --git a/snippets/csharp/System/Math/Round/round3.cs b/snippets/csharp/System/Math/Round/round3.cs
index 448e7829e61..50545a0fbbe 100644
--- a/snippets/csharp/System/Math/Round/round3.cs
+++ b/snippets/csharp/System/Math/Round/round3.cs
@@ -1,14 +1,14 @@
//
using System;
-public class Example
+public class MathRoundExample2
{
- public static void Main()
- {
- double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
- foreach (double value in values)
- Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));
- }
+ public static void Run()
+ {
+ double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
+ foreach (double value in values)
+ Console.WriteLine($"{value} --> {Math.Round(value, 2)}");
+ }
}
// The example displays the following output:
// 2.125 --> 2.12
diff --git a/snippets/csharp/System/Math/Round/round4.cs b/snippets/csharp/System/Math/Round/round4.cs
index 4644d380347..7c4443f8b86 100644
--- a/snippets/csharp/System/Math/Round/round4.cs
+++ b/snippets/csharp/System/Math/Round/round4.cs
@@ -1,22 +1,21 @@
using System;
-public class Example
+public class MathRoundExample3
{
- public static void Main()
- {
- //
- double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
- foreach (double value in values)
- Console.WriteLine("{0} --> {1}", value,
- Math.Round(value, 2, MidpointRounding.AwayFromZero));
+ public static void Run()
+ {
+ //
+ double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
+ foreach (double value in values)
+ Console.WriteLine($"{value} --> {Math.Round(value, 2, MidpointRounding.AwayFromZero)}");
- // The example displays the following output:
- // 2.125 --> 2.13
- // 2.135 --> 2.13
- // 2.145 --> 2.15
- // 3.125 --> 3.13
- // 3.135 --> 3.14
- // 3.145 --> 3.15
- //
- }
+ // The example displays the following output:
+ // 2.125 --> 2.13
+ // 2.135 --> 2.13
+ // 2.145 --> 2.15
+ // 3.125 --> 3.13
+ // 3.135 --> 3.14
+ // 3.145 --> 3.15
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Round/round5.cs b/snippets/csharp/System/Math/Round/round5.cs
index c75ab9b2c20..bbccada8586 100644
--- a/snippets/csharp/System/Math/Round/round5.cs
+++ b/snippets/csharp/System/Math/Round/round5.cs
@@ -1,26 +1,26 @@
//
using System;
-public class Example
+public class MathRoundExample4
{
- public static void Main()
- {
- double value = 11.1;
- for (int ctr = 0; ctr <= 5; ctr++)
- value = RoundValueAndAdd(value);
+ public static void Run()
+ {
+ double value = 11.1;
+ for (int ctr = 0; ctr <= 5; ctr++)
+ value = RoundValueAndAdd(value);
- Console.WriteLine();
+ Console.WriteLine();
- value = 11.5;
- RoundValueAndAdd(value);
- }
+ value = 11.5;
+ RoundValueAndAdd(value);
+ }
- private static double RoundValueAndAdd(double value)
- {
- Console.WriteLine("{0} --> {1}", value, Math.Round(value,
- MidpointRounding.AwayFromZero));
- return value + .1;
- }
+ private static double RoundValueAndAdd(double value)
+ {
+ Console.WriteLine($"{value} --> {Math.Round(value,
+ MidpointRounding.AwayFromZero)}");
+ return value + .1;
+ }
}
// The example displays the following output:
// 11.1 --> 11
diff --git a/snippets/csharp/System/Math/Round/rounddecimal1.cs b/snippets/csharp/System/Math/Round/rounddecimal1.cs
index bc9ad15c373..7f4059f166a 100644
--- a/snippets/csharp/System/Math/Round/rounddecimal1.cs
+++ b/snippets/csharp/System/Math/Round/rounddecimal1.cs
@@ -1,20 +1,20 @@
using System;
-class Example
+class MathRoundExample5
{
- static void Main()
- {
- //
- for (decimal value = 4.2m; value <= 4.8m; value+=.1m )
- Console.WriteLine("{0} --> {1}", value, Math.Round(value));
- // The example displays the following output:
- // 4.2 --> 4
- // 4.3 --> 4
- // 4.4 --> 4
- // 4.5 --> 4
- // 4.6 --> 5
- // 4.7 --> 5
- // 4.8 --> 5
- //
- }
+ public static void Run()
+ {
+ //
+ for (decimal value = 4.2m; value <= 4.8m; value += .1m)
+ Console.WriteLine($"{value} --> {Math.Round(value)}");
+ // The example displays the following output:
+ // 4.2 --> 4
+ // 4.3 --> 4
+ // 4.4 --> 4
+ // 4.5 --> 4
+ // 4.6 --> 5
+ // 4.7 --> 5
+ // 4.8 --> 5
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Round/source.cs b/snippets/csharp/System/Math/Round/source.cs
index 5b7e92dc26c..b4ce79acb8a 100644
--- a/snippets/csharp/System/Math/Round/source.cs
+++ b/snippets/csharp/System/Math/Round/source.cs
@@ -1,15 +1,15 @@
using System;
-class Program
+class MathRoundExample6
{
- static void Main()
+ public static void Run()
{
-//
- Console.WriteLine("Classic Math.Round in CSharp");
- Console.WriteLine(Math.Round(4.4)); // 4
- Console.WriteLine(Math.Round(4.5)); // 4
- Console.WriteLine(Math.Round(4.6)); // 5
- Console.WriteLine(Math.Round(5.5)); // 6
-//
+ //
+ Console.WriteLine("Classic Math.Round in CSharp");
+ Console.WriteLine(Math.Round(4.4)); // 4
+ Console.WriteLine(Math.Round(4.5)); // 4
+ Console.WriteLine(Math.Round(4.6)); // 5
+ Console.WriteLine(Math.Round(5.5)); // 6
+ //
}
}
diff --git a/snippets/csharp/System/Math/Round/source1.cs b/snippets/csharp/System/Math/Round/source1.cs
index 24dc3206c31..01ae6d4c79c 100644
--- a/snippets/csharp/System/Math/Round/source1.cs
+++ b/snippets/csharp/System/Math/Round/source1.cs
@@ -1,15 +1,17 @@
using System;
-public class Sample {
- static void Main() {
- //
- Math.Round(3.44, 1); //Returns 3.4.
- Math.Round(3.45, 1); //Returns 3.4.
- Math.Round(3.46, 1); //Returns 3.5.
+public class Sample
+{
+ public static void Run()
+ {
+ //
+ Math.Round(3.44, 1); //Returns 3.4.
+ Math.Round(3.45, 1); //Returns 3.4.
+ Math.Round(3.46, 1); //Returns 3.5.
- Math.Round(4.34, 1); // Returns 4.3
- Math.Round(4.35, 1); // Returns 4.4
- Math.Round(4.36, 1); // Returns 4.4
- //
- }
+ Math.Round(4.34, 1); // Returns 4.3
+ Math.Round(4.35, 1); // Returns 4.4
+ Math.Round(4.36, 1); // Returns 4.4
+ //
+ }
};
diff --git a/snippets/csharp/System/Math/Sign/sign.cs b/snippets/csharp/System/Math/Sign/sign.cs
index 6445b40198f..9238a4d9e53 100644
--- a/snippets/csharp/System/Math/Sign/sign.cs
+++ b/snippets/csharp/System/Math/Sign/sign.cs
@@ -8,17 +8,17 @@ public static void Main()
{
string str = "{0}: {1,3} is {2} zero.";
string nl = Environment.NewLine;
- byte xByte1 = 0;
- short xShort1 = -2;
- int xInt1 = -3;
- long xLong1 = -4;
- float xSingle1 = 0.0f;
- double xDouble1 = 6.0;
- Decimal xDecimal1 = -7m;
- nint xIntPtr1 = 8;
+ byte xByte1 = 0;
+ short xShort1 = -2;
+ int xInt1 = -3;
+ long xLong1 = -4;
+ float xSingle1 = 0.0f;
+ double xDouble1 = 6.0;
+ decimal xDecimal1 = -7m;
+ nint xIntPtr1 = 8;
// The following type is not CLS-compliant.
- sbyte xSbyte1 = -101;
+ sbyte xSbyte1 = -101;
Console.WriteLine($"{nl}Test the sign of the following types of values:");
Console.WriteLine(str, "Byte ", xByte1, Test(Math.Sign(xByte1)));
diff --git a/snippets/csharp/System/Math/Sqrt/sqrt1.cs b/snippets/csharp/System/Math/Sqrt/sqrt1.cs
index 9f0ee019044..ac12b1d9aea 100644
--- a/snippets/csharp/System/Math/Sqrt/sqrt1.cs
+++ b/snippets/csharp/System/Math/Sqrt/sqrt1.cs
@@ -2,34 +2,32 @@
public class Example
{
- public static void Main()
- {
- //
- // Create an array containing the area of some squares.
- Tuple[] areas =
- { Tuple.Create("Sitka, Alaska", 2870.3),
+ public static void Main()
+ {
+ //
+ // Create an array containing the area of some squares.
+ Tuple[] areas =
+ { Tuple.Create("Sitka, Alaska", 2870.3),
Tuple.Create("New York City", 302.6),
Tuple.Create("Los Angeles", 468.7),
Tuple.Create("Detroit", 138.8),
Tuple.Create("Chicago", 227.1),
Tuple.Create("San Diego", 325.2) };
- Console.WriteLine("{0,-18} {1,14:N1} {2,30}\n", "City", "Area (mi.)",
- "Equivalent to a square with:");
+ Console.WriteLine($"{"City",-18} {"Area (mi.)",14:N1} {"Equivalent to a square with:",30}\n");
- foreach (var area in areas)
- Console.WriteLine("{0,-18} {1,14:N1} {2,14:N2} miles per side",
- area.Item1, area.Item2, Math.Round(Math.Sqrt(area.Item2), 2));
+ foreach (var area in areas)
+ Console.WriteLine($"{area.Item1,-18} {area.Item2,14:N1} {Math.Round(Math.Sqrt(area.Item2), 2),14:N2} miles per side");
- // The example displays the following output:
- // City Area (mi.) Equivalent to a square with:
- //
- // Sitka, Alaska 2,870.3 53.58 miles per side
- // New York City 302.6 17.40 miles per side
- // Los Angeles 468.7 21.65 miles per side
- // Detroit 138.8 11.78 miles per side
- // Chicago 227.1 15.07 miles per side
- // San Diego 325.2 18.03 miles per side
- //
- }
+ // The example displays the following output:
+ // City Area (mi.) Equivalent to a square with:
+ //
+ // Sitka, Alaska 2,870.3 53.58 miles per side
+ // New York City 302.6 17.40 miles per side
+ // Los Angeles 468.7 21.65 miles per side
+ // Detroit 138.8 11.78 miles per side
+ // Chicago 227.1 15.07 miles per side
+ // San Diego 325.2 18.03 miles per side
+ //
+ }
}
diff --git a/snippets/csharp/System/Math/Tanh/tanh.cs b/snippets/csharp/System/Math/Tanh/tanh.cs
index 2287df55413..650de427e13 100644
--- a/snippets/csharp/System/Math/Tanh/tanh.cs
+++ b/snippets/csharp/System/Math/Tanh/tanh.cs
@@ -8,13 +8,13 @@ public static void Main()
{
Console.WriteLine(
"This example of hyperbolic Math.Tanh( double )\n" +
- "generates the following output." );
+ "generates the following output.");
Console.WriteLine(
"\nEvaluate these hyperbolic identities " +
- "with selected values for X:" );
- Console.WriteLine( " tanh(X) == sinh(X) / cosh(X)" );
+ "with selected values for X:");
+ Console.WriteLine(" tanh(X) == sinh(X) / cosh(X)");
Console.WriteLine(
- " tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X))" );
+ " tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X))");
UseTanh(0.1);
UseTanh(1.2);
@@ -23,7 +23,7 @@ public static void Main()
Console.WriteLine(
"\nEvaluate [tanh(X + Y) == (tanh(X) + tanh(Y)) " +
"/ (1 + tanh(X) * tanh(Y))]" +
- "\nwith selected values for X and Y:" );
+ "\nwith selected values for X and Y:");
UseTwoArgs(0.1, 1.2);
UseTwoArgs(1.2, 4.9);
@@ -38,18 +38,14 @@ static void UseTanh(double arg)
Console.WriteLine(
"\n Math.Tanh({0}) == {1:E16}\n" +
" Math.Sinh({0}) / Math.Cosh({0}) == {2:E16}",
- arg, tanhArg, (Math.Sinh(arg) / Math.Cosh(arg)) );
+ arg, tanhArg, (Math.Sinh(arg) / Math.Cosh(arg)));
// Evaluate tanh(2 * X) == 2 * tanh(X) / (1 + tanh^2(X)).
Console.WriteLine(
" 2 * Math.Tanh({0}) /",
- arg, 2.0 * tanhArg );
- Console.WriteLine(
- " (1 + (Math.Tanh({0}))^2) == {1:E16}",
- arg, 2.0 * tanhArg / (1.0 + tanhArg * tanhArg ) );
- Console.WriteLine(
- " Math.Tanh({0}) == {1:E16}",
- 2.0 * arg, Math.Tanh(2.0 * arg) );
+ arg, 2.0 * tanhArg);
+ Console.WriteLine($" (1 + (Math.Tanh({arg}))^2) == {2.0 * tanhArg / (1.0 + tanhArg * tanhArg):E16}");
+ Console.WriteLine($" Math.Tanh({2.0 * arg}) == {Math.Tanh(2.0 * arg):E16}");
}
// Evaluate a hyperbolic identity that is a function of two arguments.
@@ -60,10 +56,8 @@ static void UseTwoArgs(double argX, double argY)
"\n (Math.Tanh({0}) + Math.Tanh({1})) /\n" +
"(1 + Math.Tanh({0}) * Math.Tanh({1})) == {2:E16}",
argX, argY, (Math.Tanh(argX) + Math.Tanh(argY)) /
- (1.0 + Math.Tanh(argX) * Math.Tanh(argY)) );
- Console.WriteLine(
- " Math.Tanh({0}) == {1:E16}",
- argX + argY, Math.Tanh(argX + argY));
+ (1.0 + Math.Tanh(argX) * Math.Tanh(argY)));
+ Console.WriteLine($" Math.Tanh({argX + argY}) == {Math.Tanh(argX + argY):E16}");
}
}
diff --git a/snippets/csharp/System/Math/Truncate/Truncate1.cs b/snippets/csharp/System/Math/Truncate/Truncate1.cs
index ccd81138362..53645bcee23 100644
--- a/snippets/csharp/System/Math/Truncate/Truncate1.cs
+++ b/snippets/csharp/System/Math/Truncate/Truncate1.cs
@@ -2,30 +2,30 @@
public class Class1
{
- public static void Main()
- {
- //
- double floatNumber;
+ public static void Main()
+ {
+ //
+ double floatNumber;
- floatNumber = 32.7865;
- // Displays 32
- Console.WriteLine(Math.Truncate(floatNumber));
+ floatNumber = 32.7865;
+ // Displays 32
+ Console.WriteLine(Math.Truncate(floatNumber));
- floatNumber = -32.9012;
- // Displays -32
- Console.WriteLine(Math.Truncate(floatNumber));
- //
+ floatNumber = -32.9012;
+ // Displays -32
+ Console.WriteLine(Math.Truncate(floatNumber));
+ //
- //
- decimal decimalNumber;
+ //
+ decimal decimalNumber;
- decimalNumber = 32.7865m;
- // Displays 32
- Console.WriteLine(Math.Truncate(decimalNumber));
+ decimalNumber = 32.7865m;
+ // Displays 32
+ Console.WriteLine(Math.Truncate(decimalNumber));
- decimalNumber = -32.9012m;
- // Displays -32
- Console.WriteLine(Math.Truncate(decimalNumber));
- //
- }
+ decimalNumber = -32.9012m;
+ // Displays -32
+ Console.WriteLine(Math.Truncate(decimalNumber));
+ //
+ }
}
diff --git a/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs b/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs
index 13c515ba601..ee088e3f376 100644
--- a/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs
+++ b/snippets/csharp/System/MissingFieldException/Overview/MissingMethodException.cs
@@ -22,7 +22,7 @@ public static void Main()
catch (MissingMethodException e)
{
// Show the user that the DoSomething method cannot be called.
- Console.WriteLine("Unable to call the DoSomething method: {0}", e.Message);
+ Console.WriteLine($"Unable to call the DoSomething method: {e.Message}");
}
//
@@ -33,12 +33,12 @@ public static void Main()
// However, because the App class does not define this field,
// a MissingFieldException is thrown.
typeof(App).InvokeMember("AField", BindingFlags.Static | BindingFlags.SetField,
- null, null, new Object[] { 5 });
+ null, null, new object[] { 5 });
}
catch (MissingFieldException e)
{
- // Show the user that the AField field cannot be accessed.
- Console.WriteLine("Unable to access the AField field: {0}", e.Message);
+ // Show the user that the AField field cannot be accessed.
+ Console.WriteLine($"Unable to access the AField field: {e.Message}");
}
//
@@ -53,10 +53,10 @@ public static void Main()
}
catch (MissingMemberException e)
{
- // Notice that this code is catching MissingMemberException which is the
- // base class of MissingMethodException and MissingFieldException.
- // Show the user that the AnotherField field cannot be accessed.
- Console.WriteLine("Unable to access the AnotherField field: {0}", e.Message);
+ // Notice that this code is catching MissingMemberException which is the
+ // base class of MissingMethodException and MissingFieldException.
+ // Show the user that the AnotherField field cannot be accessed.
+ Console.WriteLine($"Unable to access the AnotherField field: {e.Message}");
}
//
}
@@ -66,4 +66,4 @@ public static void Main()
// Unable to call the DoSomething method: Method 'App.DoSomething' not found.
// Unable to access the AField field: Field 'App.AField' not found.
// Unable to access the AnotherField field: Field 'App.AnotherField' not found.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs b/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs
index 0ca29355b27..1fa902ccf3a 100644
--- a/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs
+++ b/snippets/csharp/System/MulticastDelegate/Overview/delegatestring.cs
@@ -4,103 +4,100 @@
class StringContainer
{
- // Define a delegate to handle string display.
- public delegate void CheckAndDisplayDelegate(string str);
-
- // A generic list object that holds the strings.
- private List container = new List();
-
- // A method that adds strings to the collection.
- public void AddString(string str)
- {
- container.Add(str);
- }
-
- // Iterate through the strings and invoke the method(s) that the delegate points to.
- public void DisplayAllQualified(CheckAndDisplayDelegate displayDelegate)
- {
- foreach (var str in container) {
- displayDelegate(str);
- }
- }
- }
+ // Define a delegate to handle string display.
+ public delegate void CheckAndDisplayDelegate(string str);
+
+ // A generic list object that holds the strings.
+ private List container = new();
+
+ // A method that adds strings to the collection.
+ public void AddString(string str) => container.Add(str);
+
+ // Iterate through the strings and invoke the method(s) that the delegate points to.
+ public void DisplayAllQualified(CheckAndDisplayDelegate displayDelegate)
+ {
+ foreach (string str in container)
+ {
+ displayDelegate(str);
+ }
+ }
+}
// This class defines some methods to display strings.
class StringExtensions
{
- // Display a string if it starts with a consonant.
- public static void ConStart(string str)
- {
- if (!(str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u'))
- Console.WriteLine(str);
- }
-
- // Display a string if it starts with a vowel.
- public static void VowelStart(string str)
- {
- if ((str[0]=='a'||str[0]=='e'||str[0]=='i'||str[0]=='o'||str[0]=='u'))
- Console.WriteLine(str);
- }
+ // Display a string if it starts with a consonant.
+ public static void ConStart(string str)
+ {
+ if (!(str[0] == 'a' || str[0] == 'e' || str[0] == 'i' || str[0] == 'o' || str[0] == 'u'))
+ Console.WriteLine(str);
+ }
+
+ // Display a string if it starts with a vowel.
+ public static void VowelStart(string str)
+ {
+ if ((str[0] == 'a' || str[0] == 'e' || str[0] == 'i' || str[0] == 'o' || str[0] == 'u'))
+ Console.WriteLine(str);
+ }
}
// Demonstrate the use of delegates, including the Remove and
// Combine methods to create and modify delegate combinations.
class Test
{
- static public void Main()
- {
- // Declare the StringContainer class and add some strings
- StringContainer container = new StringContainer();
- container.AddString("This");
- container.AddString("is");
- container.AddString("a");
- container.AddString("multicast");
- container.AddString("delegate");
- container.AddString("example");
-
- // Create two delegates individually using different methods.
- StringContainer.CheckAndDisplayDelegate conStart = StringExtensions.ConStart;
- StringContainer.CheckAndDisplayDelegate vowelStart = StringExtensions.VowelStart;
-
- // Get the list of all delegates assigned to this MulticastDelegate instance.
- Delegate[] delegateList = conStart.GetInvocationList();
- Console.WriteLine("conStart contains {0} delegate(s).", delegateList.Length);
- delegateList = vowelStart.GetInvocationList();
- Console.WriteLine("vowelStart contains {0} delegate(s).\n", delegateList.Length);
-
- // Determine whether the delegates are System.Multicast delegates.
- if (conStart is System.MulticastDelegate && vowelStart is System.MulticastDelegate)
- Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n");
-
- // Execute the two delegates.
- Console.WriteLine("Executing the conStart delegate:");
- container.DisplayAllQualified(conStart);
- Console.WriteLine();
- Console.WriteLine("Executing the vowelStart delegate:");
- container.DisplayAllQualified(vowelStart);
- Console.WriteLine();
-
- // Create a new MulticastDelegate and call Combine to add two delegates.
- StringContainer.CheckAndDisplayDelegate multipleDelegates =
- (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(conStart, vowelStart);
-
- // How many delegates does multipleDelegates contain?
- delegateList = multipleDelegates.GetInvocationList();
- Console.WriteLine("\nmultipleDelegates contains {0} delegates.\n",
- delegateList.Length);
-
- // Pass this multicast delegate to DisplayAllQualified.
- Console.WriteLine("Executing the multipleDelegate delegate.");
- container.DisplayAllQualified(multipleDelegates);
-
- // Call remove and combine to change the contained delegates.
- multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Remove(multipleDelegates, vowelStart);
- multipleDelegates = (StringContainer.CheckAndDisplayDelegate) Delegate.Combine(multipleDelegates, conStart);
-
- // Pass multipleDelegates to DisplayAllQualified again.
- Console.WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:");
- container.DisplayAllQualified(multipleDelegates);
- }
+ static public void Main()
+ {
+ // Declare the StringContainer class and add some strings
+ StringContainer container = new();
+ container.AddString("This");
+ container.AddString("is");
+ container.AddString("a");
+ container.AddString("multicast");
+ container.AddString("delegate");
+ container.AddString("example");
+
+ // Create two delegates individually using different methods.
+ StringContainer.CheckAndDisplayDelegate conStart = StringExtensions.ConStart;
+ StringContainer.CheckAndDisplayDelegate vowelStart = StringExtensions.VowelStart;
+
+ // Get the list of all delegates assigned to this MulticastDelegate instance.
+ Delegate[] delegateList = conStart.GetInvocationList();
+ Console.WriteLine($"conStart contains {delegateList.Length} delegate(s).");
+ delegateList = vowelStart.GetInvocationList();
+ Console.WriteLine($"vowelStart contains {delegateList.Length} delegate(s).\n");
+
+ // Determine whether the delegates are System.Multicast delegates.
+ if (conStart is System.MulticastDelegate && vowelStart is System.MulticastDelegate)
+ Console.WriteLine("conStart and vowelStart are derived from MulticastDelegate.\n");
+
+ // Execute the two delegates.
+ Console.WriteLine("Executing the conStart delegate:");
+ container.DisplayAllQualified(conStart);
+ Console.WriteLine();
+ Console.WriteLine("Executing the vowelStart delegate:");
+ container.DisplayAllQualified(vowelStart);
+ Console.WriteLine();
+
+ // Create a new MulticastDelegate and call Combine to add two delegates.
+ StringContainer.CheckAndDisplayDelegate multipleDelegates =
+ (StringContainer.CheckAndDisplayDelegate)Delegate.Combine(conStart, vowelStart);
+
+ // How many delegates does multipleDelegates contain?
+ delegateList = multipleDelegates.GetInvocationList();
+ Console.WriteLine($"\nmultipleDelegates contains {delegateList.Length} delegates.\n");
+
+ // Pass this multicast delegate to DisplayAllQualified.
+ Console.WriteLine("Executing the multipleDelegate delegate.");
+ container.DisplayAllQualified(multipleDelegates);
+
+ // Call remove and combine to change the contained delegates.
+ multipleDelegates = (StringContainer.CheckAndDisplayDelegate)Delegate.Remove(multipleDelegates, vowelStart);
+ multipleDelegates = (StringContainer.CheckAndDisplayDelegate)Delegate.Combine(multipleDelegates, conStart);
+
+ // Pass multipleDelegates to DisplayAllQualified again.
+ Console.WriteLine("\nExecuting the multipleDelegate delegate with two conStart delegates:");
+ container.DisplayAllQualified(multipleDelegates);
+ }
}
// The example displays the following output:
// conStart contains 1 delegate(s).
diff --git a/snippets/csharp/System/NotImplementedException/Overview/program.cs b/snippets/csharp/System/NotImplementedException/Overview/program.cs
index 301fca07fae..941b6c8435b 100644
--- a/snippets/csharp/System/NotImplementedException/Overview/program.cs
+++ b/snippets/csharp/System/NotImplementedException/Overview/program.cs
@@ -2,23 +2,23 @@
class Program
{
-//
-static void Main(string[] args)
-{
- try
+ //
+ static void Main(string[] args)
{
- FutureFeature();
+ try
+ {
+ FutureFeature();
+ }
+ catch (NotImplementedException notImp)
+ {
+ Console.WriteLine(notImp.Message);
+ }
}
- catch (NotImplementedException notImp)
+
+ static void FutureFeature()
{
- Console.WriteLine(notImp.Message);
+ // Not developed yet.
+ throw new NotImplementedException();
}
-}
-
-static void FutureFeature()
-{
- // Not developed yet.
- throw new NotImplementedException();
-}
-//
+ //
}
diff --git a/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs b/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs
index 323cea83410..de52310127b 100644
--- a/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs
+++ b/snippets/csharp/System/NotSupportedException/Overview/BadState1.cs
@@ -9,10 +9,10 @@ public class Example
public static async Task Main()
{
Encoding enc = Encoding.Unicode;
- String value = "This is a string to persist.";
- Byte[] bytes = enc.GetBytes(value);
+ string value = "This is a string to persist.";
+ byte[] bytes = enc.GetBytes(value);
- FileStream fs = new FileStream(@".\TestFile.dat",
+ FileStream fs = new(@".\TestFile.dat",
FileMode.Open,
FileAccess.Read);
Task t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length);
diff --git a/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs b/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs
index 7eaf7c84e92..abc9ae52b90 100644
--- a/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs
+++ b/snippets/csharp/System/NotSupportedException/Overview/TestProp1.cs
@@ -7,12 +7,11 @@ public class TestPropEx1
{
public static async Task Main()
{
- String name = @".\TestFile.dat";
+ string name = @".\TestFile.dat";
var fs = new FileStream(name,
FileMode.Create,
FileAccess.Write);
- Console.WriteLine("Filename: {0}, Encoding: {1}",
- name, await FileUtilities1.GetEncodingType(fs));
+ Console.WriteLine($"Filename: {name}, Encoding: {await FileUtilities1.GetEncodingType(fs)}");
}
}
@@ -23,7 +22,7 @@ public enum EncodingType
public async static Task GetEncodingType(FileStream fs)
{
- Byte[] bytes = new Byte[4];
+ byte[] bytes = new byte[4];
int bytesRead = await fs.ReadAsync(bytes, 0, 4);
if (bytesRead < 2)
return EncodingType.None;
@@ -33,12 +32,12 @@ public async static Task GetEncodingType(FileStream fs)
if (bytesRead == 4)
{
- var value = BitConverter.ToUInt32(bytes, 0);
+ uint value = BitConverter.ToUInt32(bytes, 0);
if (value == 0x0000FEFF | value == 0xFEFF0000)
return EncodingType.Utf32;
}
- var value16 = BitConverter.ToUInt16(bytes, 0);
+ ushort value16 = BitConverter.ToUInt16(bytes, 0);
if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE)
return EncodingType.Utf16;
diff --git a/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs b/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs
index 795a01183ae..a10c1987c38 100644
--- a/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs
+++ b/snippets/csharp/System/NotSupportedException/Overview/TestProp2.cs
@@ -6,12 +6,11 @@ public class TestPropEx2
{
public static async Task Main()
{
- String name = @".\TestFile.dat";
+ string name = @".\TestFile.dat";
var fs = new FileStream(name,
FileMode.Create,
FileAccess.Write);
- Console.WriteLine("Filename: {0}, Encoding: {1}",
- name, await FileUtilities.GetEncodingType(fs));
+ Console.WriteLine($"Filename: {name}, Encoding: {await FileUtilities.GetEncodingType(fs)}");
}
}
@@ -26,7 +25,7 @@ public static async Task GetEncodingType(FileStream fs)
if (!fs.CanRead)
return EncodingType.Unknown;
- Byte[] bytes = new Byte[4];
+ byte[] bytes = new byte[4];
int bytesRead = await fs.ReadAsync(bytes, 0, 4);
if (bytesRead < 2)
return EncodingType.None;
@@ -36,12 +35,12 @@ public static async Task GetEncodingType(FileStream fs)
if (bytesRead == 4)
{
- var value = BitConverter.ToUInt32(bytes, 0);
+ uint value = BitConverter.ToUInt32(bytes, 0);
if (value == 0x0000FEFF | value == 0xFEFF0000)
return EncodingType.Utf32;
}
- var value16 = BitConverter.ToUInt16(bytes, 0);
+ ushort value16 = BitConverter.ToUInt16(bytes, 0);
if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE)
return EncodingType.Utf16;
diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs
index 599029a2be9..bf12d6305a3 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/Array1.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/Array1.cs
@@ -5,10 +5,9 @@ public class Array1Example
public static void Main()
{
//
- string[] values = [ "one", null, "two" ];
+ string[] values = ["one", null, "two"];
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
- Console.Write("{0}{1}", values[ctr].Trim(),
- ctr == values.GetUpperBound(0) ? "" : ", ");
+ Console.Write($"{values[ctr].Trim()}{(ctr == values.GetUpperBound(0) ? "" : ", ")}");
Console.WriteLine();
// The example displays the following output:
diff --git a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs
index 756e52f450b..4cdb6435cb9 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/Array2.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/Array2.cs
@@ -5,11 +5,9 @@ public class Array2Example
public static void Main()
{
//
- string[] values = [ "one", null, "two" ];
+ string[] values = ["one", null, "two"];
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
- Console.Write("{0}{1}",
- values[ctr] != null ? values[ctr].Trim() : "",
- ctr == values.GetUpperBound(0) ? "" : ", ");
+ Console.Write($"{(values[ctr] != null ? values[ctr].Trim() : "")}{(ctr == values.GetUpperBound(0) ? "" : ", ")}");
Console.WriteLine();
// The example displays the following output:
diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs
index 31f69e53c3e..2756d22fbf4 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/Chain1.cs
@@ -23,7 +23,7 @@ public class Pages
public Page CurrentPage
{
- get { return _page[_ctr]; }
+ get => _page[_ctr];
set
{
// Move all the page objects down to accommodate the new one.
diff --git a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs
index 2034ef1efb6..8987d0d9a28 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/Chain2.cs
@@ -30,7 +30,7 @@ public class Pages
public Page CurrentPage
{
- get { return _page[_ctr]; }
+ get => _page[_ctr];
set
{
// Move all the page objects down to accommodate the new one.
diff --git a/snippets/csharp/System/NullReferenceException/Overview/example2.cs b/snippets/csharp/System/NullReferenceException/Overview/example2.cs
index 41dfb78ede0..71ab56fe89a 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/example2.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/example2.cs
@@ -17,10 +17,7 @@ private static void PopulateNames(List names)
names.Add(arrName);
}
- private static List GetData()
- {
- return null;
- }
+ private static List GetData() => null;
}
// The example displays output like the following:
diff --git a/snippets/csharp/System/NullReferenceException/Overview/example3.cs b/snippets/csharp/System/NullReferenceException/Overview/example3.cs
index 2ce0700f112..412cfa96068 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/example3.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/example3.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using System.Collections.Generic;
using System.Collections;
@@ -12,15 +12,12 @@ public static void Main()
_ = GetList(listType);
}
- private static Type GetListType()
- {
- return typeof(List);
- }
+ private static Type GetListType() => typeof(List);
private static IList GetList(Type type)
{
var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor
- var value = 1;
+ int value = 1;
emptyList.Add(value);
return emptyList;
}
diff --git a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs
index 2c6dd285739..2036797ecce 100644
--- a/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs
+++ b/snippets/csharp/System/NullReferenceException/Overview/nullreturn2.cs
@@ -44,15 +44,12 @@ public static Person[] AddRange(params string[] firstNames)
{
Person[] p = new Person[firstNames.Length];
for (int ctr = 0; ctr < firstNames.Length; ctr++)
- p[ctr] = new Person(firstNames[ctr]);
+ p[ctr] = new(firstNames[ctr]);
return p;
}
- public Person(string firstName)
- {
- FirstName = firstName;
- }
+ public Person(string firstName) => FirstName = firstName;
public string FirstName;
}
diff --git a/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs b/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs
index dc86f85c3bd..8e163b67ee9 100644
--- a/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs
+++ b/snippets/csharp/System/Nullable/GetUnderlyingType/gut.cs
@@ -7,33 +7,30 @@
class Sample
{
-// Declare a type named Example.
-// The MyMethod member of Example returns a Nullable of Int32.
+ // Declare a type named Example.
+ // The MyMethod member of Example returns a Nullable of Int32.
public class Example
{
- public int? MyMethod()
- {
- return 0;
- }
+ public int? MyMethod() => 0;
}
-/*
- Use reflection to obtain a Type object for the Example type.
- Use the Type object to obtain a MethodInfo object for the MyMethod method.
- Use the MethodInfo object to obtain the type of the return value of
- MyMethod, which is Nullable of Int32.
- Use the GetUnderlyingType method to obtain the type argument of the
- return value type, which is Int32.
-*/
+ /*
+ Use reflection to obtain a Type object for the Example type.
+ Use the Type object to obtain a MethodInfo object for the MyMethod method.
+ Use the MethodInfo object to obtain the type of the return value of
+ MyMethod, which is Nullable of Int32.
+ Use the GetUnderlyingType method to obtain the type argument of the
+ return value type, which is Int32.
+ */
public static void Main()
{
Type t = typeof(Example);
MethodInfo mi = t.GetMethod("MyMethod");
Type retval = mi.ReturnType;
- Console.WriteLine("Return value type ... {0}", retval);
+ Console.WriteLine($"Return value type ... {retval}");
Type answer = Nullable.GetUnderlyingType(retval);
- Console.WriteLine("Underlying type ..... {0}", answer);
+ Console.WriteLine($"Underlying type ..... {answer}");
}
}
/*
@@ -43,4 +40,4 @@ Return value type ... System.Nullable`1[System.Int32]
Underlying type ..... System.Int32
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/Equals/eq.cs b/snippets/csharp/System/NullableT/Equals/eq.cs
index ebd405f2f38..a86abbad545 100644
--- a/snippets/csharp/System/NullableT/Equals/eq.cs
+++ b/snippets/csharp/System/NullableT/Equals/eq.cs
@@ -8,30 +8,30 @@ class Sample
{
public static void Main()
{
- int? nullInt1 = 100;
- int? nullInt2 = 200;
- object myObj;
-
-// Determine if two nullable of System.Int32 values are equal.
-// The nullable objects have different values.
- Console.Write("1) nullInt1 and nullInt2 ");
- if (nullInt1.Equals(nullInt2))
- Console.Write("are");
- else
- Console.Write("are not");
- Console.WriteLine(" equal.");
-
-// Determine if a nullable of System.Int32 and an object
-// are equal. The object contains the boxed value of the
-// nullable object.
-
- myObj = (object)nullInt1;
- Console.Write("2) nullInt1 and myObj ");
- if (nullInt1.Equals(myObj))
- Console.Write("are");
- else
- Console.Write("are not");
- Console.WriteLine(" equal.");
+ int? nullInt1 = 100;
+ int? nullInt2 = 200;
+ object myObj;
+
+ // Determine if two nullable of System.Int32 values are equal.
+ // The nullable objects have different values.
+ Console.Write("1) nullInt1 and nullInt2 ");
+ if (nullInt1.Equals(nullInt2))
+ Console.Write("are");
+ else
+ Console.Write("are not");
+ Console.WriteLine(" equal.");
+
+ // Determine if a nullable of System.Int32 and an object
+ // are equal. The object contains the boxed value of the
+ // nullable object.
+
+ myObj = (object)nullInt1;
+ Console.Write("2) nullInt1 and myObj ");
+ if (nullInt1.Equals(myObj))
+ Console.Write("are");
+ else
+ Console.Write("are not");
+ Console.WriteLine(" equal.");
}
}
@@ -42,4 +42,4 @@ public static void Main()
2) nullInt1 and myObj are equal.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs b/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs
index 3169bdada67..2fd73c2cee6 100644
--- a/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs
+++ b/snippets/csharp/System/NullableT/GetValueOrDefault/gvod.cs
@@ -8,67 +8,63 @@ class Sample
{
public static void Main()
{
- float? mySingle = 12.34f;
- float? yourSingle = -1.0f;
+ float? mySingle = 12.34f;
+ float? yourSingle = -1.0f;
- Console.WriteLine("*** Display a value or the default value ***\n");
-// Display the values of mySingle and yourSingle.
+ Console.WriteLine("*** Display a value or the default value ***\n");
+ // Display the values of mySingle and yourSingle.
- Display("A1", mySingle, yourSingle);
+ Display("A1", mySingle, yourSingle);
-// Assign the value of mySingle to yourSingle, then display the values
-// of mySingle and yourSingle. The yourSingle variable is assigned the
-// value 12.34 because mySingle has a value.
+ // Assign the value of mySingle to yourSingle, then display the values
+ // of mySingle and yourSingle. The yourSingle variable is assigned the
+ // value 12.34 because mySingle has a value.
- yourSingle = mySingle.GetValueOrDefault();
- Display("A2", mySingle, yourSingle);
+ yourSingle = mySingle.GetValueOrDefault();
+ Display("A2", mySingle, yourSingle);
-// Assign null (Nothing in Visual Basic) to mySingle, which means no value is
-// defined for mySingle. Then assign the value of mySingle to yourSingle and
-// display the values of both variables. The default value of all binary zeroes
-// is assigned to yourSingle because mySingle has no value.
+ // Assign null (Nothing in Visual Basic) to mySingle, which means no value is
+ // defined for mySingle. Then assign the value of mySingle to yourSingle and
+ // display the values of both variables. The default value of all binary zeroes
+ // is assigned to yourSingle because mySingle has no value.
- mySingle = null;
- yourSingle = mySingle.GetValueOrDefault();
- Display("A3", mySingle, yourSingle);
+ mySingle = null;
+ yourSingle = mySingle.GetValueOrDefault();
+ Display("A3", mySingle, yourSingle);
-// Reassign the original values of mySingle and yourSingle.
- mySingle = 12.34f;
- yourSingle = -1.0f;
+ // Reassign the original values of mySingle and yourSingle.
+ mySingle = 12.34f;
+ yourSingle = -1.0f;
- Console.Write("\n*** Display a value or the ");
- Console.WriteLine("specified default value ***\n");
+ Console.Write("\n*** Display a value or the ");
+ Console.WriteLine("specified default value ***\n");
-// Display the values of mySingle and yourSingle.
- Display("B1", mySingle, yourSingle);
+ // Display the values of mySingle and yourSingle.
+ Display("B1", mySingle, yourSingle);
-// Assign the value of mySingle to yourSingle, then display the values
-// of mySingle and yourSingle. The yourSingle variable is assigned the
-// value 12.34 because mySingle has a value.
+ // Assign the value of mySingle to yourSingle, then display the values
+ // of mySingle and yourSingle. The yourSingle variable is assigned the
+ // value 12.34 because mySingle has a value.
- yourSingle = mySingle.GetValueOrDefault(-222.22f);
- Display("B2", mySingle, yourSingle);
+ yourSingle = mySingle.GetValueOrDefault(-222.22f);
+ Display("B2", mySingle, yourSingle);
-// Assign null (Nothing in Visual Basic) to mySingle, which means no value is
-// defined for mySingle. Then assign the value of mySingle to yourSingle and
-// display the values of both variables. The specified default value of -333.33
-// is assigned to yourSingle because mySingle has no value.
+ // Assign null (Nothing in Visual Basic) to mySingle, which means no value is
+ // defined for mySingle. Then assign the value of mySingle to yourSingle and
+ // display the values of both variables. The specified default value of -333.33
+ // is assigned to yourSingle because mySingle has no value.
- mySingle = null;
- yourSingle = mySingle.GetValueOrDefault(-333.33f);
- Display("B3", mySingle, yourSingle);
+ mySingle = null;
+ yourSingle = mySingle.GetValueOrDefault(-333.33f);
+ Display("B3", mySingle, yourSingle);
}
-// Display the values of two nullable of System.Single structures.
-// The Console.WriteLine method automatically calls the ToString methods of
-// each input argument to display its values. If no value is defined for a
-// nullable type, the ToString method for that argument returns the empty
-// string ("").
- public static void Display(string title, float? dspMySingle, float? dspYourSingle)
- {
- Console.WriteLine("{0}) mySingle = [{1}], yourSingle = [{2}]",
- title, dspMySingle, dspYourSingle);
- }
+ // Display the values of two nullable of System.Single structures.
+ // The Console.WriteLine method automatically calls the ToString methods of
+ // each input argument to display its values. If no value is defined for a
+ // nullable type, the ToString method for that argument returns the empty
+ // string ("").
+ public static void Display(string title, float? dspMySingle, float? dspYourSingle) => Console.WriteLine($"{title}) mySingle = [{dspMySingle}], yourSingle = [{dspYourSingle}]");
}
/*
@@ -85,4 +81,4 @@ public static void Display(string title, float? dspMySingle, float? dspYourSingl
B3) mySingle = [], yourSingle = [-333.33]
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs b/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs
index a0d19fb3abe..07d18f393b6 100644
--- a/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs
+++ b/snippets/csharp/System/NullableT/HasValue/hasvalue2.cs
@@ -3,27 +3,30 @@
public class Example
{
- public static void Main()
- {
- Nullable n1 = new Nullable(10);
- Nullable n2 = null;
- Nullable n3 = new Nullable(20);
- n3 = null;
- Nullable[] items = { n1, n2, n3 };
+ public static void Main()
+ {
+ Nullable n1 = new Nullable(10);
+ Nullable n2 = null;
+ Nullable n3 = new Nullable(20);
+ n3 = null;
+ Nullable[] items = { n1, n2, n3 };
- foreach (var item in items) {
- Console.WriteLine("Has a value: {0}", item.HasValue);
- if (item.HasValue) {
- Console.WriteLine("Type: {0}", item.GetType().Name);
- Console.WriteLine("Value: {0}", item.Value);
- }
- else {
- Console.WriteLine("Null: {0}", item == null);
- Console.WriteLine("Default Value: {0}", item.GetValueOrDefault());
- }
- Console.WriteLine();
- }
- }
+ foreach (var item in items)
+ {
+ Console.WriteLine($"Has a value: {item.HasValue}");
+ if (item.HasValue)
+ {
+ Console.WriteLine($"Type: {item.GetType().Name}");
+ Console.WriteLine($"Value: {item.Value}");
+ }
+ else
+ {
+ Console.WriteLine($"Null: {item == null}");
+ Console.WriteLine($"Default Value: {item.GetValueOrDefault()}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Has a value: True
@@ -37,4 +40,4 @@ public static void Main()
// Has a value: False
// Null: True
// Default Value: 0
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/Overview/tarow.cs b/snippets/csharp/System/NullableT/Overview/tarow.cs
index 04d3a3085b5..541343a4e55 100644
--- a/snippets/csharp/System/NullableT/Overview/tarow.cs
+++ b/snippets/csharp/System/NullableT/Overview/tarow.cs
@@ -6,55 +6,56 @@ class Sample
// Define the "titleAuthor" table of the Microsoft "pubs" database.
public struct titleAuthor
{
- // Author ID; format ###-##-####
- public string au_id;
- // Title ID; format AA####
- public string title_id;
- // Author ORD is nullable.
- public short? au_ord;
- // Royalty Percent is nullable.
- public int? royaltyper;
+ // Author ID; format ###-##-####
+ public string au_id;
+ // Title ID; format AA####
+ public string title_id;
+ // Author ORD is nullable.
+ public short? au_ord;
+ // Royalty Percent is nullable.
+ public int? royaltyper;
}
public static void Main()
{
- // Declare and initialize the titleAuthor array.
- titleAuthor[] ta = new titleAuthor[3];
- ta[0].au_id = "712-32-1176";
- ta[0].title_id = "PS3333";
- ta[0].au_ord = 1;
- ta[0].royaltyper = 100;
+ // Declare and initialize the titleAuthor array.
+ titleAuthor[] ta = new titleAuthor[3];
+ ta[0].au_id = "712-32-1176";
+ ta[0].title_id = "PS3333";
+ ta[0].au_ord = 1;
+ ta[0].royaltyper = 100;
- ta[1].au_id = "213-46-8915";
- ta[1].title_id = "BU1032";
- ta[1].au_ord = null;
- ta[1].royaltyper = null;
+ ta[1].au_id = "213-46-8915";
+ ta[1].title_id = "BU1032";
+ ta[1].au_ord = null;
+ ta[1].royaltyper = null;
- ta[2].au_id = "672-71-3249";
- ta[2].title_id = "TC7777";
- ta[2].au_ord = null;
- ta[2].royaltyper = 40;
+ ta[2].au_id = "672-71-3249";
+ ta[2].title_id = "TC7777";
+ ta[2].au_ord = null;
+ ta[2].royaltyper = 40;
- // Display the values of the titleAuthor array elements, and
- // display a legend.
- Display("Title Authors Table", ta);
- Console.WriteLine("Legend:");
- Console.WriteLine("An Author ORD of -1 means no value is defined.");
- Console.WriteLine("A Royalty % of 0 means no value is defined.");
+ // Display the values of the titleAuthor array elements, and
+ // display a legend.
+ Display("Title Authors Table", ta);
+ Console.WriteLine("Legend:");
+ Console.WriteLine("An Author ORD of -1 means no value is defined.");
+ Console.WriteLine("A Royalty % of 0 means no value is defined.");
}
// Display the values of the titleAuthor array elements.
public static void Display(string dspTitle,
titleAuthor[] dspAllTitleAuthors)
{
- Console.WriteLine("*** {0} ***", dspTitle);
- foreach (titleAuthor dspTA in dspAllTitleAuthors) {
- Console.WriteLine("Author ID ... {0}", dspTA.au_id);
- Console.WriteLine("Title ID .... {0}", dspTA.title_id);
- Console.WriteLine("Author ORD .. {0}", dspTA.au_ord ?? -1);
- Console.WriteLine("Royalty % ... {0}", dspTA.royaltyper ?? 0);
- Console.WriteLine();
- }
+ Console.WriteLine($"*** {dspTitle} ***");
+ foreach (titleAuthor dspTA in dspAllTitleAuthors)
+ {
+ Console.WriteLine($"Author ID ... {dspTA.au_id}");
+ Console.WriteLine($"Title ID .... {dspTA.title_id}");
+ Console.WriteLine($"Author ORD .. {dspTA.au_ord ?? -1}");
+ Console.WriteLine($"Royalty % ... {dspTA.royaltyper ?? 0}");
+ Console.WriteLine();
+ }
}
}
// The example displays the following output:
@@ -77,4 +78,4 @@ public static void Display(string dspTitle,
// Legend:
// An Author ORD of -1 means no value is defined.
// A Royalty % of 0 means no value is defined.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/ToString/ts.cs b/snippets/csharp/System/NullableT/ToString/ts.cs
index 3636eb9ddce..5736259dbc3 100644
--- a/snippets/csharp/System/NullableT/ToString/ts.cs
+++ b/snippets/csharp/System/NullableT/ToString/ts.cs
@@ -8,28 +8,28 @@ class Sample
{
public static void Main()
{
- DateTime? nullableDate;
+ DateTime? nullableDate;
-// Display the current date and time.
- nullableDate = DateTime.Now;
- Display("1)", nullableDate);
+ // Display the current date and time.
+ nullableDate = DateTime.Now;
+ Display("1)", nullableDate);
-// Assign null (Nothing in Visual Basic) to nullableDate, then
-// display its value.
- nullableDate = null;
- Display("2)", nullableDate);
+ // Assign null (Nothing in Visual Basic) to nullableDate, then
+ // display its value.
+ nullableDate = null;
+ Display("2)", nullableDate);
}
-// Display the text representation of a nullable DateTime.
+ // Display the text representation of a nullable DateTime.
public static void Display(string title, DateTime? dspDT)
{
- string msg = dspDT.ToString();
+ string msg = dspDT.ToString();
- Console.Write("{0} ", title);
- if (String.IsNullOrEmpty(msg))
- Console.WriteLine("The nullable DateTime has no defined value.");
- else
- Console.WriteLine("The current date and time is {0}.", msg);
+ Console.Write($"{title} ");
+ if (string.IsNullOrEmpty(msg))
+ Console.WriteLine("The nullable DateTime has no defined value.");
+ else
+ Console.WriteLine($"The current date and time is {msg}.");
}
}
@@ -40,4 +40,4 @@ public static void Display(string title, DateTime? dspDT)
2) The nullable DateTime has no defined value.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs b/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs
index c8b71550f9b..e98b1ec2a02 100644
--- a/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs
+++ b/snippets/csharp/System/NullableT/op_Explicit/explicit1.cs
@@ -3,16 +3,16 @@
public class Example
{
- public static void Main()
- {
- var nullInt = new Nullable(172);
- // Convert with CInt conversion method.
- Console.WriteLine((int)nullInt);
- // Convert with Convert.ChangeType.
- Console.WriteLine(Convert.ChangeType(nullInt, typeof(int)));
- }
+ public static void Main()
+ {
+ var nullInt = new Nullable(172);
+ // Convert with CInt conversion method.
+ Console.WriteLine((int)nullInt);
+ // Convert with Convert.ChangeType.
+ Console.WriteLine(Convert.ChangeType(nullInt, typeof(int)));
+ }
}
// The example displays the following output:
// 172
// 172
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Object/Equals/equals2.cs b/snippets/csharp/System/Object/Equals/equals2.cs
index e64ae9a67b8..e1f943ae930 100644
--- a/snippets/csharp/System/Object/Equals/equals2.cs
+++ b/snippets/csharp/System/Object/Equals/equals2.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
class Point2
@@ -14,7 +14,7 @@ public Point2(int x, int y)
this.y = y;
}
- public override bool Equals(Object obj)
+ public override bool Equals(object obj)
{
//Check for null and compare run-time types.
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
@@ -28,27 +28,18 @@ public override bool Equals(Object obj)
}
}
- public override int GetHashCode()
- {
- return HashCode.Combine(x, y);
- }
+ public override int GetHashCode() => HashCode.Combine(x, y);
- public override string ToString()
- {
- return String.Format("Point2({0}, {1})", x, y);
- }
+ public override string ToString() => $"Point2({x}, {y})";
}
sealed class Point3D : Point2
{
int z;
- public Point3D(int x, int y, int z) : base(x, y)
- {
- this.z = z;
- }
+ public Point3D(int x, int y, int z) : base(x, y) => this.z = z;
- public override bool Equals(Object obj)
+ public override bool Equals(object obj)
{
Point3D pt3 = obj as Point3D;
if (pt3 == null)
@@ -57,25 +48,19 @@ public override bool Equals(Object obj)
return base.Equals((Point2)obj) && z == pt3.z;
}
- public override int GetHashCode()
- {
- return HashCode.Combine(base.GetHashCode(), z);
- }
+ public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), z);
- public override String ToString()
- {
- return String.Format("Point2({0}, {1}, {2})", x, y, z);
- }
+ public override string ToString() => $"Point2({x}, {y}, {z})";
}
class Example7
{
public static void Main()
{
- Point2 point2D = new Point2(5, 5);
- Point3D point3Da = new Point3D(5, 5, 2);
- Point3D point3Db = new Point3D(5, 5, 2);
- Point3D point3Dc = new Point3D(5, 5, -1);
+ Point2 point2D = new(5, 5);
+ Point3D point3Da = new(5, 5, 2);
+ Point3D point3Db = new(5, 5, 2);
+ Point3D point3Dc = new(5, 5, -1);
Console.WriteLine($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}");
Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}");
diff --git a/snippets/csharp/System/Object/Equals/equals3.cs b/snippets/csharp/System/Object/Equals/equals3.cs
index b03eeb114ab..bcf7e2bf2d3 100644
--- a/snippets/csharp/System/Object/Equals/equals3.cs
+++ b/snippets/csharp/System/Object/Equals/equals3.cs
@@ -1,74 +1,64 @@
-//
+//
using System;
class Rectangle
{
- private Point a, b;
+ private Point a, b;
- public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
- {
- this.a = new Point(upLeftX, upLeftY);
- this.b = new Point(downRightX, downRightY);
- }
-
- public override bool Equals(Object obj)
- {
- // Perform an equality check on two rectangles (Point object pairs).
- if (obj == null || GetType() != obj.GetType())
- return false;
- Rectangle r = (Rectangle)obj;
- return a.Equals(r.a) && b.Equals(r.b);
- }
-
- public override int GetHashCode()
- {
- return Tuple.Create(a, b).GetHashCode();
- }
+ public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
+ {
+ this.a = new(upLeftX, upLeftY);
+ this.b = new(downRightX, downRightY);
+ }
- public override String ToString()
+ public override bool Equals(object obj)
{
- return String.Format("Rectangle({0}, {1}, {2}, {3})",
- a.x, a.y, b.x, b.y);
+ // Perform an equality check on two rectangles (Point object pairs).
+ if (obj == null || GetType() != obj.GetType())
+ return false;
+ Rectangle r = (Rectangle)obj;
+ return a.Equals(r.a) && b.Equals(r.b);
}
+
+ public override int GetHashCode() => Tuple.Create(a, b).GetHashCode();
+
+ public override string ToString() => $"Rectangle({a.x}, {a.y}, {b.x}, {b.y})";
}
class Point
{
- internal int x;
- internal int y;
+ internal int x;
+ internal int y;
- public Point(int X, int Y)
- {
- this.x = X;
- this.y = Y;
- }
+ public Point(int X, int Y)
+ {
+ this.x = X;
+ this.y = Y;
+ }
- public override bool Equals (Object obj)
- {
- // Performs an equality check on two points (integer pairs).
- if (obj == null || GetType() != obj.GetType()) return false;
- Point p = (Point)obj;
- return (x == p.x) && (y == p.y);
- }
+ public override bool Equals(object obj)
+ {
+ // Performs an equality check on two points (integer pairs).
+ if (obj == null || GetType() != obj.GetType()) return false;
+ Point p = (Point)obj;
+ return (x == p.x) && (y == p.y);
+ }
- public override int GetHashCode()
- {
- return Tuple.Create(x, y).GetHashCode();
- }
+ public override int GetHashCode() => Tuple.Create(x, y).GetHashCode();
}
class Example
{
- public static void Main()
- {
- Rectangle r1 = new Rectangle(0, 0, 100, 200);
- Rectangle r2 = new Rectangle(0, 0, 100, 200);
- Rectangle r3 = new Rectangle(0, 0, 150, 200);
+ public static void Main()
+ {
+ Rectangle r1 = new(0, 0, 100, 200);
+ Rectangle r2 = new(0, 0, 100, 200);
+ Rectangle r3 = new(0, 0, 150, 200);
- Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}");
- Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}");
- Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}");
- }
+ Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}");
+ Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}");
+ Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}");
+ }
}
// The example displays the following output:
// Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
diff --git a/snippets/csharp/System/Object/Equals/equals4.cs b/snippets/csharp/System/Object/Equals/equals4.cs
index fae811a3bca..69018b798e1 100644
--- a/snippets/csharp/System/Object/Equals/equals4.cs
+++ b/snippets/csharp/System/Object/Equals/equals4.cs
@@ -1,56 +1,41 @@
-//
+//
using System;
public struct Complex
{
- public double re, im;
+ public double re, im;
- public override bool Equals(Object obj)
- {
- return obj is Complex && this == (Complex)obj;
- }
+ public override bool Equals(object obj) => obj is Complex && this == (Complex)obj;
- public override int GetHashCode()
- {
- return Tuple.Create(re, im).GetHashCode();
- }
+ public override int GetHashCode() => Tuple.Create(re, im).GetHashCode();
- public static bool operator ==(Complex x, Complex y)
- {
- return x.re == y.re && x.im == y.im;
- }
+ public static bool operator ==(Complex x, Complex y) => x.re == y.re && x.im == y.im;
- public static bool operator !=(Complex x, Complex y)
- {
- return !(x == y);
- }
+ public static bool operator !=(Complex x, Complex y) => !(x == y);
- public override String ToString()
- {
- return String.Format("({0}, {1})", re, im);
- }
+ public override string ToString() => $"({re}, {im})";
}
class MyClass
{
- public static void Main()
- {
- Complex cmplx1, cmplx2;
+ public static void Main()
+ {
+ Complex cmplx1, cmplx2;
- cmplx1.re = 4.0;
- cmplx1.im = 1.0;
+ cmplx1.re = 4.0;
+ cmplx1.im = 1.0;
- cmplx2.re = 2.0;
- cmplx2.im = 1.0;
+ cmplx2.re = 2.0;
+ cmplx2.im = 1.0;
- Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}");
- Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
+ Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}");
+ Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
- cmplx2.re = 4.0;
+ cmplx2.re = 4.0;
- Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}");
- Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
- }
+ Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}");
+ Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
+ }
}
// The example displays the following output:
// (4, 1) <> (2, 1): True
diff --git a/snippets/csharp/System/Object/Equals/equals_ref.cs b/snippets/csharp/System/Object/Equals/equals_ref.cs
index 8db6b1dc08a..2f9efcc9277 100644
--- a/snippets/csharp/System/Object/Equals/equals_ref.cs
+++ b/snippets/csharp/System/Object/Equals/equals_ref.cs
@@ -1,38 +1,32 @@
-//
+//
using System;
// Define a reference type that does not override Equals.
public class Person
{
- private string personName;
+ private string personName;
- public Person(string name)
- {
- this.personName = name;
- }
+ public Person(string name) => this.personName = name;
- public override string ToString()
- {
- return this.personName;
- }
+ public override string ToString() => this.personName;
}
public class Example1
{
- public static void Main()
- {
- Person person1a = new Person("John");
- Person person1b = person1a;
- Person person2 = new Person(person1a.ToString());
+ public static void Main()
+ {
+ Person person1a = new("John");
+ Person person1b = person1a;
+ Person person2 = new(person1a.ToString());
- Console.WriteLine("Calling Equals:");
- Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}");
- Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}");
+ Console.WriteLine("Calling Equals:");
+ Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}");
+ Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}");
- Console.WriteLine("\nCasting to an Object and calling Equals:");
- Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}");
- Console.WriteLine($"person1a and person2: {((object) person1a).Equals((object) person2)}");
- }
+ Console.WriteLine("\nCasting to an Object and calling Equals:");
+ Console.WriteLine($"person1a and person1b: {((object)person1a).Equals((object)person1b)}");
+ Console.WriteLine($"person1a and person2: {((object)person1a).Equals((object)person2)}");
+ }
}
// The example displays the following output:
// person1a and person1b: True
diff --git a/snippets/csharp/System/Object/Equals/equals_static2.cs b/snippets/csharp/System/Object/Equals/equals_static2.cs
index d355f135482..8fdc2b1bb92 100644
--- a/snippets/csharp/System/Object/Equals/equals_static2.cs
+++ b/snippets/csharp/System/Object/Equals/equals_static2.cs
@@ -3,60 +3,53 @@
public class RefExample
{
- public static void Main()
- {
- Dog m1 = new Dog("Alaskan Malamute");
- Dog m2 = new Dog("Alaskan Malamute");
- Dog g1 = new Dog("Great Pyrenees");
- Dog g2 = g1;
- Dog d1 = new Dog("Dalmation");
- Dog n1 = null;
- Dog n2 = null;
+ public static void Main()
+ {
+ Dog m1 = new("Alaskan Malamute");
+ Dog m2 = new("Alaskan Malamute");
+ Dog g1 = new("Great Pyrenees");
+ Dog g2 = g1;
+ Dog d1 = new("Dalmatian");
+ Dog n1 = null;
+ Dog n2 = null;
- Console.WriteLine("null = null: {0}", Object.Equals(n1, n2));
- Console.WriteLine("null Reference Equals null: {0}\n", Object.ReferenceEquals(n1, n2));
+ Console.WriteLine($"null = null: {object.Equals(n1, n2)}");
+ Console.WriteLine($"null Reference Equals null: {object.ReferenceEquals(n1, n2)}\n");
- Console.WriteLine("{0} = {1}: {2}", g1, g2, Object.Equals(g1, g2));
- Console.WriteLine("{0} Reference Equals {1}: {2}\n", g1, g2, Object.ReferenceEquals(g1, g2));
+ Console.WriteLine($"{g1} = {g2}: {object.Equals(g1, g2)}");
+ Console.WriteLine($"{g1} Reference Equals {g2}: {object.ReferenceEquals(g1, g2)}\n");
- Console.WriteLine("{0} = {1}: {2}", m1, m2, Object.Equals(m1, m2));
- Console.WriteLine("{0} Reference Equals {1}: {2}\n", m1, m2, Object.ReferenceEquals(m1, m2));
+ Console.WriteLine($"{m1} = {m2}: {object.Equals(m1, m2)}");
+ Console.WriteLine($"{m1} Reference Equals {m2}: {object.ReferenceEquals(m1, m2)}\n");
- Console.WriteLine("{0} = {1}: {2}", m1, d1, Object.Equals(m1, d1));
- Console.WriteLine("{0} Reference Equals {1}: {2}", m1, d1, Object.ReferenceEquals(m1, d1));
- }
+ Console.WriteLine($"{m1} = {d1}: {object.Equals(m1, d1)}");
+ Console.WriteLine($"{m1} Reference Equals {d1}: {object.ReferenceEquals(m1, d1)}");
+ }
}
public class Dog
{
- // Public field.
- public string Breed;
+ // Public field.
+ public string Breed;
- // Class constructor.
- public Dog(string dogBreed)
- {
- this.Breed = dogBreed;
- }
+ // Class constructor.
+ public Dog(string dogBreed) => this.Breed = dogBreed;
- public override bool Equals(Object obj)
- {
- if (obj == null || !(obj is Dog))
- return false;
- else
- return this.Breed == ((Dog) obj).Breed;
- }
+ public override bool Equals(object obj)
+ {
+ if (obj == null || !(obj is Dog))
+ return false;
+ else
+ return this.Breed == ((Dog)obj).Breed;
+ }
- public override int GetHashCode()
- {
- return this.Breed.GetHashCode();
- }
+ public override int GetHashCode() => this.Breed.GetHashCode();
- public override string ToString()
- {
- return this.Breed;
- }
+ public override string ToString() => this.Breed;
}
+
// The example displays the following output:
+
// null = null: True
// null Reference Equals null: True
//
@@ -66,6 +59,7 @@ public override string ToString()
// Alaskan Malamute = Alaskan Malamute: True
// Alaskan Malamute Reference Equals Alaskan Malamute: False
//
-// Alaskan Malamute = Dalmation: False
-// Alaskan Malamute Reference Equals Dalmation: False
+// Alaskan Malamute = Dalmatian: False
+// Alaskan Malamute Reference Equals Dalmatian: False
+
//
diff --git a/snippets/csharp/System/Object/Equals/equals_val1.cs b/snippets/csharp/System/Object/Equals/equals_val1.cs
index 533e01bf098..d8bb277ceb0 100644
--- a/snippets/csharp/System/Object/Equals/equals_val1.cs
+++ b/snippets/csharp/System/Object/Equals/equals_val1.cs
@@ -1,20 +1,20 @@
-using System;
+using System;
public class Example2
{
- public static void Main()
- {
- //
- byte value1 = 12;
- int value2 = 12;
+ public static void Main()
+ {
+ //
+ byte value1 = 12;
+ int value2 = 12;
- object object1 = value1;
- object object2 = value2;
+ object object1 = value1;
+ object object2 = value2;
- Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}");
+ Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}");
- // The example displays the following output:
- // 12 (Byte) = 12 (Int32): False
- //
- }
+ // The example displays the following output:
+ // 12 (Byte) = 12 (Int32): False
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/Equals/equals_val2.cs b/snippets/csharp/System/Object/Equals/equals_val2.cs
index 2c128e53757..fa6ab1ce4cd 100644
--- a/snippets/csharp/System/Object/Equals/equals_val2.cs
+++ b/snippets/csharp/System/Object/Equals/equals_val2.cs
@@ -4,32 +4,26 @@
// Define a value type that does not override Equals.
public struct Person3
{
- private string personName;
+ private string personName;
- public Person3(string name)
- {
- this.personName = name;
- }
+ public Person3(string name) => this.personName = name;
- public override string ToString()
- {
- return this.personName;
- }
+ public override string ToString() => this.personName;
}
public struct Example3
{
- public static void Main()
- {
- Person3 person1 = new Person3("John");
- Person3 person2 = new Person3("John");
+ public static void Main()
+ {
+ Person3 person1 = new("John");
+ Person3 person2 = new("John");
- Console.WriteLine("Calling Equals:");
- Console.WriteLine(person1.Equals(person2));
+ Console.WriteLine("Calling Equals:");
+ Console.WriteLine(person1.Equals(person2));
- Console.WriteLine("\nCasting to an Object and calling Equals:");
- Console.WriteLine(((object) person1).Equals((object) person2));
- }
+ Console.WriteLine("\nCasting to an Object and calling Equals:");
+ Console.WriteLine(((object)person1).Equals((object)person2));
+ }
}
// The example displays the following output:
// Calling Equals:
diff --git a/snippets/csharp/System/Object/Equals/equalsoverride.cs b/snippets/csharp/System/Object/Equals/equalsoverride.cs
index b8da28c242f..7330a16c3e3 100644
--- a/snippets/csharp/System/Object/Equals/equalsoverride.cs
+++ b/snippets/csharp/System/Object/Equals/equalsoverride.cs
@@ -3,39 +3,36 @@
//
public class Person6
{
- private string idNumber;
- private string personName;
+ private string idNumber;
+ private string personName;
- public Person6(string name, string id)
- {
- this.personName = name;
- this.idNumber = id;
- }
+ public Person6(string name, string id)
+ {
+ this.personName = name;
+ this.idNumber = id;
+ }
- public override bool Equals(Object obj)
- {
- Person6 personObj = obj as Person6;
- if (personObj == null)
- return false;
- else
- return idNumber.Equals(personObj.idNumber);
- }
+ public override bool Equals(object obj)
+ {
+ Person6 personObj = obj as Person6;
+ if (personObj == null)
+ return false;
+ else
+ return idNumber.Equals(personObj.idNumber);
+ }
- public override int GetHashCode()
- {
- return this.idNumber.GetHashCode();
- }
+ public override int GetHashCode() => this.idNumber.GetHashCode();
}
public class Example6
{
- public static void Main()
- {
- Person6 p1 = new Person6("John", "63412895");
- Person6 p2 = new Person6("Jack", "63412895");
- Console.WriteLine(p1.Equals(p2));
- Console.WriteLine(Object.Equals(p1, p2));
- }
+ public static void Main()
+ {
+ Person6 p1 = new("John", "63412895");
+ Person6 p2 = new("Jack", "63412895");
+ Console.WriteLine(p1.Equals(p2));
+ Console.WriteLine(object.Equals(p1, p2));
+ }
}
// The example displays the following output:
// True
diff --git a/snippets/csharp/System/Object/Equals/equalssb1.cs b/snippets/csharp/System/Object/Equals/equalssb1.cs
index b51fd0e2a2a..368ba138c41 100644
--- a/snippets/csharp/System/Object/Equals/equalssb1.cs
+++ b/snippets/csharp/System/Object/Equals/equalssb1.cs
@@ -1,21 +1,21 @@
-//
+//
using System;
using System.Text;
public class Example5
{
- public static void Main()
- {
- StringBuilder sb1 = new StringBuilder("building a string...");
- StringBuilder sb2 = new StringBuilder("building a string...");
+ public static void Main()
+ {
+ StringBuilder sb1 = new("building a string...");
+ StringBuilder sb2 = new("building a string...");
- Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}");
- Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}");
- Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}");
+ Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}");
+ Console.WriteLine($"((Object) sb1).Equals(sb2): {((object)sb1).Equals(sb2)}");
+ Console.WriteLine($"Object.Equals(sb1, sb2): {object.Equals(sb1, sb2)}");
- Object sb3 = new StringBuilder("building a string...");
- Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}");
- }
+ object sb3 = new StringBuilder("building a string...");
+ Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}");
+ }
}
// The example displays the following output:
// sb1.Equals(sb2): True
diff --git a/snippets/csharp/System/Object/Finalize/finalize1.cs b/snippets/csharp/System/Object/Finalize/finalize1.cs
index 2179ebbccb4..7f8bffb1641 100644
--- a/snippets/csharp/System/Object/Finalize/finalize1.cs
+++ b/snippets/csharp/System/Object/Finalize/finalize1.cs
@@ -4,36 +4,31 @@
public class ExampleClass
{
- Stopwatch sw;
+ Stopwatch sw;
- public ExampleClass()
- {
- sw = Stopwatch.StartNew();
- Console.WriteLine("Instantiated object");
- }
+ public ExampleClass()
+ {
+ sw = Stopwatch.StartNew();
+ Console.WriteLine("Instantiated object");
+ }
- public void ShowDuration()
- {
- Console.WriteLine("This instance of {0} has been in existence for {1}",
- this, sw.Elapsed);
- }
+ public void ShowDuration() => Console.WriteLine($"This instance of {this} has been in existence for {sw.Elapsed}");
- ~ExampleClass()
- {
- Console.WriteLine("Finalizing object");
- sw.Stop();
- Console.WriteLine("This instance of {0} has been in existence for {1}",
- this, sw.Elapsed);
- }
+ ~ExampleClass()
+ {
+ Console.WriteLine("Finalizing object");
+ sw.Stop();
+ Console.WriteLine($"This instance of {this} has been in existence for {sw.Elapsed}");
+ }
}
public class Demo
{
- public static void Main()
- {
- ExampleClass ex = new ExampleClass();
- ex.ShowDuration();
- }
+ public static void Main()
+ {
+ ExampleClass ex = new();
+ ex.ShowDuration();
+ }
}
// The example displays output like the following:
// Instantiated object
diff --git a/snippets/csharp/System/Object/Finalize/finalize_safe.cs b/snippets/csharp/System/Object/Finalize/finalize_safe.cs
index 3206babdc10..e21fdb54061 100644
--- a/snippets/csharp/System/Object/Finalize/finalize_safe.cs
+++ b/snippets/csharp/System/Object/Finalize/finalize_safe.cs
@@ -51,7 +51,7 @@ public FileAssociationInfo(string fileExtension)
if (retVal != ERROR_SUCCESS)
throw new Win32Exception(retVal);
// Instantiate the first SafeRegistryHandle.
- hExtHandle = new SafeRegistryHandle(hExtension, true);
+ hExtHandle = new(hExtension, true);
string appId = new(' ', MAX_PATH);
uint appIdLength = (uint)appId.Length;
@@ -83,7 +83,7 @@ public FileAssociationInfo(string fileExtension)
throw new Win32Exception(retVal);
// Instantiate the second SafeRegistryHandle.
- hAppIdHandle = new SafeRegistryHandle(hAppId, true);
+ hAppIdHandle = new(hAppId, true);
// Get the executable name for this file type.
string exePath = new(' ', MAX_PATH);
@@ -117,14 +117,14 @@ public FileAssociationInfo(string fileExtension)
public string Open
{
- get { return openCmd; }
+ get => openCmd;
set
{
if (hAppIdHandle.IsInvalid | hAppIdHandle.IsClosed)
throw new InvalidOperationException("Cannot write to registry key.");
if (!File.Exists(value))
{
- string message = string.Format("'{0}' does not exist", value);
+ string message = $"'{value}' does not exist";
throw new FileNotFoundException(message);
}
string cmd = value + " %1";
diff --git a/snippets/csharp/System/Object/GetHashCode/direct1.cs b/snippets/csharp/System/Object/GetHashCode/direct1.cs
index 666b1dff966..81d36c5d115 100644
--- a/snippets/csharp/System/Object/GetHashCode/direct1.cs
+++ b/snippets/csharp/System/Object/GetHashCode/direct1.cs
@@ -3,48 +3,37 @@
public struct Number
{
- private int n;
+ private int n;
- public Number(int value)
- {
- n = value;
- }
+ public Number(int value) => n = value;
- public int Value
- {
- get { return n; }
- }
+ public int Value => n;
- public override bool Equals(Object obj)
- {
- if (obj == null || ! (obj is Number))
- return false;
- else
- return n == ((Number) obj).n;
- }
+ public override bool Equals(object obj)
+ {
+ if (obj == null || !(obj is Number))
+ return false;
+ else
+ return n == ((Number)obj).n;
+ }
- public override int GetHashCode()
- {
- return n;
- }
+ public override int GetHashCode() => n;
- public override string ToString()
- {
- return n.ToString();
- }
+ public override string ToString() => n.ToString();
}
public class Example1
{
- public static void Main()
- {
- Random rnd = new Random();
- for (int ctr = 0; ctr <= 9; ctr++) {
- int randomN = rnd.Next(Int32.MinValue, Int32.MaxValue);
- Number n = new Number(randomN);
- Console.WriteLine("n = {0,12}, hash code = {1,12}", n, n.GetHashCode());
- }
- }
+ public static void Main()
+ {
+ Random rnd = new();
+ for (int ctr = 0; ctr <= 9; ctr++)
+ {
+ int randomN = rnd.Next(int.MinValue, int.MaxValue);
+ Number n = new(randomN);
+ Console.WriteLine($"n = {n,12}, hash code = {n.GetHashCode(),12}");
+ }
+ }
}
// The example displays output like the following:
// n = -634398368, hash code = -634398368
diff --git a/snippets/csharp/System/Object/GetHashCode/shift1.cs b/snippets/csharp/System/Object/GetHashCode/shift1.cs
index c9f7c4431f9..26ab57852b9 100644
--- a/snippets/csharp/System/Object/GetHashCode/shift1.cs
+++ b/snippets/csharp/System/Object/GetHashCode/shift1.cs
@@ -8,22 +8,19 @@ public struct Point
public Point(int x, int y)
{
- this.x = x;
- this.y = y;
+ this.x = x;
+ this.y = y;
}
- public override bool Equals(Object obj)
+ public override bool Equals(object obj)
{
- if (!(obj is Point)) return false;
+ if (!(obj is Point)) return false;
- Point p = (Point) obj;
- return x == p.x & y == p.y;
+ Point p = (Point)obj;
+ return x == p.x & y == p.y;
}
- public override int GetHashCode()
- {
- return ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode();
- }
+ public override int GetHashCode() => ShiftAndWrap(x.GetHashCode(), 2) ^ y.GetHashCode();
private int ShiftAndWrap(int value, int positions)
{
@@ -40,14 +37,14 @@ private int ShiftAndWrap(int value, int positions)
public class Example2
{
- public static void Main()
- {
- Point pt = new Point(5, 8);
+ public static void Main()
+ {
+ Point pt = new(5, 8);
Console.WriteLine(pt.GetHashCode());
- pt = new Point(8, 5);
+ pt = new(8, 5);
Console.WriteLine(pt.GetHashCode());
- }
+ }
}
// The example displays the following output:
// 28
@@ -56,7 +53,7 @@ public static void Main()
public class Utility
{
- //
+ //
public int ShiftAndWrap(int value, int positions)
{
positions = positions & 0x1F;
@@ -68,5 +65,5 @@ public int ShiftAndWrap(int value, int positions)
// Shift and wrap the discarded bits.
return BitConverter.ToInt32(BitConverter.GetBytes((number << positions) | wrapped), 0);
}
- //
+ //
}
diff --git a/snippets/csharp/System/Object/GetHashCode/xor1.cs b/snippets/csharp/System/Object/GetHashCode/xor1.cs
index a37b2efa1b4..d37ec11bd41 100644
--- a/snippets/csharp/System/Object/GetHashCode/xor1.cs
+++ b/snippets/csharp/System/Object/GetHashCode/xor1.cs
@@ -9,34 +9,31 @@ public struct Point2
public Point2(int x, int y)
{
- this.x = x;
- this.y = y;
+ this.x = x;
+ this.y = y;
}
- public override bool Equals(Object obj)
+ public override bool Equals(object obj)
{
- if (! (obj is Point2)) return false;
+ if (!(obj is Point2)) return false;
- Point2 p = (Point2) obj;
- return x == p.x & y == p.y;
+ Point2 p = (Point2)obj;
+ return x == p.x & y == p.y;
}
- public override int GetHashCode()
- {
- return x ^ y;
- }
+ public override int GetHashCode() => x ^ y;
}
public class Example3
{
- public static void Main()
- {
- Point2 pt = new Point2(5, 8);
- Console.WriteLine(pt.GetHashCode());
+ public static void Main()
+ {
+ Point2 pt = new(5, 8);
+ Console.WriteLine(pt.GetHashCode());
- pt = new Point2(8, 5);
- Console.WriteLine(pt.GetHashCode());
- }
+ pt = new(8, 5);
+ Console.WriteLine(pt.GetHashCode());
+ }
}
// The example displays the following output:
// 13
diff --git a/snippets/csharp/System/Object/GetHashCode/xor2.cs b/snippets/csharp/System/Object/GetHashCode/xor2.cs
index d8ad45dd2f9..bac63c34bf7 100644
--- a/snippets/csharp/System/Object/GetHashCode/xor2.cs
+++ b/snippets/csharp/System/Object/GetHashCode/xor2.cs
@@ -8,39 +8,36 @@ public struct Point3
public Point3(int x, int y)
{
- this.x = x;
- this.y = y;
+ this.x = x;
+ this.y = y;
}
- public override bool Equals(Object obj)
+ public override bool Equals(object obj)
{
if (obj is Point3)
{
- Point3 p = (Point3) obj;
+ Point3 p = (Point3)obj;
return x == p.x & y == p.y;
}
else
{
return false;
- }
+ }
}
- public override int GetHashCode()
- {
- return HashCode.Combine(x, y);
- }
+ public override int GetHashCode() => HashCode.Combine(x, y);
}
public class Example
{
- public static void Main()
- {
- Point3 pt = new Point3(5, 8);
+ public static void Main()
+ {
+ Point3 pt = new(5, 8);
Console.WriteLine(pt.GetHashCode());
- pt = new Point3(8, 5);
+ pt = new(8, 5);
Console.WriteLine(pt.GetHashCode());
- }
+ }
}
// The example displays output similar to the following.
// Note: HashCode.Combine results are not stable across .NET versions.
diff --git a/snippets/csharp/System/Object/GetType/GetTypeEx2.cs b/snippets/csharp/System/Object/GetType/GetTypeEx2.cs
index 1c3edbca961..7c6d5a6b520 100644
--- a/snippets/csharp/System/Object/GetType/GetTypeEx2.cs
+++ b/snippets/csharp/System/Object/GetType/GetTypeEx2.cs
@@ -1,36 +1,36 @@
using System;
-public class Example
+public class ObjectGetTypeExample2
{
- public static void Main()
- {
- //
- object[] values = { (int) 12, (long) 10653, (byte) 12, (sbyte) -5,
+ public static void Run()
+ {
+ //
+ object[] values = { (int) 12, (long) 10653, (byte) 12, (sbyte) -5,
16.3, "string" };
- foreach (var value in values) {
- Type t = value.GetType();
- if (t.Equals(typeof(byte)))
- Console.WriteLine("{0} is an unsigned byte.", value);
- else if (t.Equals(typeof(sbyte)))
- Console.WriteLine("{0} is a signed byte.", value);
- else if (t.Equals(typeof(int)))
- Console.WriteLine("{0} is a 32-bit integer.", value);
- else if (t.Equals(typeof(long)))
- Console.WriteLine("{0} is a 64-bit integer.", value);
- else if (t.Equals(typeof(double)))
- Console.WriteLine("{0} is a double-precision floating point.",
- value);
- else
- Console.WriteLine("'{0}' is another data type.", value);
- }
+ foreach (object value in values)
+ {
+ Type t = value.GetType();
+ if (t.Equals(typeof(byte)))
+ Console.WriteLine($"{value} is an unsigned byte.");
+ else if (t.Equals(typeof(sbyte)))
+ Console.WriteLine($"{value} is a signed byte.");
+ else if (t.Equals(typeof(int)))
+ Console.WriteLine($"{value} is a 32-bit integer.");
+ else if (t.Equals(typeof(long)))
+ Console.WriteLine($"{value} is a 64-bit integer.");
+ else if (t.Equals(typeof(double)))
+ Console.WriteLine($"{value} is a double-precision floating point.");
+ else
+ Console.WriteLine($"'{value}' is another data type.");
+ }
- // The example displays the following output:
- // 12 is a 32-bit integer.
- // 10653 is a 64-bit integer.
- // 12 is an unsigned byte.
- // -5 is a signed byte.
- // 16.3 is a double-precision floating point.
- // 'string' is another data type.
- //
- }
+ // The example displays the following output:
+ // 12 is a 32-bit integer.
+ // 10653 is a 64-bit integer.
+ // 12 is an unsigned byte.
+ // -5 is a signed byte.
+ // 16.3 is a double-precision floating point.
+ // 'string' is another data type.
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/GetType/Program.cs b/snippets/csharp/System/Object/GetType/Program.cs
new file mode 100644
index 00000000000..5fd825006c1
--- /dev/null
+++ b/snippets/csharp/System/Object/GetType/Program.cs
@@ -0,0 +1,3 @@
+Test.Run();
+ObjectGetTypeExample1.Run();
+ObjectGetTypeExample2.Run();
diff --git a/snippets/csharp/System/Object/GetType/Project.csproj b/snippets/csharp/System/Object/GetType/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/Object/GetType/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/Object/GetType/gettype.cs b/snippets/csharp/System/Object/GetType/gettype.cs
index 6979a2f7601..7215196251f 100644
--- a/snippets/csharp/System/Object/GetType/gettype.cs
+++ b/snippets/csharp/System/Object/GetType/gettype.cs
@@ -1,26 +1,28 @@
//
using System;
-public class MyBaseClass {
+public class MyBaseClass
+{
}
-public class MyDerivedClass: MyBaseClass {
+public class MyDerivedClass : MyBaseClass
+{
}
public class Test
{
- public static void Main()
- {
- MyBaseClass myBase = new MyBaseClass();
- MyDerivedClass myDerived = new MyDerivedClass();
- object o = myDerived;
- MyBaseClass b = myDerived;
+ public static void Run()
+ {
+ MyBaseClass myBase = new();
+ MyDerivedClass myDerived = new();
+ object o = myDerived;
+ MyBaseClass b = myDerived;
- Console.WriteLine("mybase: Type is {0}", myBase.GetType());
- Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
- Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
- Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
- }
+ Console.WriteLine($"mybase: Type is {myBase.GetType()}");
+ Console.WriteLine($"myDerived: Type is {myDerived.GetType()}");
+ Console.WriteLine($"object o = myDerived: Type is {o.GetType()}");
+ Console.WriteLine($"MyBaseClass b = myDerived: Type is {b.GetType()}");
+ }
}
// The example displays the following output:
// mybase: Type is MyBaseClass
diff --git a/snippets/csharp/System/Object/GetType/gettype1.cs b/snippets/csharp/System/Object/GetType/gettype1.cs
index f2774e02f1d..5f5f0a7ffc6 100644
--- a/snippets/csharp/System/Object/GetType/gettype1.cs
+++ b/snippets/csharp/System/Object/GetType/gettype1.cs
@@ -1,22 +1,20 @@
using System;
-public class Example
+public class ObjectGetTypeExample1
{
- public static void Main()
- {
- //
- int n1 = 12;
- int n2 = 82;
- long n3 = 12;
+ public static void Run()
+ {
+ //
+ int n1 = 12;
+ int n2 = 82;
+ long n3 = 12;
- Console.WriteLine("n1 and n2 are the same type: {0}",
- Object.ReferenceEquals(n1.GetType(), n2.GetType()));
- Console.WriteLine("n1 and n3 are the same type: {0}",
- Object.ReferenceEquals(n1.GetType(), n3.GetType()));
+ Console.WriteLine($"n1 and n2 are the same type: {object.ReferenceEquals(n1.GetType(), n2.GetType())}");
+ Console.WriteLine($"n1 and n3 are the same type: {object.ReferenceEquals(n1.GetType(), n3.GetType())}");
- // The example displays the following output:
- // n1 and n2 are the same type: True
- // n1 and n3 are the same type: False
- //
- }
+ // The example displays the following output:
+ // n1 and n2 are the same type: True
+ // n1 and n3 are the same type: False
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs b/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs
index d1e01ad251a..7382e05a1a9 100644
--- a/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs
+++ b/snippets/csharp/System/Object/MemberwiseClone/memberwiseclone1.cs
@@ -5,10 +5,7 @@ public class IdInfo
{
public int IdNumber;
- public IdInfo(int IdNumber)
- {
- this.IdNumber = IdNumber;
- }
+ public IdInfo(int IdNumber) => this.IdNumber = IdNumber;
}
public class Person
@@ -17,15 +14,12 @@ public class Person
public string Name;
public IdInfo IdInfo;
- public Person ShallowCopy()
- {
- return (Person)MemberwiseClone();
- }
+ public Person ShallowCopy() => (Person)MemberwiseClone();
public Person DeepCopy()
{
Person other = (Person)MemberwiseClone();
- other.IdInfo = new IdInfo(IdInfo.IdNumber);
+ other.IdInfo = new(IdInfo.IdNumber);
return other;
}
}
@@ -39,7 +33,7 @@ public static void Main()
{
Age = 42,
Name = "Sam",
- IdInfo = new IdInfo(6565)
+ IdInfo = new(6565)
};
// Perform a shallow copy of p1 and assign it to p2.
@@ -83,7 +77,7 @@ public static void DisplayValues(Person p)
}
/* The example displays the following output:
- *
+ *
* Original values of p1 and p2:
p1 instance values:
Name: Sam, Age: 42
diff --git a/snippets/csharp/System/Object/Overview/ObjectX.cs b/snippets/csharp/System/Object/Overview/ObjectX.cs
index 9fdea2c6e6b..21a694f6ef0 100644
--- a/snippets/csharp/System/Object/Overview/ObjectX.cs
+++ b/snippets/csharp/System/Object/Overview/ObjectX.cs
@@ -1,4 +1,4 @@
-//Types:System.Object
+//Types:System.Object
//
using System;
@@ -20,33 +20,24 @@ public override bool Equals(object obj)
if (obj.GetType() != this.GetType()) return false;
// Return true if x and y fields match.
- var other = (Point) obj;
+ var other = (Point)obj;
return (this.x == other.x) && (this.y == other.y);
}
//
//
// Return the XOR of the x and y fields.
- public override int GetHashCode()
- {
- return x ^ y;
- }
+ public override int GetHashCode() => x ^ y;
//
//
// Return the point's value as a string.
- public override String ToString()
- {
- return $"({x}, {y})";
- }
+ public override string ToString() => $"({x}, {y})";
//
//
// Return a copy of this point object by making a simple field copy.
- public Point Copy()
- {
- return (Point) this.MemberwiseClone();
- }
+ public Point Copy() => (Point)this.MemberwiseClone();
//
}
@@ -55,7 +46,7 @@ public sealed class App
static void Main()
{
// Construct a Point object.
- var p1 = new Point(1,2);
+ var p1 = new Point(1, 2);
// Make another Point object that is a copy of the first.
var p2 = p1.Copy();
@@ -63,18 +54,18 @@ static void Main()
// Make another variable that references the first Point object.
var p3 = p1;
- //
+ //
// The line below displays false because p1 and p2 refer to two different objects.
- Console.WriteLine(Object.ReferenceEquals(p1, p2));
+ Console.WriteLine(object.ReferenceEquals(p1, p2));
//
//
// The line below displays true because p1 and p2 refer to two different objects that have the same value.
- Console.WriteLine(Object.Equals(p1, p2));
+ Console.WriteLine(object.Equals(p1, p2));
//
// The line below displays true because p1 and p3 refer to one object.
- Console.WriteLine(Object.ReferenceEquals(p1, p3));
+ Console.WriteLine(object.ReferenceEquals(p1, p3));
//
// The line below displays: p1's value is: (1, 2)
diff --git a/snippets/csharp/System/Object/ReferenceEquals/Program.cs b/snippets/csharp/System/Object/ReferenceEquals/Program.cs
new file mode 100644
index 00000000000..c5491b97f1d
--- /dev/null
+++ b/snippets/csharp/System/Object/ReferenceEquals/Program.cs
@@ -0,0 +1,3 @@
+MyClass.Run();
+ObjectReferenceEqualsExample1.Run();
+ObjectReferenceEqualsExample2.Run();
diff --git a/snippets/csharp/System/Object/ReferenceEquals/Project.csproj b/snippets/csharp/System/Object/ReferenceEquals/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/Object/ReferenceEquals/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs
index ce5acd6f484..4e15698ca94 100644
--- a/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs
+++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequals.cs
@@ -1,22 +1,23 @@
using System;
-class MyClass {
+class MyClass
+{
+ public static void Run()
+ {
+ //
+ object o = null;
+ object p = null;
+ object q = new();
- static void Main() {
- //
- object o = null;
- object p = null;
- object q = new Object();
+ Console.WriteLine(object.ReferenceEquals(o, p));
+ p = q;
+ Console.WriteLine(object.ReferenceEquals(p, q));
+ Console.WriteLine(object.ReferenceEquals(o, p));
- Console.WriteLine(Object.ReferenceEquals(o, p));
- p = q;
- Console.WriteLine(Object.ReferenceEquals(p, q));
- Console.WriteLine(Object.ReferenceEquals(o, p));
-
- // This code produces the following output:
- // True
- // True
- // False
- //
- }
+ // This code produces the following output:
+ // True
+ // True
+ // False
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs
index 9c3204be773..c6ede57640a 100644
--- a/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs
+++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequals4.cs
@@ -1,17 +1,17 @@
using System;
-public class Example
+public class ObjectReferenceEqualsExample1
{
- public static void Main()
- {
- //
- int int1 = 3;
- Console.WriteLine(Object.ReferenceEquals(int1, int1));
- Console.WriteLine(int1.GetType().IsValueType);
+ public static void Run()
+ {
+ //
+ int int1 = 3;
+ Console.WriteLine(object.ReferenceEquals(int1, int1));
+ Console.WriteLine(int1.GetType().IsValueType);
- // The example displays the following output:
- // False
- // True
- //
- }
+ // The example displays the following output:
+ // False
+ // True
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs b/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs
index 82eb588bce7..1073ab78bd1 100644
--- a/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs
+++ b/snippets/csharp/System/Object/ReferenceEquals/referenceequalsa.cs
@@ -1,28 +1,26 @@
using System;
-public class Example
+public class ObjectReferenceEqualsExample2
{
- public static void Main()
- {
- //
- String s1 = "String1";
- String s2 = "String1";
- Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2));
- Console.WriteLine("{0} interned: {1}", s1,
- String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes");
+ public static void Run()
+ {
+ //
+ string s1 = "String1";
+ string s2 = "String1";
+ Console.WriteLine($"s1 = s2: {object.ReferenceEquals(s1, s2)}");
+ Console.WriteLine($"{s1} interned: {(string.IsNullOrEmpty(string.IsInterned(s1)) ? "No" : "Yes")}");
- String suffix = "A";
- String s3 = "String" + suffix;
- String s4 = "String" + suffix;
- Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4));
- Console.WriteLine("{0} interned: {1}", s3,
- String.IsNullOrEmpty(String.IsInterned(s3)) ? "No" : "Yes");
+ string suffix = "A";
+ string s3 = "String" + suffix;
+ string s4 = "String" + suffix;
+ Console.WriteLine($"s3 = s4: {object.ReferenceEquals(s3, s4)}");
+ Console.WriteLine($"{s3} interned: {(string.IsNullOrEmpty(string.IsInterned(s3)) ? "No" : "Yes")}");
- // The example displays the following output:
- // s1 = s2: True
- // String1 interned: Yes
- // s3 = s4: False
- // StringA interned: No
- //
- }
+ // The example displays the following output:
+ // s1 = s2: True
+ // String1 interned: Yes
+ // s3 = s4: False
+ // StringA interned: No
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/ToString/array1.cs b/snippets/csharp/System/Object/ToString/array1.cs
index cf7b237be0c..6ed34b9f10a 100644
--- a/snippets/csharp/System/Object/ToString/array1.cs
+++ b/snippets/csharp/System/Object/ToString/array1.cs
@@ -3,18 +3,18 @@
public class Example
{
- public static void Main()
- {
- //
- int[] values = { 1, 2, 4, 8, 16, 32, 64, 128 };
- Console.WriteLine(values.ToString());
+ public static void Main()
+ {
+ //
+ int[] values = { 1, 2, 4, 8, 16, 32, 64, 128 };
+ Console.WriteLine(values.ToString());
- List list = new List(values);
- Console.WriteLine(list.ToString());
+ List list = new(values);
+ Console.WriteLine(list.ToString());
- // The example displays the following output:
- // System.Int32[]
- // System.Collections.Generic.List`1[System.Int32]
- //
- }
+ // The example displays the following output:
+ // System.Int32[]
+ // System.Collections.Generic.List`1[System.Int32]
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/ToString/customize1.cs b/snippets/csharp/System/Object/ToString/customize1.cs
index 6a8593a7b6c..d7fc7c42bb3 100644
--- a/snippets/csharp/System/Object/ToString/customize1.cs
+++ b/snippets/csharp/System/Object/ToString/customize1.cs
@@ -4,34 +4,33 @@
public class CList : List
{
- public CList(IEnumerable collection) : base(collection)
- { }
+ public CList(IEnumerable collection) : base(collection)
+ { }
- public CList() : base()
- {}
+ public CList() : base()
+ { }
- public override string ToString()
- {
- string retVal = string.Empty;
- foreach (T item in this) {
- if (string.IsNullOrEmpty(retVal))
- retVal += item.ToString();
- else
- retVal += string.Format(", {0}", item);
- }
- return retVal;
- }
+ public override string ToString()
+ {
+ string retVal = string.Empty;
+ foreach (T item in this)
+ {
+ if (string.IsNullOrEmpty(retVal))
+ retVal += item.ToString();
+ else
+ retVal += $", {item}";
+ }
+ return retVal;
+ }
}
public class Example2
{
- public static void Main()
- {
- var list2 = new CList();
- list2.Add(1000);
- list2.Add(2000);
- Console.WriteLine(list2.ToString());
- }
+ public static void Main()
+ {
+ var list2 = new CList() { 1000, 2000 };
+ Console.WriteLine(list2.ToString());
+ }
}
// The example displays the following output:
// 1000, 2000
diff --git a/snippets/csharp/System/Object/ToString/customize2.cs b/snippets/csharp/System/Object/ToString/customize2.cs
index bc7495d7690..3161e420315 100644
--- a/snippets/csharp/System/Object/ToString/customize2.cs
+++ b/snippets/csharp/System/Object/ToString/customize2.cs
@@ -4,42 +4,43 @@
public static class StringExtensions
{
- public static string ToString2(this List l)
- {
- string retVal = string.Empty;
- foreach (T item in l)
- retVal += string.Format("{0}{1}", string.IsNullOrEmpty(retVal) ?
- "" : ", ",
- item);
- return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
- }
+ public static string ToString2(this List l)
+ {
+ string retVal = string.Empty;
+ foreach (T item in l)
+ retVal += $"{(string.IsNullOrEmpty(retVal) ?
+ "" : ", ")}{item}";
+ return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
+ }
- public static string ToString(this List l, string fmt)
- {
- string retVal = string.Empty;
- foreach (T item in l) {
- IFormattable ifmt = item as IFormattable;
- if (ifmt != null)
- retVal += string.Format("{0}{1}",
- string.IsNullOrEmpty(retVal) ?
- "" : ", ", ifmt.ToString(fmt, null));
- else
- retVal += ToString2(l);
- }
- return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
- }
+ public static string ToString(this List l, string fmt)
+ {
+ string retVal = string.Empty;
+ foreach (T item in l)
+ {
+ IFormattable ifmt = item as IFormattable;
+ if (ifmt != null)
+ retVal += $"{(string.IsNullOrEmpty(retVal) ?
+ "" : ", ")}{ifmt.ToString(fmt, null)}";
+ else
+ retVal += ToString2(l);
+ }
+ return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
+ }
}
public class Example3
{
- public static void Main()
- {
- List list = new List();
- list.Add(1000);
- list.Add(2000);
- Console.WriteLine(list.ToString2());
- Console.WriteLine(list.ToString("N0"));
- }
+ public static void Main()
+ {
+ List list = new()
+ {
+ 1000,
+ 2000
+ };
+ Console.WriteLine(list.ToString2());
+ Console.WriteLine(list.ToString("N0"));
+ }
}
// The example displays the following output:
// { 1000, 2000 }
diff --git a/snippets/csharp/System/Object/ToString/tostring1.cs b/snippets/csharp/System/Object/ToString/tostring1.cs
index 4651e461af2..ffe03decb9e 100644
--- a/snippets/csharp/System/Object/ToString/tostring1.cs
+++ b/snippets/csharp/System/Object/ToString/tostring1.cs
@@ -2,14 +2,14 @@
public class Example4
{
- public static void Main()
- {
- //
- Object obj = new Object();
- Console.WriteLine(obj.ToString());
+ public static void Main()
+ {
+ //
+ object obj = new();
+ Console.WriteLine(obj.ToString());
- // The example displays the following output:
- // System.Object
- //
- }
+ // The example displays the following output:
+ // System.Object
+ //
+ }
}
diff --git a/snippets/csharp/System/Object/ToString/tostring2.cs b/snippets/csharp/System/Object/ToString/tostring2.cs
index 651cd69732c..d4daca9616b 100644
--- a/snippets/csharp/System/Object/ToString/tostring2.cs
+++ b/snippets/csharp/System/Object/ToString/tostring2.cs
@@ -4,18 +4,18 @@
namespace Examples
{
- public class Object1
- {
- }
+ public class Object1
+ {
+ }
}
public class Example5
{
- public static void Main()
- {
- object obj1 = new Object1();
- Console.WriteLine(obj1.ToString());
- }
+ public static void Main()
+ {
+ object obj1 = new Object1();
+ Console.WriteLine(obj1.ToString());
+ }
}
// The example displays the following output:
// Examples.Object1
diff --git a/snippets/csharp/System/Object/ToString/tostring3.cs b/snippets/csharp/System/Object/ToString/tostring3.cs
index 8752cac0b47..b9101a8114f 100644
--- a/snippets/csharp/System/Object/ToString/tostring3.cs
+++ b/snippets/csharp/System/Object/ToString/tostring3.cs
@@ -3,26 +3,20 @@
public class Object2
{
- private object value;
+ private object value;
- public Object2(object value)
- {
- this.value = value;
- }
+ public Object2(object value) => this.value = value;
- public override string ToString()
- {
- return base.ToString() + ": " + value.ToString();
- }
+ public override string ToString() => base.ToString() + ": " + value.ToString();
}
public class Example6
{
- public static void Main()
- {
- Object2 obj2 = new Object2('a');
- Console.WriteLine(obj2.ToString());
- }
+ public static void Main()
+ {
+ Object2 obj2 = new('a');
+ Console.WriteLine(obj2.ToString());
+ }
}
// The example displays the following output:
// Object2: a
diff --git a/snippets/csharp/System/Object/ToString/tostringoverload1.cs b/snippets/csharp/System/Object/ToString/tostringoverload1.cs
index 83cf6df70ad..81a7c57be79 100644
--- a/snippets/csharp/System/Object/ToString/tostringoverload1.cs
+++ b/snippets/csharp/System/Object/ToString/tostringoverload1.cs
@@ -3,71 +3,60 @@
public class Automobile
{
- private int _doors;
- private string _cylinders;
- private int _year;
- private string _model;
+ private int _doors;
+ private string _cylinders;
+ private int _year;
+ private string _model;
- public Automobile(string model, int year , int doors,
- string cylinders)
- {
- _model = model;
- _year = year;
- _doors = doors;
- _cylinders = cylinders;
- }
+ public Automobile(string model, int year, int doors,
+ string cylinders)
+ {
+ _model = model;
+ _year = year;
+ _doors = doors;
+ _cylinders = cylinders;
+ }
- public int Doors
- { get { return _doors; } }
+ public int Doors => _doors;
- public string Model
- { get { return _model; } }
+ public string Model => _model;
- public int Year
- { get { return _year; } }
+ public int Year => _year;
- public string Cylinders
- { get { return _cylinders; } }
+ public string Cylinders => _cylinders;
- public override string ToString()
- {
- return ToString("G");
- }
+ public override string ToString() => ToString("G");
- public string ToString(string fmt)
- {
- if (string.IsNullOrEmpty(fmt))
- fmt = "G";
+ public string ToString(string fmt)
+ {
+ if (string.IsNullOrEmpty(fmt))
+ fmt = "G";
- switch (fmt.ToUpperInvariant())
- {
- case "G":
- return string.Format("{0} {1}", _year, _model);
- case "D":
- return string.Format("{0} {1}, {2} dr.",
- _year, _model, _doors);
- case "C":
- return string.Format("{0} {1}, {2}",
- _year, _model, _cylinders);
- case "A":
- return string.Format("{0} {1}, {2} dr. {3}",
- _year, _model, _doors, _cylinders);
- default:
- string msg = string.Format("'{0}' is an invalid format string",
- fmt);
- throw new ArgumentException(msg);
- }
- }
+ switch (fmt.ToUpperInvariant())
+ {
+ case "G":
+ return $"{_year} {_model}";
+ case "D":
+ return $"{_year} {_model}, {_doors} dr.";
+ case "C":
+ return $"{_year} {_model}, {_cylinders}";
+ case "A":
+ return $"{_year} {_model}, {_doors} dr. {_cylinders}";
+ default:
+ string msg = $"'{fmt}' is an invalid format string";
+ throw new ArgumentException(msg);
+ }
+ }
}
public class Example7
{
- public static void Main()
- {
- var auto = new Automobile("Lynx", 2016, 4, "V8");
- Console.WriteLine(auto.ToString());
- Console.WriteLine(auto.ToString("A"));
- }
+ public static void Main()
+ {
+ var auto = new Automobile("Lynx", 2016, 4, "V8");
+ Console.WriteLine(auto.ToString());
+ Console.WriteLine(auto.ToString("A"));
+ }
}
// The example displays the following output:
// 2016 Lynx
diff --git a/snippets/csharp/System/Object/ToString/tostringoverload2.cs b/snippets/csharp/System/Object/ToString/tostringoverload2.cs
index cce98befd3e..75a86b2fbfe 100644
--- a/snippets/csharp/System/Object/ToString/tostringoverload2.cs
+++ b/snippets/csharp/System/Object/ToString/tostringoverload2.cs
@@ -1,19 +1,20 @@
-//
+//
using System;
using System.Globalization;
public class Example8
{
- public static void Main()
- {
- string[] cultureNames = { "en-US", "en-GB", "fr-FR",
+ public static void Main()
+ {
+ string[] cultureNames = { "en-US", "en-GB", "fr-FR",
"hr-HR", "ja-JP" };
- Decimal value = 1603.49m;
- foreach (var cultureName in cultureNames) {
- CultureInfo culture = new CultureInfo(cultureName);
- Console.WriteLine($"{culture.Name}: {value.ToString("C2", culture)}");
- }
- }
+ decimal value = 1603.49m;
+ foreach (string cultureName in cultureNames)
+ {
+ CultureInfo culture = new(cultureName);
+ Console.WriteLine($"{culture.Name}: {value.ToString("C2", culture)}");
+ }
+ }
}
// The example displays the following output:
// en-US: $1,603.49
diff --git a/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs b/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs
index 684182d5d88..f48c42eaeed 100644
--- a/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs
+++ b/snippets/csharp/System/ObjectDisposedException/Overview/dispose1.cs
@@ -4,21 +4,18 @@
public class Example
{
- public static void Main()
- {
- Timer t = new Timer(TimerNotification, null,
- 100, Timeout.Infinite);
- Thread.Sleep(2000);
- t.Dispose();
+ public static void Main()
+ {
+ Timer t = new(TimerNotification, null,
+ 100, Timeout.Infinite);
+ Thread.Sleep(2000);
+ t.Dispose();
- t.Change(200, 1000);
- Thread.Sleep(3000);
- }
+ t.Change(200, 1000);
+ Thread.Sleep(3000);
+ }
- private static void TimerNotification(Object obj)
- {
- Console.WriteLine("Timer event fired at {0:F}", DateTime.Now);
- }
+ private static void TimerNotification(object obj) => Console.WriteLine($"Timer event fired at {DateTime.Now:F}");
}
// The example displays output like the following:
// Timer event fired at Monday, July 14, 2014 11:54:08 AM
diff --git a/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs b/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs
index 162dc2167b1..fcd6b575cae 100644
--- a/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs
+++ b/snippets/csharp/System/ObjectDisposedException/Overview/objdispexc.cs
@@ -4,18 +4,18 @@
public class ObjectDisposedExceptionTest
{
- public static void Main()
- {
- MemoryStream ms = new MemoryStream(16);
- ms.Close();
- try
- {
- ms.ReadByte();
- }
- catch (ObjectDisposedException e)
- {
- Console.WriteLine("Caught: {0}", e.Message);
- }
- }
+ public static void Main()
+ {
+ MemoryStream ms = new(16);
+ ms.Close();
+ try
+ {
+ ms.ReadByte();
+ }
+ catch (ObjectDisposedException e)
+ {
+ Console.WriteLine($"Caught: {e.Message}");
+ }
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs b/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs
index 9c1c3d1348c..0cd8229c448 100644
--- a/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs
+++ b/snippets/csharp/System/ObsoleteAttribute/IsError/obsoleteattribute_message.cs
@@ -4,51 +4,45 @@
public class Example
{
- // Mark OldProperty As Obsolete.
- [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
- public string OldProperty
- { get { return "The old property value."; } }
+ // Mark OldProperty As Obsolete.
+ [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
+ public string OldProperty => "The old property value.";
- public string NewProperty
- { get { return "The new property value."; } }
+ public string NewProperty => "The new property value.";
- // Mark OldMethod As Obsolete.
- [ObsoleteAttribute("This method is obsolete. Call NewMethod instead.", true)]
- public string OldMethod()
- {
- return "You have called OldMethod.";
- }
+ // Mark OldMethod As Obsolete.
+ [ObsoleteAttribute("This method is obsolete. Call NewMethod instead.", true)]
+ public string OldMethod() => "You have called OldMethod.";
- public string NewMethod()
- {
- return "You have called NewMethod.";
- }
+ public string NewMethod() => "You have called NewMethod.";
- public static void Main()
- {
- // Get all public members of this type.
- MemberInfo[] members = typeof(Example).GetMembers();
- // Count total obsolete members.
- int n = 0;
+ public static void Main()
+ {
+ // Get all public members of this type.
+ MemberInfo[] members = typeof(Example).GetMembers();
+ // Count total obsolete members.
+ int n = 0;
- // Try to get the ObsoleteAttribute for each public member.
- Console.WriteLine("Obsolete members in the Example class:\n");
- foreach (var member in members) {
- ObsoleteAttribute[] attribs = (ObsoleteAttribute[])
- member.GetCustomAttributes(typeof(ObsoleteAttribute),
- false);
- if (attribs.Length > 0) {
- ObsoleteAttribute attrib = attribs[0];
- Console.WriteLine("Member Name: {0}.{1}", member.DeclaringType.FullName, member.Name);
- Console.WriteLine(" Message: {0}", attrib.Message);
- Console.WriteLine(" Warning/Error: {0}", attrib.IsError ? "Error" : "Warning");
- n++;
- }
- }
+ // Try to get the ObsoleteAttribute for each public member.
+ Console.WriteLine("Obsolete members in the Example class:\n");
+ foreach (var member in members)
+ {
+ ObsoleteAttribute[] attribs = (ObsoleteAttribute[])
+ member.GetCustomAttributes(typeof(ObsoleteAttribute),
+ false);
+ if (attribs.Length > 0)
+ {
+ ObsoleteAttribute attrib = attribs[0];
+ Console.WriteLine($"Member Name: {member.DeclaringType.FullName}.{member.Name}");
+ Console.WriteLine($" Message: {attrib.Message}");
+ Console.WriteLine($" Warning/Error: {(attrib.IsError ? "Error" : "Warning")}");
+ n++;
+ }
+ }
- if (n == 0)
- Console.WriteLine("The Example type has no obsolete attributes.");
- }
+ if (n == 0)
+ Console.WriteLine("The Example type has no obsolete attributes.");
+ }
}
// The example displays the following output:
// Obsolete members in the Example class:
diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj b/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/ObsoleteAttribute/Overview/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs b/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs
index b363324a60a..dea87202a8d 100644
--- a/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs
+++ b/snippets/csharp/System/ObsoleteAttribute/Overview/obsoleteattributeex1.cs
@@ -1,39 +1,34 @@
-//
-using System;
-using System.Reflection;
+using System;
public class Example
{
- // Mark OldProperty As Obsolete.
- [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
- public static string OldProperty
- { get { return "The old property value."; } }
-
- public static string NewProperty
- { get { return "The new property value."; } }
-
- // Mark CallOldMethod As Obsolete.
- [ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", true)]
- public static string CallOldMethod()
- {
- return "You have called CallOldMethod.";
- }
-
- public static string CallNewMethod()
- {
- return "You have called CallNewMethod.";
- }
-
- public static void Main()
- {
- Console.WriteLine(OldProperty);
- Console.WriteLine();
- Console.WriteLine(CallOldMethod());
- }
+ //
+
+ // Mark OldProperty As Obsolete.
+ [ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
+ public static string OldProperty => "The old property value.";
+
+ public static string NewProperty => "The new property value.";
+
+ // Mark CallOldMethod As Obsolete.
+ [ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", true)]
+ public static string CallOldMethod() => "You have called CallOldMethod.";
+
+ public static string CallNewMethod() => "You have called CallNewMethod.";
+
+ public static void Main()
+ {
+ Console.WriteLine(OldProperty);
+ Console.WriteLine();
+ // This call intentionally results in a compiler error.
+ Console.WriteLine(CallOldMethod());
+ }
+
+ // The attempt to compile this example produces output like the following output:
+ // Example.cs(31,25): error CS0619: 'Example.CallOldMethod()' is obsolete:
+ // 'This method is obsolete. Call CallNewMethod instead.'
+ // Example.cs(29,25): warning CS0618: 'Example.OldProperty' is obsolete:
+ // 'This property is obsolete. Use NewProperty instead.'
+
+ //
}
-// The attempt to compile this example produces output like the following output:
-// Example.cs(31,25): error CS0619: 'Example.CallOldMethod()' is obsolete:
-// 'This method is obsolete. Call CallNewMethod instead.'
-// Example.cs(29,25): warning CS0618: 'Example.OldProperty' is obsolete:
-// 'This property is obsolete. Use NewProperty instead.'
-//
diff --git a/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json b/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json
new file mode 100644
index 00000000000..11be0770fa1
--- /dev/null
+++ b/snippets/csharp/System/ObsoleteAttribute/Overview/snippets.5000.json
@@ -0,0 +1,10 @@
+{
+ "host": "dotnet",
+ "expectederrors": [
+ {
+ "file": "snippets\\csharp\\System\\ObsoleteAttribute\\Overview\\obsoleteattributeex1.cs",
+ "line": 24,
+ "error": "CS0619"
+ }
+ ]
+}
diff --git a/snippets/csharp/System/OperatingSystem/Clone/clone.cs b/snippets/csharp/System/OperatingSystem/Clone/clone.cs
index 705fcb4c7f6..7d31c8ad8a2 100644
--- a/snippets/csharp/System/OperatingSystem/Clone/clone.cs
+++ b/snippets/csharp/System/OperatingSystem/Clone/clone.cs
@@ -5,42 +5,34 @@
class CloneCompareDemo
{
// Copy, clone, and duplicate an OperatingSystem object.
- static void CopyOperatingSystemObjects( )
+ static void CopyOperatingSystemObjects()
{
// The Version object does not need to correspond to an
// actual OS version.
- Version verMMBVer = new Version( 5, 6, 7, 8 );
+ Version verMMBVer = new(5, 6, 7, 8);
- OperatingSystem opCreate1 = new
- OperatingSystem( PlatformID.Win32NT, verMMBVer );
+ OperatingSystem opCreate1 = new(PlatformID.Win32NT, verMMBVer);
// Create another OperatingSystem object with the same
// parameters as opCreate1.
- OperatingSystem opCreate2 = new
- OperatingSystem( PlatformID.Win32NT, verMMBVer );
+ OperatingSystem opCreate2 = new(PlatformID.Win32NT, verMMBVer);
// Clone opCreate1 and copy the opCreate1 reference.
OperatingSystem opClone =
- (OperatingSystem)opCreate1.Clone( );
+ (OperatingSystem)opCreate1.Clone();
OperatingSystem opCopy = opCreate1;
// Compare the various objects for equality.
- Console.WriteLine( "{0,-50}{1}",
- "Is the second object the same as the original?",
- opCreate1.Equals( opCreate2 ) );
- Console.WriteLine( "{0,-50}{1}",
- "Is the object clone the same as the original?",
- opCreate1.Equals( opClone ) );
- Console.WriteLine( "{0,-50}{1}",
- "Is the copied object the same as the original?",
- opCreate1.Equals( opCopy ) );
+ Console.WriteLine($"{"Is the second object the same as the original?",-50}{opCreate1.Equals(opCreate2)}");
+ Console.WriteLine($"{"Is the object clone the same as the original?",-50}{opCreate1.Equals(opClone)}");
+ Console.WriteLine($"{"Is the copied object the same as the original?",-50}{opCreate1.Equals(opCopy)}");
}
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of OperatingSystem.Clone( ) " +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Create an OperatingSystem object, and then " +
"create another object with the \n" +
@@ -49,9 +41,9 @@ static void Main( )
"each object with the original " +
"using the Equals( ) method. Equals( ) \n" +
"returns true only when both " +
- "references refer to the same object.\n" );
+ "references refer to the same object.\n");
- CopyOperatingSystemObjects( );
+ CopyOperatingSystemObjects();
}
}
diff --git a/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs b/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs
index dc03f9023a9..c25e34a4dd8 100644
--- a/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs
+++ b/snippets/csharp/System/OperatingSystem/Overview/osinfo1.cs
@@ -3,17 +3,17 @@
public class Example
{
- public static void Main()
- {
- var os = Environment.OSVersion;
- Console.WriteLine("Current OS Information:\n");
- Console.WriteLine("Platform: {0:G}", os.Platform);
- Console.WriteLine("Version String: {0}", os.VersionString);
- Console.WriteLine("Version Information:");
- Console.WriteLine(" Major: {0}", os.Version.Major);
- Console.WriteLine(" Minor: {0}", os.Version.Minor);
- Console.WriteLine("Service Pack: '{0}'", os.ServicePack);
- }
+ public static void Main()
+ {
+ var os = Environment.OSVersion;
+ Console.WriteLine("Current OS Information:\n");
+ Console.WriteLine($"Platform: {os.Platform:G}");
+ Console.WriteLine($"Version String: {os.VersionString}");
+ Console.WriteLine("Version Information:");
+ Console.WriteLine($" Major: {os.Version.Major}");
+ Console.WriteLine($" Minor: {os.Version.Minor}");
+ Console.WriteLine($"Service Pack: '{os.ServicePack}'");
+ }
}
// If run on a Windows 8.1 system, the example displays output like the following:
// Current OS Information:
@@ -33,4 +33,4 @@ public static void Main()
// Major: 6
// Minor: 1
// Service Pack: 'Service Pack 1'
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs b/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs
index 05b27d594c2..0d606fc6876 100644
--- a/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs
+++ b/snippets/csharp/System/OperatingSystem/Platform/plat_ver.cs
@@ -7,52 +7,51 @@ class PlatformVersionDemo
{
// Create an OperatingSystem object and display the Platform
// and Version properties.
- static void BuildOSObj( PlatformID pID, Version ver )
+ static void BuildOSObj(PlatformID pID, Version ver)
{
- OperatingSystem opSys = new OperatingSystem( pID, ver );
- PlatformID platform = opSys.Platform;
- Version version = opSys.Version;
+ OperatingSystem opSys = new(pID, ver);
+ PlatformID platform = opSys.Platform;
+ Version version = opSys.Version;
- Console.WriteLine( " Platform: {0,-15} Version: {1}",
- platform, version );
+ Console.WriteLine($" Platform: {platform,-15} Version: {version}");
}
- static void BuildOperatingSystemObjects( )
+ static void BuildOperatingSystemObjects()
{
// The Version object does not need to correspond to an
// actual OS version.
- Version verNull = new Version( );
- Version verString = new Version( "3.5.8.13" );
- Version verMajMin = new Version( 6, 10 );
- Version verMMBld = new Version( 5, 25, 5025 );
- Version verMMBVer = new Version( 5, 6, 7, 8 );
+ Version verNull = new();
+ Version verString = new("3.5.8.13");
+ Version verMajMin = new(6, 10);
+ Version verMMBld = new(5, 25, 5025);
+ Version verMMBVer = new(5, 6, 7, 8);
// All PlatformID members are shown here.
- BuildOSObj( PlatformID.Win32NT, verNull );
- BuildOSObj( PlatformID.Win32S, verString );
- BuildOSObj( PlatformID.Win32Windows, verMajMin );
- BuildOSObj( PlatformID.WinCE, verMMBld );
- BuildOSObj( PlatformID.Win32NT, verMMBVer );
+ BuildOSObj(PlatformID.Win32NT, verNull);
+ BuildOSObj(PlatformID.Win32S, verString);
+ BuildOSObj(PlatformID.Win32Windows, verMajMin);
+ BuildOSObj(PlatformID.WinCE, verMMBld);
+ BuildOSObj(PlatformID.Win32NT, verMMBVer);
}
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of OperatingSystem.Platform " +
"and OperatingSystem.Version \n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Create several OperatingSystem objects " +
- "and display their properties:\n" );
+ "and display their properties:\n");
- BuildOperatingSystemObjects( );
+ BuildOperatingSystemObjects();
Console.WriteLine(
- "\nThe operating system of the host computer is:\n" );
+ "\nThe operating system of the host computer is:\n");
BuildOSObj(
Environment.OSVersion.Platform,
- Environment.OSVersion.Version );
+ Environment.OSVersion.Version);
}
}
diff --git a/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs b/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs
index d3bbb823032..f8c8b572acc 100644
--- a/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs
+++ b/snippets/csharp/System/OperatingSystem/ServicePack/sp.cs
@@ -6,9 +6,9 @@ class Sample
{
public static void Main()
{
- OperatingSystem os = Environment.OSVersion;
- String sp = os.ServicePack;
- Console.WriteLine("Service pack version = \"{0}\"", sp);
+ OperatingSystem os = Environment.OSVersion;
+ string sp = os.ServicePack;
+ Console.WriteLine($"Service pack version = \"{sp}\"");
}
}
/*
@@ -17,4 +17,4 @@ public static void Main()
Service pack version = "Service Pack 1"
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs b/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs
index eb0d575a92e..19f36ac13dc 100644
--- a/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs
+++ b/snippets/csharp/System/OperatingSystem/ToString/ctor_tostr.cs
@@ -6,46 +6,44 @@
class OpSysConstructDemo
{
// Create and display an OperatingSystem object.
- static void BuildOSObj( PlatformID pID, Version ver )
+ static void BuildOSObj(PlatformID pID, Version ver)
{
- OperatingSystem os = new OperatingSystem( pID, ver );
+ OperatingSystem os = new(pID, ver);
- Console.WriteLine( " {0}", os.ToString( ) );
+ Console.WriteLine($" {os.ToString()}");
}
- static void BuildOperatingSystemObjects( )
+ static void BuildOperatingSystemObjects()
{
// The Version object does not need to correspond to an
// actual OS version.
- Version verNull = new Version( );
- Version verMajMin = new Version( 3, 11 );
- Version verMMBld = new Version( 5, 25, 625 );
- Version verMMBVer = new Version( 5, 6, 7, 8 );
- Version verString = new Version( "3.5.8.13" );
+ Version verNull = new();
+ Version verMajMin = new(3, 11);
+ Version verMMBld = new(5, 25, 625);
+ Version verMMBVer = new(5, 6, 7, 8);
+ Version verString = new("3.5.8.13");
// All PlatformID members are shown here.
- BuildOSObj( PlatformID.Win32NT, verNull );
- BuildOSObj( PlatformID.Win32S, verMajMin );
- BuildOSObj( PlatformID.Win32Windows, verMMBld );
- BuildOSObj( PlatformID.WinCE, verMMBVer );
- BuildOSObj( PlatformID.Win32NT, verString );
+ BuildOSObj(PlatformID.Win32NT, verNull);
+ BuildOSObj(PlatformID.Win32S, verMajMin);
+ BuildOSObj(PlatformID.Win32Windows, verMMBld);
+ BuildOSObj(PlatformID.WinCE, verMMBVer);
+ BuildOSObj(PlatformID.Win32NT, verString);
}
- public static void Main( )
+ public static void Main()
{
Console.WriteLine(
"This example of the OperatingSystem constructor " +
"and \nOperatingSystem.ToString( ) " +
- "generates the following output.\n" );
+ "generates the following output.\n");
Console.WriteLine(
"Create and display several different " +
- "OperatingSystem objects:\n" );
+ "OperatingSystem objects:\n");
- BuildOperatingSystemObjects( );
+ BuildOperatingSystemObjects();
- Console.WriteLine(
- "\nThe OS version of the host computer is:\n\n {0}",
- Environment.OSVersion.ToString( ) );
+ Console.WriteLine($"\nThe OS version of the host computer is:\n\n {Environment.OSVersion.ToString()}");
}
}
diff --git a/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs b/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs
index 330baa296cf..909f0330401 100644
--- a/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs
+++ b/snippets/csharp/System/OperatingSystem/VersionString/osvs.cs
@@ -6,10 +6,10 @@ class Sample
{
public static void Main()
{
- OperatingSystem os = Environment.OSVersion;
-// Display the value of OperatingSystem.VersionString. By default, this is
-// the same value as OperatingSystem.ToString.
- Console.WriteLine("This operating system is {0}", os.VersionString);
+ OperatingSystem os = Environment.OSVersion;
+ // Display the value of OperatingSystem.VersionString. By default, this is
+ // the same value as OperatingSystem.ToString.
+ Console.WriteLine($"This operating system is {os.VersionString}");
}
}
/*
@@ -17,4 +17,4 @@ public static void Main()
This operating system is Microsoft Windows NT 5.1.2600.0 Service Pack 1
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs b/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs
new file mode 100644
index 00000000000..e40728734f5
--- /dev/null
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/Program.cs
@@ -0,0 +1,4 @@
+OutOfMemoryExceptionExample1.Run();
+OutOfMemoryExceptionExample2.Run();
+OutOfMemoryExceptionExample3.Run();
+OutOfMemoryExceptionExample4.Run();
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj b/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs
index c1426bc6baf..1aa2d6eb7d5 100644
--- a/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/data1.cs
@@ -2,37 +2,36 @@
using System;
using System.Collections.Generic;
-public class Example
+public class OutOfMemoryExceptionExample1
{
- public static void Main()
- {
- Double[] values = GetData();
- // Compute mean.
- Console.WriteLine("Sample mean: {0}, N = {1}",
- GetMean(values), values.Length);
- }
+ public static void Run()
+ {
+ double[] values = GetData();
+ // Compute mean.
+ Console.WriteLine($"Sample mean: {GetMean(values)}, N = {values.Length}");
+ }
- private static Double[] GetData()
- {
- Random rnd = new Random();
- List values = new List();
- for (int ctr = 1; ctr <= 200000000; ctr++) {
- values.Add(rnd.NextDouble());
- if (ctr % 10000000 == 0)
- Console.WriteLine("Retrieved {0:N0} items of data.",
- ctr);
- }
- return values.ToArray();
- }
+ private static double[] GetData()
+ {
+ Random rnd = new();
+ List values = new();
+ for (int ctr = 1; ctr <= 200000000; ctr++)
+ {
+ values.Add(rnd.NextDouble());
+ if (ctr % 10000000 == 0)
+ Console.WriteLine($"Retrieved {ctr:N0} items of data.");
+ }
+ return values.ToArray();
+ }
- private static Double GetMean(Double[] values)
- {
- Double sum = 0;
- foreach (var value in values)
- sum += value;
+ private static double GetMean(double[] values)
+ {
+ double sum = 0;
+ foreach (double value in values)
+ sum += value;
- return sum / values.Length;
- }
+ return sum / values.Length;
+ }
}
// The example displays output like the following:
// Retrieved 10,000,000 items of data.
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs b/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs
index 1bc52b4c686..af03dede687 100644
--- a/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/data2.cs
@@ -1,43 +1,44 @@
//
using System;
-using System.IO;
-public class Example
+
+public class OutOfMemoryExceptionExample2
{
- public static void Main()
- {
- Tuple result = GetResult();
- Console.WriteLine("Sample mean: {0}, N = {1:N0}",
- result.Item1, result.Item2);
- }
+ public static void Run()
+ {
+ Tuple result = GetResult();
+ Console.WriteLine($"Sample mean: {result.Item1}, N = {result.Item2:N0}");
+ }
- private static Tuple GetResult()
- {
- int chunkSize = 50000000;
- int nToGet = 200000000;
- Random rnd = new Random();
- // FileStream fs = new FileStream(@".\data.bin", FileMode.Create);
- // BinaryWriter bin = new BinaryWriter(fs);
- // bin.Write((int)0);
- int n = 0;
- Double sum = 0;
- for (int outer = 0;
- outer <= ((int) Math.Ceiling(nToGet * 1.0 / chunkSize) - 1);
- outer++) {
- for (int inner = 0;
- inner <= Math.Min(nToGet - n - 1, chunkSize - 1);
- inner++) {
- Double value = rnd.NextDouble();
- sum += value;
- n++;
- // bin.Write(value);
- }
- }
- // bin.Seek(0, SeekOrigin.Begin);
- // bin.Write(n);
- // bin.Close();
- return new Tuple(sum/n, n);
- }
+ private static Tuple GetResult()
+ {
+ int chunkSize = 50000000;
+ int nToGet = 200000000;
+ Random rnd = new();
+ // FileStream fs = new FileStream(@".\data.bin", FileMode.Create);
+ // BinaryWriter bin = new BinaryWriter(fs);
+ // bin.Write((int)0);
+ int n = 0;
+ double sum = 0;
+ for (int outer = 0;
+ outer <= ((int)Math.Ceiling(nToGet * 1.0 / chunkSize) - 1);
+ outer++)
+ {
+ for (int inner = 0;
+ inner <= Math.Min(nToGet - n - 1, chunkSize - 1);
+ inner++)
+ {
+ double value = rnd.NextDouble();
+ sum += value;
+ n++;
+ // bin.Write(value);
+ }
+ }
+ // bin.Seek(0, SeekOrigin.Begin);
+ // bin.Write(n);
+ // bin.Close();
+ return new Tuple(sum / n, n);
+ }
}
// The example displays output like the following:
// Sample mean: 0.500022771458399, N = 200,000,000
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs
index 4f491b0a9c4..b294c975cca 100644
--- a/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/failfast1.cs
@@ -1,31 +1,34 @@
//
using System;
-public class Example
+public class OutOfMemoryExceptionExample3
{
- public static void Main()
- {
- try {
- // Outer block to handle any unexpected exceptions.
- try {
- string s = "This";
- s = s.Insert(2, "is ");
+ public static void Run()
+ {
+ try
+ {
+ // Outer block to handle any unexpected exceptions.
+ try
+ {
+ string s = "This";
+ s = s.Insert(2, "is ");
- // Throw an OutOfMemoryException exception.
- throw new OutOfMemoryException();
- }
- catch (ArgumentException) {
- Console.WriteLine("ArgumentException in String.Insert");
- }
+ // Throw an OutOfMemoryException exception.
+ throw new OutOfMemoryException();
+ }
+ catch (ArgumentException)
+ {
+ Console.WriteLine("ArgumentException in String.Insert");
+ }
- // Execute program logic.
- }
- catch (OutOfMemoryException e) {
- Console.WriteLine("Terminating application unexpectedly...");
- Environment.FailFast(String.Format("Out of Memory: {0}",
- e.Message));
- }
- }
+ // Execute program logic.
+ }
+ catch (OutOfMemoryException e)
+ {
+ Console.WriteLine("Terminating application unexpectedly...");
+ Environment.FailFast($"Out of Memory: {e.Message}");
+ }
+ }
}
// The example displays the following output:
// Terminating application unexpectedly...
diff --git a/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs b/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs
index a879f70bc01..03bff3781f7 100644
--- a/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs
+++ b/snippets/csharp/System/OutOfMemoryException/Overview/sb_example1.cs
@@ -2,19 +2,21 @@
using System;
using System.Text;
-public class Example
+public class OutOfMemoryExceptionExample4
{
- public static void Main()
- {
- StringBuilder sb = new StringBuilder(15, 15);
- sb.Append("Substring #1 ");
- try {
- sb.Insert(0, "Substring #2 ", 1);
- }
- catch (OutOfMemoryException e) {
- Console.WriteLine("Out of Memory: {0}", e.Message);
- }
- }
+ public static void Run()
+ {
+ StringBuilder sb = new(15, 15);
+ sb.Append("Substring #1 ");
+ try
+ {
+ sb.Insert(0, "Substring #2 ", 1);
+ }
+ catch (OutOfMemoryException e)
+ {
+ Console.WriteLine($"Out of Memory: {e.Message}");
+ }
+ }
}
// The example displays the following output:
// Out of Memory: Insufficient memory to continue the execution of the program.
diff --git a/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs b/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs
index 40759953456..09ae86bef64 100644
--- a/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs
+++ b/snippets/csharp/System/OverflowException/Overview/arithmetic1.cs
@@ -2,63 +2,68 @@
public class Example
{
- public static void Main()
- {
- //
- int value = 780000000;
- checked {
- try {
- // Square the original value.
- int square = value * value;
- Console.WriteLine("{0} ^ 2 = {1}", value, square);
- }
- catch (OverflowException) {
- double square = Math.Pow(value, 2);
- Console.WriteLine("Exception: {0} > {1:E}.",
- square, Int32.MaxValue);
- } }
- // The example displays the following output:
- // Exception: 6.084E+17 > 2.147484E+009.
- //
+ public static void Main()
+ {
+ //
+ int value = 780000000;
+ checked
+ {
+ try
+ {
+ // Square the original value.
+ int square = value * value;
+ Console.WriteLine($"{value} ^ 2 = {square}");
+ }
+ catch (OverflowException)
+ {
+ double square = Math.Pow(value, 2);
+ Console.WriteLine($"Exception: {square} > {int.MaxValue:E}.");
+ }
+ }
+ // The example displays the following output:
+ // Exception: 6.084E+17 > 2.147484E+009.
+ //
- Cast();
- Unchecked();
- }
+ Cast();
+ Unchecked();
+ }
- private static void Cast()
- {
- //
- byte value = 241;
- checked {
- try {
- sbyte newValue = (sbyte) value;
- Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
- value.GetType().Name, value,
- newValue.GetType().Name, newValue);
- }
- catch (OverflowException) {
- Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
- } }
- // The example displays the following output:
- // Exception: 241 > 127.
- //
- }
+ private static void Cast()
+ {
+ //
+ byte value = 241;
+ checked
+ {
+ try
+ {
+ sbyte newValue = (sbyte)value;
+ Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {newValue.GetType().Name} value {newValue}.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Exception: {value} > {sbyte.MaxValue}.");
+ }
+ }
+ // The example displays the following output:
+ // Exception: 241 > 127.
+ //
+ }
- private static void Unchecked()
- {
- //
- byte value = 241;
- try {
- sbyte newValue = (sbyte) value;
- Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
- value.GetType().Name, value,
- newValue.GetType().Name, newValue);
- }
- catch (OverflowException) {
- Console.WriteLine("Exception: {0} > {1}.", value, SByte.MaxValue);
- }
- // The example displays the following output:
- // Converted the Byte value 241 to the SByte value -15.
- //
- }
+ private static void Unchecked()
+ {
+ //
+ byte value = 241;
+ try
+ {
+ sbyte newValue = (sbyte)value;
+ Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {newValue.GetType().Name} value {newValue}.");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"Exception: {value} > {sbyte.MaxValue}.");
+ }
+ // The example displays the following output:
+ // Converted the Byte value 241 to the SByte value -15.
+ //
+ }
}
diff --git a/xml/System/ObsoleteAttribute.xml b/xml/System/ObsoleteAttribute.xml
index 2d2d6ef8d0f..3fa1933077f 100644
--- a/xml/System/ObsoleteAttribute.xml
+++ b/xml/System/ObsoleteAttribute.xml
@@ -1,3 +1,4 @@
+
@@ -55,14 +56,8 @@
-
- Marks program elements that are no longer in use.
-
-
- Source code imported from
-
- ObsoleteAttribute.cs without any changes, all resulting warnings ignored accordingly.
-
+ Marks program elements that are no longer in use.
+ To be added.
attribute. Accessing the value of the `OldProperty` property in code generates a compiler warning, but calling the `CallOldMethod` method generates a compiler error. The example also shows the output that results when you attempt to compile the source code.
From e6022b7639b38efa9782523fe6ff8d271094c428 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Fri, 14 Aug 2026 09:55:30 -0700
Subject: [PATCH 4/9] Modernize C# code snippets - System/Type (#12973)
---
.../Type/AssemblyQualifiedName/fullname1.cs | 6 +-
.../System/Type/Attributes/attributes1.cs | 162 +++++++++---------
.../csharp/System/Type/BaseType/basetype3.cs | 42 ++---
.../csharp/System/Type/BaseType/remarks.cs | 6 +-
.../System/Type/BaseType/testbasetype.cs | 4 +-
.../Type/ContainsGenericParameters/source.cs | 29 ++--
.../System/Type/DeclaringMethod/source.cs | 26 +--
.../System/Type/DeclaringType/remarks.cs | 8 +-
.../System/Type/DeclaringType/source.cs | 8 +-
.../Type/DefaultBinder/type_defaultbinder.cs | 15 +-
.../System/Type/EmptyTypes/Project.csproj | 6 +
.../csharp/System/Type/EmptyTypes/source.cs | 12 +-
.../csharp/System/Type/Equals/EqualsEx1.cs | 71 ++++----
snippets/csharp/System/Type/Equals/Program.cs | 2 +
.../csharp/System/Type/Equals/Project.csproj | 6 +
snippets/csharp/System/Type/Equals/source.cs | 22 +--
.../FilterAttribute/type_filterattribute.cs | 18 +-
.../System/Type/FilterName/Project.csproj | 6 +
.../csharp/System/Type/FilterName/source.cs | 30 ++--
.../type_filternameignorecase.cs | 16 +-
.../FindInterfaces/type_findinterfaces.cs | 36 ++--
.../Type/FindMembers/type_findmembers.cs | 18 +-
.../csharp/System/Type/FullName/Fullname3.cs | 34 ++--
.../csharp/System/Type/FullName/Fullname4.cs | 59 +++----
.../csharp/System/Type/FullName/Fullname5.cs | 50 +++---
.../csharp/System/Type/FullName/Program.cs | 5 +
.../System/Type/FullName/Project.csproj | 6 +
.../System/Type/FullName/fullnameex1.cs | 20 +--
.../System/Type/FullName/testfullname.cs | 8 +-
snippets/csharp/System/Type/GUID/type_guid.cs | 8 +-
.../Type/GenericParameterAttributes/source.cs | 38 ++--
.../Type/GenericParameterPosition/remarks.cs | 11 +-
.../Type/GetArrayRank/type_getarrayrank.cs | 8 +-
.../System/Type/GetConstructors/Program.cs | 2 +
.../Type/GetConstructors/Project.csproj | 6 +
.../System/Type/GetConstructors/source1.cs | 32 ++--
.../System/Type/GetConstructors/source2.cs | 36 ++--
.../System/Type/GetDefaultMembers/source2.cs | 24 +--
.../type_getdefaultmembers.cs | 24 +--
.../Type/GetElementType/testgetelementtype.cs | 10 +-
.../csharp/System/Type/GetEvent/Program.cs | 2 +
.../System/Type/GetEvent/Project.csproj | 7 +
.../System/Type/GetEvent/type_getevent.cs | 20 +--
.../System/Type/GetEvent/type_getevent1.cs | 20 +--
.../csharp/System/Type/GetEvents/Program.cs | 2 +
.../System/Type/GetEvents/Project.csproj | 7 +
.../System/Type/GetEvents/type_getevents1.cs | 14 +-
.../System/Type/GetEvents/type_getevents2.cs | 14 +-
.../System/Type/GetField/type_getfield.cs | 19 +-
.../Type/GetFields/fieldinfo_isspecialname.cs | 13 +-
.../csharp/System/Type/GetFields/source.cs | 11 +-
.../System/Type/GetGenericArguments/source.cs | 23 +--
.../Type/GetGenericTypeDefinition/source.cs | 18 +-
.../System/Type/GetHashCode/Project.csproj | 7 +
.../GetHashCode/type_gethashcode_getfields.cs | 31 ++--
.../System/Type/GetInterface/Project.csproj | 6 +
.../Type/GetInterface/type_getinterface.cs | 40 ++---
.../Type/GetInterfaceMap/Project.csproj | 6 +
.../Type/GetInterfaceMap/interfacemapping1.cs | 60 +++----
.../System/Type/GetMember/type_getmember.cs | 48 +++---
.../csharp/System/Type/GetMembers/Program.cs | 2 +
.../System/Type/GetMembers/Project.csproj | 6 +
.../Type/GetMembers/type_getmembers1.cs | 72 ++++----
.../Type/GetMembers/type_getmembers2.cs | 82 ++++-----
.../System/Type/GetMethod/GetMethod1.cs | 88 +++++-----
.../Type/GetMethod/GetMethodWithOverloads1.cs | 32 ++--
.../Type/GetMethod/GetMethodWithOverloads2.cs | 21 +--
.../System/Type/GetMethod/type_getmethod1.cs | 2 +-
.../System/Type/GetMethod/type_getmethod2.cs | 2 +-
.../System/Type/GetMethod/type_getmethod3.cs | 92 +++++-----
.../System/Type/GetMethod/type_getmethod4.cs | 64 +++----
.../System/Type/GetMethod/type_getmethod5.cs | 82 ++++-----
.../Type/GetMethods/type_getmethods2.cs | 28 ++-
.../type_getnestedclassesabs.cs | 12 +-
.../GetNestedTypes/type_getnestedtypes.cs | 20 +--
.../Type/GetProperties/type_getproperties2.cs | 87 ++++------
.../Type/GetProperties/type_gettypecode.cs | 30 ++--
.../Type/GetProperty/type_getproperty1.cs | 2 +-
.../Type/GetProperty/type_getproperty2.cs | 2 +-
.../Type/GetProperty/type_getproperty21.cs | 26 ++-
.../Type/GetProperty/type_getproperty3.cs | 17 +-
.../GetProperty/type_getproperty_types.cs | 12 +-
.../csharp/System/Type/GetType/Project.csproj | 4 +-
.../Type/GetType/mypath/v5.0/myassembly.cs | 4 +-
snippets/csharp/System/Type/GetType/source.cs | 2 +-
.../System/Type/GetType/type_gettype.cs | 43 ++---
.../System/Type/GetTypeCode/iconvertible.cs | 107 +++---------
.../System/Type/GetTypeFromCLSID/Program.cs | 5 +
.../Type/GetTypeFromCLSID/Project.csproj | 6 +
.../GetTypeFromCLSID/gettypefromclsid1.cs | 35 ++--
.../GetTypeFromCLSID/gettypefromclsid11.cs | 108 ++++++------
.../GetTypeFromCLSID/gettypefromclsid_ex2.cs | 48 +++---
.../GetTypeFromCLSID/gettypefromclsid_ex3.cs | 46 ++---
.../GetTypeFromCLSID/gettypefromclsid_ex4.cs | 56 +++---
.../type_gettypefromhandle.cs | 18 +-
.../System/Type/GetTypeFromProgID/Program.cs | 3 +
.../Type/GetTypeFromProgID/Project.csproj | 6 +
.../type_gettypefromprogid2.cs | 20 +--
.../type_gettypefromprogid3.cs | 22 +--
.../type_gettypefromprogid4.cs | 22 +--
.../System/Type/HasElementType/Project.csproj | 7 +
.../HasElementType/type_haselementtype.cs | 25 ++-
.../type_haselementtypeimpl.cs | 31 ++--
.../System/Type/InvokeMember/invokemem.cs | 34 ++--
.../System/Type/IsAbstract/isabstract1.cs | 36 ++--
.../Type/IsAnsiClass/type_isansiclass.cs | 16 +-
.../csharp/System/Type/IsArray/isarray2.cs | 19 +-
.../Type/IsArrayImpl/type_isarrayimpl.cs | 25 ++-
.../IsAssignableFrom/IsAssignableFrom2.cs | 20 +--
.../IsAssignableFrom/IsAssignableFrom3.cs | 26 +--
.../System/Type/IsAssignableFrom/Program.cs | 4 +
.../Type/IsAssignableFrom/Project.csproj | 6 +
.../IsAssignableFrom/isassignablefrom_ex1.cs | 31 ++--
.../IsAssignableFrom/testisassignablefrom.cs | 114 ++++++------
.../Type/IsAutoLayout/type_isautolayout.cs | 7 +-
.../System/Type/IsClass/type_isclass.cs | 12 +-
.../System/Type/IsContextful/Project.csproj | 6 +
.../Type/IsContextful/type_iscontextful.cs | 28 ++-
.../IsContextfulImpl/type_iscontextfulimpl.cs | 25 ++-
.../csharp/System/Type/IsEnum/testisenum.cs | 14 +-
.../IsExplicitLayout/type_isexplicitlayout.cs | 29 ++--
.../System/Type/IsGenericParameter/source.cs | 23 +--
.../System/Type/IsGenericType/Program.cs | 2 +
.../System/Type/IsGenericType/Project.csproj | 6 +
.../System/Type/IsGenericType/remarks.cs | 20 +--
.../System/Type/IsGenericType/source.cs | 32 ++--
.../IsInstanceOfType/testisinstanceoftype.cs | 23 +--
.../Type/IsInterface/type_isinterface.cs | 12 +-
.../type_islayoutsequential.cs | 18 +-
.../type_ismarshalbyrefimpl.cs | 25 ++-
.../IsNested/isnestedfamilyandassembly1.cs | 47 ++---
.../csharp/System/Type/IsNotPublic/source.cs | 8 +-
.../IsPrimitiveImpl/type_isprimitiveimpl.cs | 27 ++-
.../System/Type/IsPublic/type_ispublic.cs | 18 +-
.../System/Type/IsSealed/type_issealed.cs | 32 ++--
.../IsSubclassOf/issubclassof_interface1.cs | 21 +--
.../Type/IsSubclassOf/testissubclassof.cs | 8 +-
.../Type/IsValueType/type_isvaluetype.cs | 4 +-
.../csharp/System/Type/IsVisible/source.cs | 18 +-
.../System/Type/MakeByRefType/source.cs | 14 +-
.../System/Type/MakeGenericType/remarks.cs | 10 +-
.../System/Type/MakeGenericType/source.cs | 29 ++--
.../csharp/System/Type/Missing/Project.csproj | 9 +
snippets/csharp/System/Type/Missing/source.cs | 17 +-
.../System/Type/Module/type_tostring.cs | 20 +--
.../csharp/System/Type/Overview/Equals1.cs | 8 +-
.../csharp/System/Type/Overview/GetType1.cs | 6 +-
.../csharp/System/Type/Overview/source.cs | 10 +-
.../System/Type/ReflectedType/source.cs | 5 +-
.../Type/StructLayoutAttribute/source.cs | 8 +-
.../System/Type/TypeHandle/type_typehandle.cs | 14 +-
.../Overview/Missing1.cs | 20 +--
.../Overview/Missing1a.cs | 23 +--
.../Overview/Regex1.cs | 6 +-
.../Overview/ctorException1.cs | 32 ++--
.../.ctor/typeloadexception_constructor2.cs | 32 ++--
.../.ctor/typeloadexception_constructor3.cs | 64 +++----
.../Message/typeloadexception_typename.cs | 41 +++--
.../System/TypedReference/Overview/source.cs | 28 +--
159 files changed, 1886 insertions(+), 2003 deletions(-)
create mode 100644 snippets/csharp/System/Type/EmptyTypes/Project.csproj
create mode 100644 snippets/csharp/System/Type/Equals/Program.cs
create mode 100644 snippets/csharp/System/Type/Equals/Project.csproj
create mode 100644 snippets/csharp/System/Type/FilterName/Project.csproj
create mode 100644 snippets/csharp/System/Type/FullName/Program.cs
create mode 100644 snippets/csharp/System/Type/FullName/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetConstructors/Program.cs
create mode 100644 snippets/csharp/System/Type/GetConstructors/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetEvent/Program.cs
create mode 100644 snippets/csharp/System/Type/GetEvent/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetEvents/Program.cs
create mode 100644 snippets/csharp/System/Type/GetEvents/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetHashCode/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetInterface/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetInterfaceMap/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetMembers/Program.cs
create mode 100644 snippets/csharp/System/Type/GetMembers/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs
create mode 100644 snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj
create mode 100644 snippets/csharp/System/Type/GetTypeFromProgID/Program.cs
create mode 100644 snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj
create mode 100644 snippets/csharp/System/Type/HasElementType/Project.csproj
create mode 100644 snippets/csharp/System/Type/IsAssignableFrom/Program.cs
create mode 100644 snippets/csharp/System/Type/IsAssignableFrom/Project.csproj
create mode 100644 snippets/csharp/System/Type/IsContextful/Project.csproj
create mode 100644 snippets/csharp/System/Type/IsGenericType/Program.cs
create mode 100644 snippets/csharp/System/Type/IsGenericType/Project.csproj
create mode 100644 snippets/csharp/System/Type/Missing/Project.csproj
diff --git a/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs b/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs
index 4ff74780f6b..ce3d21c98c2 100644
--- a/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs
+++ b/snippets/csharp/System/Type/AssemblyQualifiedName/fullname1.cs
@@ -7,17 +7,17 @@ public class Example
{
public static void Main()
{
- Type t = typeof(String);
+ Type t = typeof(string);
ShowTypeInfo(t);
t = typeof(List<>);
ShowTypeInfo(t);
- var list = new List();
+ var list = new List();
t = list.GetType();
ShowTypeInfo(t);
- Object v = 12;
+ object v = 12;
t = v.GetType();
ShowTypeInfo(t);
diff --git a/snippets/csharp/System/Type/Attributes/attributes1.cs b/snippets/csharp/System/Type/Attributes/attributes1.cs
index c76637c5c15..290499fb41e 100644
--- a/snippets/csharp/System/Type/Attributes/attributes1.cs
+++ b/snippets/csharp/System/Type/Attributes/attributes1.cs
@@ -9,99 +9,99 @@ internal struct S
public abstract class Example
{
- protected sealed class NestedClass {}
+ protected sealed class NestedClass { }
- public interface INested {}
+ public interface INested { }
public static void Main()
{
// Create an array of types.
- Type[] types = { typeof(Example), typeof(NestedClass),
- typeof(INested), typeof(S) };
+ Type[] types = [typeof(Example), typeof(NestedClass),
+ typeof(INested), typeof(S)];
- foreach (var t in types)
+ foreach (var t in types)
{
- Console.WriteLine("Attributes for type {0}:", t.Name);
+ Console.WriteLine($"Attributes for type {t.Name}:");
- TypeAttributes attr = t.Attributes;
+ TypeAttributes attr = t.Attributes;
- // To test for visibility attributes, you must use the visibility mask.
- TypeAttributes visibility = attr & TypeAttributes.VisibilityMask;
- switch (visibility)
- {
- case TypeAttributes.NotPublic:
- Console.WriteLine(" ...is not public");
- break;
- case TypeAttributes.Public:
- Console.WriteLine(" ...is public");
- break;
- case TypeAttributes.NestedPublic:
- Console.WriteLine(" ...is nested and public");
- break;
- case TypeAttributes.NestedPrivate:
- Console.WriteLine(" ...is nested and private");
- break;
- case TypeAttributes.NestedFamANDAssem:
- Console.WriteLine(" ...is nested, and inheritable only within the assembly" +
- "\n (cannot be declared in C#)");
- break;
- case TypeAttributes.NestedAssembly:
- Console.WriteLine(" ...is nested and internal");
- break;
- case TypeAttributes.NestedFamily:
- Console.WriteLine(" ...is nested and protected");
- break;
- case TypeAttributes.NestedFamORAssem:
- Console.WriteLine(" ...is nested and protected internal");
- break;
- }
+ // To test for visibility attributes, you must use the visibility mask.
+ TypeAttributes visibility = attr & TypeAttributes.VisibilityMask;
+ switch (visibility)
+ {
+ case TypeAttributes.NotPublic:
+ Console.WriteLine(" ...is not public");
+ break;
+ case TypeAttributes.Public:
+ Console.WriteLine(" ...is public");
+ break;
+ case TypeAttributes.NestedPublic:
+ Console.WriteLine(" ...is nested and public");
+ break;
+ case TypeAttributes.NestedPrivate:
+ Console.WriteLine(" ...is nested and private");
+ break;
+ case TypeAttributes.NestedFamANDAssem:
+ Console.WriteLine(" ...is nested, and inheritable only within the assembly" +
+ "\n (cannot be declared in C#)");
+ break;
+ case TypeAttributes.NestedAssembly:
+ Console.WriteLine(" ...is nested and internal");
+ break;
+ case TypeAttributes.NestedFamily:
+ Console.WriteLine(" ...is nested and protected");
+ break;
+ case TypeAttributes.NestedFamORAssem:
+ Console.WriteLine(" ...is nested and protected internal");
+ break;
+ }
- // Use the layout mask to test for layout attributes.
- TypeAttributes layout = attr & TypeAttributes.LayoutMask;
- switch (layout)
- {
- case TypeAttributes.AutoLayout:
- Console.WriteLine(" ...is AutoLayout");
- break;
- case TypeAttributes.SequentialLayout:
- Console.WriteLine(" ...is SequentialLayout");
- break;
- case TypeAttributes.ExplicitLayout:
- Console.WriteLine(" ...is ExplicitLayout");
- break;
- }
+ // Use the layout mask to test for layout attributes.
+ TypeAttributes layout = attr & TypeAttributes.LayoutMask;
+ switch (layout)
+ {
+ case TypeAttributes.AutoLayout:
+ Console.WriteLine(" ...is AutoLayout");
+ break;
+ case TypeAttributes.SequentialLayout:
+ Console.WriteLine(" ...is SequentialLayout");
+ break;
+ case TypeAttributes.ExplicitLayout:
+ Console.WriteLine(" ...is ExplicitLayout");
+ break;
+ }
- // Use the class semantics mask to test for class semantics attributes.
- TypeAttributes classSemantics = attr & TypeAttributes.ClassSemanticsMask;
- switch (classSemantics)
- {
- case TypeAttributes.Class:
- if (t.IsValueType)
- {
- Console.WriteLine(" ...is a value type");
- }
- else
- {
- Console.WriteLine(" ...is a class");
- }
- break;
- case TypeAttributes.Interface:
- Console.WriteLine(" ...is an interface");
- break;
- }
+ // Use the class semantics mask to test for class semantics attributes.
+ TypeAttributes classSemantics = attr & TypeAttributes.ClassSemanticsMask;
+ switch (classSemantics)
+ {
+ case TypeAttributes.Class:
+ if (t.IsValueType)
+ {
+ Console.WriteLine(" ...is a value type");
+ }
+ else
+ {
+ Console.WriteLine(" ...is a class");
+ }
+ break;
+ case TypeAttributes.Interface:
+ Console.WriteLine(" ...is an interface");
+ break;
+ }
- if ((attr & TypeAttributes.Abstract) != 0)
- {
- Console.WriteLine(" ...is abstract");
- }
+ if ((attr & TypeAttributes.Abstract) != 0)
+ {
+ Console.WriteLine(" ...is abstract");
+ }
- if ((attr & TypeAttributes.Sealed) != 0)
- {
- Console.WriteLine(" ...is sealed");
- }
-
- Console.WriteLine();
- }
+ if ((attr & TypeAttributes.Sealed) != 0)
+ {
+ Console.WriteLine(" ...is sealed");
+ }
+
+ Console.WriteLine();
+ }
}
}
// The example displays the following output:
@@ -128,4 +128,4 @@ public static void Main()
// ...is SequentialLayout
// ...is a value type
// ...is sealed
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/BaseType/basetype3.cs b/snippets/csharp/System/Type/BaseType/basetype3.cs
index 500bf5b7dd4..6d0aed03f61 100644
--- a/snippets/csharp/System/Type/BaseType/basetype3.cs
+++ b/snippets/csharp/System/Type/BaseType/basetype3.cs
@@ -3,39 +3,41 @@
public class Example
{
- public static void Main()
- {
- foreach (var t in typeof(Example).Assembly.GetTypes()) {
- Console.WriteLine("{0} derived from: ", t.FullName);
- var derived = t;
- do {
- derived = derived.BaseType;
- if (derived != null)
- Console.WriteLine(" {0}", derived.FullName);
- } while (derived != null);
- Console.WriteLine();
- }
- }
+ public static void Main()
+ {
+ foreach (var t in typeof(Example).Assembly.GetTypes())
+ {
+ Console.WriteLine($"{t.FullName} derived from: ");
+ var derived = t;
+ do
+ {
+ derived = derived.BaseType;
+ if (derived != null)
+ Console.WriteLine($" {derived.FullName}");
+ } while (derived != null);
+ Console.WriteLine();
+ }
+ }
}
-public class A {}
+public class A { }
public class B : A
-{}
+{ }
-public class C : B
-{}
+public class C : B
+{ }
// The example displays the following output:
// Example derived from:
// System.Object
-//
+//
// A derived from:
// System.Object
-//
+//
// B derived from:
// A
// System.Object
-//
+//
// C derived from:
// B
// A
diff --git a/snippets/csharp/System/Type/BaseType/remarks.cs b/snippets/csharp/System/Type/BaseType/remarks.cs
index fbc5b1bee05..252849ac5a5 100644
--- a/snippets/csharp/System/Type/BaseType/remarks.cs
+++ b/snippets/csharp/System/Type/BaseType/remarks.cs
@@ -1,4 +1,4 @@
-using System;
+
//
class B { }
@@ -7,5 +7,5 @@ class C : B { }
class ProgStubClass
{
- public static void Main() {}
-}
\ No newline at end of file
+ public static void Main() { }
+}
diff --git a/snippets/csharp/System/Type/BaseType/testbasetype.cs b/snippets/csharp/System/Type/BaseType/testbasetype.cs
index 08e8fc01e5e..f324d83297c 100644
--- a/snippets/csharp/System/Type/BaseType/testbasetype.cs
+++ b/snippets/csharp/System/Type/BaseType/testbasetype.cs
@@ -5,7 +5,7 @@ class TestType
public static void Main()
{
Type t = typeof(int);
- Console.WriteLine("{0} inherits from {1}.", t,t.BaseType);
+ Console.WriteLine($"{t} inherits from {t.BaseType}.");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/ContainsGenericParameters/source.cs b/snippets/csharp/System/Type/ContainsGenericParameters/source.cs
index 065bda276aa..c4d1e611e5c 100644
--- a/snippets/csharp/System/Type/ContainsGenericParameters/source.cs
+++ b/snippets/csharp/System/Type/ContainsGenericParameters/source.cs
@@ -1,7 +1,7 @@
//
using System;
-using System.Reflection;
-using System.Collections.Generic;
+
+
// Define a base class with two type parameters.
public class Base { }
@@ -25,10 +25,10 @@ public static void Main()
"\r\n--- Display a generic type and the open constructed");
Console.WriteLine(" type from which it is derived.");
- // Create a Type object representing the generic type definition
+ // Create a Type object representing the generic type definition
// for the Derived type, by omitting the type argument. (For
// types with multiple type parameters, supply the commas but
- // omit the type arguments.)
+ // omit the type arguments.)
//
Type derivedType = typeof(Derived<>);
DisplayGenericTypeInfo(derivedType);
@@ -39,16 +39,13 @@ public static void Main()
private static void DisplayGenericTypeInfo(Type t)
{
- Console.WriteLine("\r\n{0}", t);
+ Console.WriteLine($"\r\n{t}");
- Console.WriteLine("\tIs this a generic type definition? {0}",
- t.IsGenericTypeDefinition);
+ Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}");
- Console.WriteLine("\tIs it a generic type? {0}",
- t.IsGenericType);
+ Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}");
- Console.WriteLine("\tDoes it have unassigned generic parameters? {0}",
- t.ContainsGenericParameters);
+ Console.WriteLine($"\tDoes it have unassigned generic parameters? {t.ContainsGenericParameters}");
if (t.IsGenericType)
{
@@ -56,8 +53,7 @@ private static void DisplayGenericTypeInfo(Type t)
//
Type[] typeArguments = t.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):",
- typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
@@ -66,14 +62,11 @@ private static void DisplayGenericTypeInfo(Type t)
//
if (tParam.IsGenericParameter)
{
- Console.WriteLine(
- "\t\t{0} (unassigned - parameter position {1})",
- tParam,
- tParam.GenericParameterPosition);
+ Console.WriteLine($"\t\t{tParam} (unassigned - parameter position {tParam.GenericParameterPosition})");
}
else
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
diff --git a/snippets/csharp/System/Type/DeclaringMethod/source.cs b/snippets/csharp/System/Type/DeclaringMethod/source.cs
index 486c25baa98..391fd17f392 100644
--- a/snippets/csharp/System/Type/DeclaringMethod/source.cs
+++ b/snippets/csharp/System/Type/DeclaringMethod/source.cs
@@ -6,10 +6,7 @@
// Define a class with a generic method.
public class Example
{
- public static void Generic(T toDisplay)
- {
- Console.WriteLine("\r\nHere it is: {0}", toDisplay);
- }
+ public static void Generic(T toDisplay) => Console.WriteLine($"\r\nHere it is: {toDisplay}");
}
//
@@ -37,7 +34,7 @@ public static void Main()
//
// Invoke the method.
- object[] args = {42};
+ object[] args = [42];
miConstructed.Invoke(null, args);
// Invoke the method normally.
@@ -48,28 +45,24 @@ public static void Main()
// and show it's the same as the original definition.
//
MethodInfo miDef = miConstructed.GetGenericMethodDefinition();
- Console.WriteLine("\r\nThe definition is the same: {0}",
- miDef == mi);
+ Console.WriteLine($"\r\nThe definition is the same: {miDef == mi}");
//
}
private static void DisplayGenericMethodInfo(MethodInfo mi)
{
- Console.WriteLine("\r\n{0}", mi);
+ Console.WriteLine($"\r\n{mi}");
//
- Console.WriteLine("\tIs this a generic method definition? {0}",
- mi.IsGenericMethodDefinition);
+ Console.WriteLine($"\tIs this a generic method definition? {mi.IsGenericMethodDefinition}");
//
//
- Console.WriteLine("\tIs it a generic method? {0}",
- mi.IsGenericMethod);
+ Console.WriteLine($"\tIs it a generic method? {mi.IsGenericMethod}");
//
//
- Console.WriteLine("\tDoes it have unassigned generic parameters? {0}",
- mi.ContainsGenericParameters);
+ Console.WriteLine($"\tDoes it have unassigned generic parameters? {mi.ContainsGenericParameters}");
//
//
@@ -79,8 +72,7 @@ private static void DisplayGenericMethodInfo(MethodInfo mi)
{
Type[] typeArguments = mi.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):",
- typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
@@ -97,7 +89,7 @@ private static void DisplayGenericMethodInfo(MethodInfo mi)
}
else
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
diff --git a/snippets/csharp/System/Type/DeclaringType/remarks.cs b/snippets/csharp/System/Type/DeclaringType/remarks.cs
index 65cefe2b1d1..8df6af54a2b 100644
--- a/snippets/csharp/System/Type/DeclaringType/remarks.cs
+++ b/snippets/csharp/System/Type/DeclaringType/remarks.cs
@@ -5,9 +5,9 @@ class ProgStubClass
{
public static void Main()
{
-//
+ //
Type t = typeof(List).GetMethod("ConvertAll").GetGenericArguments()[0].DeclaringType;
-//
- Console.WriteLine("Declaring type: {0:s}", t.FullName);
+ //
+ Console.WriteLine($"Declaring type: {t.FullName:s}");
}
-}
\ No newline at end of file
+}
diff --git a/snippets/csharp/System/Type/DeclaringType/source.cs b/snippets/csharp/System/Type/DeclaringType/source.cs
index c89abffcee0..1ed1680ee72 100644
--- a/snippets/csharp/System/Type/DeclaringType/source.cs
+++ b/snippets/csharp/System/Type/DeclaringType/source.cs
@@ -1,6 +1,6 @@
//
using System;
-using System.Reflection;
+
public abstract class dtype
{
@@ -14,11 +14,7 @@ public abstract class MyClassB : MyClassA
{
}
- public static void Main(string[] args)
- {
- Console.WriteLine("The declaring type of m is {0}.",
- typeof(MyClassB).GetMethod("m").DeclaringType);
- }
+ public static void Main(string[] args) => Console.WriteLine($"The declaring type of m is {typeof(MyClassB).GetMethod("m").DeclaringType}.");
}
/* The example produces the following output:
diff --git a/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs b/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs
index cf63b5bcb1d..79837db8991 100644
--- a/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs
+++ b/snippets/csharp/System/Type/DefaultBinder/type_defaultbinder.cs
@@ -9,23 +9,20 @@ public static void Main()
try
{
Binder defaultBinder = Type.DefaultBinder;
- MyClass myClass = new MyClass();
+ MyClass myClass = new();
// Invoke the HelloWorld method of MyClass.
myClass.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod,
- defaultBinder, myClass, new object [] {});
+ defaultBinder, myClass, []);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception :" + e.Message);
}
- }
+ }
class MyClass
{
- public void HelloWorld()
- {
- Console.WriteLine("Hello World");
- }
+ public void HelloWorld() => Console.WriteLine("Hello World");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/EmptyTypes/Project.csproj b/snippets/csharp/System/Type/EmptyTypes/Project.csproj
new file mode 100644
index 00000000000..1eddf5e00ac
--- /dev/null
+++ b/snippets/csharp/System/Type/EmptyTypes/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Library
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/EmptyTypes/source.cs b/snippets/csharp/System/Type/EmptyTypes/source.cs
index 904cf7bd34d..dfe135cac1a 100644
--- a/snippets/csharp/System/Type/EmptyTypes/source.cs
+++ b/snippets/csharp/System/Type/EmptyTypes/source.cs
@@ -1,15 +1,15 @@
using System;
-using System.IO;
using System.Reflection;
public class Sample
{
- public void Method(Type type) {
+ public void Method(Type type)
+ {
ConstructorInfo cInfo;
-//
-cInfo = type.GetConstructor (BindingFlags.ExactBinding, null,
- Type.EmptyTypes, null);
-//
+ //
+ cInfo = type.GetConstructor(BindingFlags.ExactBinding, null,
+ Type.EmptyTypes, null);
+ //
}
}
diff --git a/snippets/csharp/System/Type/Equals/EqualsEx1.cs b/snippets/csharp/System/Type/Equals/EqualsEx1.cs
index 6d50d87251a..acb0ad6a5d3 100644
--- a/snippets/csharp/System/Type/Equals/EqualsEx1.cs
+++ b/snippets/csharp/System/Type/Equals/EqualsEx1.cs
@@ -3,50 +3,49 @@
using System.Collections.Generic;
using System.Reflection;
-public class Example
+public class EqualsEx1Example
{
- public static void Main()
- {
- Type t =typeof(int);
- Object obj1 = typeof(int).GetTypeInfo();
- IsEqualTo(t, obj1);
+ public static void Run()
+ {
+ Type t = typeof(int);
+ object obj1 = typeof(int).GetTypeInfo();
+ IsEqualTo(t, obj1);
- Object obj2 = typeof(String);
- IsEqualTo(t, obj2);
-
- t = typeof(Object);
- Object obj3 = typeof(Object);
- IsEqualTo(t, obj3);
-
- t = typeof(List<>);
- Object obj4 = (new List()).GetType();
- IsEqualTo(t, obj4);
-
- t = typeof(Type);
- Object obj5 = null;
- IsEqualTo(t, obj5);
- }
-
- private static void IsEqualTo(Type t, Object inst)
- {
- Type t2 = inst as Type;
- if (t2 != null)
- Console.WriteLine("{0} = {1}: {2}", t.Name, t2.Name,
- t.Equals(t2));
- else
- Console.WriteLine("Cannot cast the argument to a type.");
+ object obj2 = typeof(string);
+ IsEqualTo(t, obj2);
- Console.WriteLine();
- }
+ t = typeof(object);
+ object obj3 = typeof(object);
+ IsEqualTo(t, obj3);
+
+ t = typeof(List<>);
+ object obj4 = (new List()).GetType();
+ IsEqualTo(t, obj4);
+
+ t = typeof(Type);
+ object obj5 = null;
+ IsEqualTo(t, obj5);
+ }
+
+ private static void IsEqualTo(Type t, object inst)
+ {
+ Type t2 = inst as Type;
+ if (t2 != null)
+ Console.WriteLine($"{t.Name} = {t2.Name}: {t.Equals(t2)}");
+ else
+ Console.WriteLine("Cannot cast the argument to a type.");
+
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// Int32 = Int32: True
-//
+//
// Int32 = String: False
-//
+//
// Object = Object: True
-//
+//
// List`1 = List`1: False
-//
+//
// Cannot cast the argument to a type.
//
diff --git a/snippets/csharp/System/Type/Equals/Program.cs b/snippets/csharp/System/Type/Equals/Program.cs
new file mode 100644
index 00000000000..eee72699813
--- /dev/null
+++ b/snippets/csharp/System/Type/Equals/Program.cs
@@ -0,0 +1,2 @@
+EqualsEx1Example.Run();
+EqualsSourceExample.Run();
diff --git a/snippets/csharp/System/Type/Equals/Project.csproj b/snippets/csharp/System/Type/Equals/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/Equals/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/Equals/source.cs b/snippets/csharp/System/Type/Equals/source.cs
index 2e1a1ec3040..e8abbf1e765 100644
--- a/snippets/csharp/System/Type/Equals/source.cs
+++ b/snippets/csharp/System/Type/Equals/source.cs
@@ -1,32 +1,32 @@
//
using System;
-using System.Reflection;
-class Example
+
+class EqualsSourceExample
{
- public static void Main()
+ public static void Run()
{
- Type a = typeof(System.String);
- Type b = typeof(System.Int32);
+ Type a = typeof(string);
+ Type b = typeof(int);
- Console.WriteLine("{0} == {1}: {2}", a, b, a.Equals(b));
+ Console.WriteLine($"{a} == {b}: {a.Equals(b)}");
// The Type objects in a and b are not equal,
// because they represent different types.
- a = typeof(Example);
- b = new Example().GetType();
+ a = typeof(EqualsSourceExample);
+ b = new EqualsSourceExample().GetType();
- Console.WriteLine("{0} is equal to {1}: {2}", a, b, a.Equals(b));
+ Console.WriteLine($"{a} is equal to {b}: {a.Equals(b)}");
// The Type objects in a and b are equal,
// because they both represent type Example.
b = typeof(Type);
- Console.WriteLine("typeof({0}).Equals(typeof({1})): {2}", a, b, a.Equals(b));
+ Console.WriteLine($"typeof({a}).Equals(typeof({b})): {a.Equals(b)}");
// The Type objects in a and b are not equal,
// because variable a represents type Example
@@ -42,4 +42,4 @@ public static void Main()
Example is equal to Example: True
typeof(Example).Equals(typeof(System.Type)): False
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs b/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs
index f2a0fe4c3e0..178b7278b03 100644
--- a/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs
+++ b/snippets/csharp/System/Type/FilterAttribute/type_filterattribute.cs
@@ -10,28 +10,28 @@ public static void Main()
try
{
MemberFilter myFilter = Type.FilterAttribute;
- Type myType = typeof(System.String);
+ Type myType = typeof(string);
MemberInfo[] myMemberInfoArray = myType.FindMembers(MemberTypes.Constructor
- |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
+ | MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance, myFilter, MethodAttributes.SpecialName);
foreach (MemberInfo myMemberinfo in myMemberInfoArray)
{
- Console.Write ("\n" + myMemberinfo.Name);
- Console.Write (" is a " + myMemberinfo.MemberType.ToString());
+ Console.Write("\n" + myMemberinfo.Name);
+ Console.Write(" is a " + myMemberinfo.MemberType);
}
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.Write("ArgumentNullException : " + e.Message);
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.Write("SecurityException : " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.Write("Exception :" + e.Message);
}
- }
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/FilterName/Project.csproj b/snippets/csharp/System/Type/FilterName/Project.csproj
new file mode 100644
index 00000000000..1eddf5e00ac
--- /dev/null
+++ b/snippets/csharp/System/Type/FilterName/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Library
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/FilterName/source.cs b/snippets/csharp/System/Type/FilterName/source.cs
index 350fbe03859..fb3126f09c6 100644
--- a/snippets/csharp/System/Type/FilterName/source.cs
+++ b/snippets/csharp/System/Type/FilterName/source.cs
@@ -3,22 +3,24 @@
public class Sample
{
- public void Method()
- {
-//
- // Get the set of methods associated with the type
- MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor |
- MemberTypes.Method,
- BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
- BindingFlags.Instance | BindingFlags.DeclaredOnly,
- Type.FilterName, "*");
- Console.WriteLine("Number of methods (includes constructors): " + mi.Length);
-//
- }
+ public void Method()
+ {
+ //
+ // Get the set of methods associated with the type
+ MemberInfo[] mi = typeof(Application).FindMembers(MemberTypes.Constructor |
+ MemberTypes.Method,
+ BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic |
+ BindingFlags.Instance | BindingFlags.DeclaredOnly,
+ Type.FilterName, "*");
+ Console.WriteLine("Number of methods (includes constructors): " + mi.Length);
+ //
+ }
}
// Class added so sample will compile
-public class Application {
- public void Method() {
+public class Application
+{
+ public void Method()
+ {
}
}
diff --git a/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs b/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs
index 419668f72c1..39d5c5df732 100644
--- a/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs
+++ b/snippets/csharp/System/Type/FilterNameIgnoreCase/type_filternameignorecase.cs
@@ -7,31 +7,31 @@ public class MyFilterNameIgnoreCaseSample
public static void Main()
{
try
- {
+ {
MemberFilter myFilter = Type.FilterNameIgnoreCase;
- Type myType = typeof(System.String);
+ Type myType = typeof(string);
MemberInfo[] myMemberinfo1 = myType.FindMembers(MemberTypes.Constructor
- |MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
+ | MemberTypes.Method, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance, myFilter, "C*");
foreach (MemberInfo myMemberinfo2 in myMemberinfo1)
{
Console.Write("\n" + myMemberinfo2.Name);
MemberTypes Mymembertypes = myMemberinfo2.MemberType;
- Console.WriteLine(" is a " + Mymembertypes.ToString());
+ Console.WriteLine(" is a " + Mymembertypes);
}
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.Write("ArgumentNullException : " + e.Message);
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.Write("SecurityException : " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.Write("Exception : " + e.Message);
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs b/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs
index bf7c4b78a44..896ac2b0612 100644
--- a/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs
+++ b/snippets/csharp/System/Type/FindInterfaces/type_findinterfaces.cs
@@ -9,55 +9,51 @@ public static void Main()
{
try
{
- XmlDocument myXMLDoc = new XmlDocument();
+ XmlDocument myXMLDoc = new();
myXMLDoc.LoadXml("" +
"Pride And Prejudice" + "");
Type myType = myXMLDoc.GetType();
// Specify the TypeFilter delegate that compares the
// interfaces against filter criteria.
- TypeFilter myFilter = new TypeFilter(MyInterfaceFilter);
- String[] myInterfaceList = new String[2]
- {"System.Collections.IEnumerable",
- "System.Collections.ICollection"};
- for(int index=0; index < myInterfaceList.Length; index++)
+ TypeFilter myFilter = new(MyInterfaceFilter);
+ string[] myInterfaceList =
+ ["System.Collections.IEnumerable",
+ "System.Collections.ICollection"];
+ for (int index = 0; index < myInterfaceList.Length; index++)
{
Type[] myInterfaces = myType.FindInterfaces(myFilter,
myInterfaceList[index]);
if (myInterfaces.Length > 0)
{
- Console.WriteLine("\n{0} implements the interface {1}.",
- myType, myInterfaceList[index]);
- for(int j =0;j < myInterfaces.Length;j++)
- Console.WriteLine("Interfaces supported: {0}.",
- myInterfaces[j].ToString());
+ Console.WriteLine($"\n{myType} implements the interface {myInterfaceList[index]}.");
+ for (int j = 0; j < myInterfaces.Length; j++)
+ Console.WriteLine($"Interfaces supported: {myInterfaces[j]}.");
}
else
- Console.WriteLine(
- "\n{0} does not implement the interface {1}.",
- myType,myInterfaceList[index]);
+ Console.WriteLine($"\n{myType} does not implement the interface {myInterfaceList[index]}.");
}
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
- catch(TargetInvocationException e)
+ catch (TargetInvocationException e)
{
Console.WriteLine("TargetInvocationException: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
- public static bool MyInterfaceFilter(Type typeObj,Object criteriaObj)
+ public static bool MyInterfaceFilter(Type typeObj, object criteriaObj)
{
- if(typeObj.ToString() == criteriaObj.ToString())
+ if (typeObj.FullName == criteriaObj as string)
return true;
else
return false;
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/FindMembers/type_findmembers.cs b/snippets/csharp/System/Type/FindMembers/type_findmembers.cs
index e0fee47a706..5caae3e13b4 100644
--- a/snippets/csharp/System/Type/FindMembers/type_findmembers.cs
+++ b/snippets/csharp/System/Type/FindMembers/type_findmembers.cs
@@ -6,29 +6,29 @@ class MyFindMembersClass
{
public static void Main()
{
- Object objTest = new Object();
- Type objType = objTest.GetType ();
+ object objTest = new();
+ Type objType = objTest.GetType();
MemberInfo[] arrayMemberInfo;
try
{
//Find all static or public methods in the Object class that match the specified name.
arrayMemberInfo = objType.FindMembers(MemberTypes.Method,
- BindingFlags.Public | BindingFlags.Static| BindingFlags.Instance,
+ BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
new MemberFilter(DelegateToSearchCriteria),
"ReferenceEquals");
- for(int index=0;index < arrayMemberInfo.Length ;index++)
- Console.WriteLine ("Result of FindMembers -\t"+ arrayMemberInfo[index].ToString() +"\n");
+ for (int index = 0; index < arrayMemberInfo.Length; index++)
+ Console.WriteLine("Result of FindMembers -\t" + arrayMemberInfo[index] + "\n");
}
catch (Exception e)
{
- Console.WriteLine ("Exception : " + e.ToString() );
+ Console.WriteLine("Exception : " + e);
}
}
- public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object objSearch)
+ public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, object objSearch)
{
// Compare the name of the member function with the filter criteria.
- if(objMemberInfo.Name.ToString() == objSearch.ToString())
+ if (objMemberInfo.Name == objSearch as string)
return true;
else
return false;
@@ -38,4 +38,4 @@ public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object obj
Result of FindMembers - Boolean ReferenceEquals(System.Object, System.Object)
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/FullName/Fullname3.cs b/snippets/csharp/System/Type/FullName/Fullname3.cs
index 3e1a2dcf054..edae78a295d 100644
--- a/snippets/csharp/System/Type/FullName/Fullname3.cs
+++ b/snippets/csharp/System/Type/FullName/Fullname3.cs
@@ -1,23 +1,25 @@
//
using System;
-using System.Reflection;
-public class Example
+
+public class FullName3Example
{
- public static void Main()
- {
- Type t = typeof(Nullable<>);
- Console.WriteLine(t.FullName);
- if (t.IsGenericType) {
- Console.Write(" Generic Type Parameters: ");
- Type[] gtArgs = t.GetGenericArguments();
- for (int ctr = 0; ctr < gtArgs.Length; ctr++) {
- Console.WriteLine(gtArgs[ctr].FullName ??
- "(unassigned) " + gtArgs[ctr].ToString());
- }
- Console.WriteLine();
- }
- }
+ public static void Run()
+ {
+ Type t = typeof(Nullable<>);
+ Console.WriteLine(t.FullName);
+ if (t.IsGenericType)
+ {
+ Console.Write(" Generic Type Parameters: ");
+ Type[] gtArgs = t.GetGenericArguments();
+ for (int ctr = 0; ctr < gtArgs.Length; ctr++)
+ {
+ Console.WriteLine(gtArgs[ctr].FullName ??
+ "(unassigned) " + gtArgs[ctr]);
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// System.Nullable`1
diff --git a/snippets/csharp/System/Type/FullName/Fullname4.cs b/snippets/csharp/System/Type/FullName/Fullname4.cs
index 0d349fefccc..759c08a48a0 100644
--- a/snippets/csharp/System/Type/FullName/Fullname4.cs
+++ b/snippets/csharp/System/Type/FullName/Fullname4.cs
@@ -2,41 +2,38 @@
using System;
using System.Reflection;
-public class GenericType1
+public class GenericType1
{
- public void Display(T[] elements)
- {}
-
- public void HandleT(T obj)
- {}
-
- public bool ChangeValue(ref T arg)
- {
- return true;
- }
+ public void Display(T[] elements)
+ { }
+
+ public void HandleT(T obj)
+ { }
+
+ public bool ChangeValue(ref T arg) => true;
}
-public class Example
+public class FullName4Example
{
- public static void Main()
- {
- Type t = typeof(GenericType1<>);
- Console.WriteLine("Type Name: {0}", t.FullName);
- MethodInfo[] methods = t.GetMethods(BindingFlags.Instance |
- BindingFlags.DeclaredOnly |
- BindingFlags.Public);
- foreach (var method in methods) {
- Console.WriteLine(" Method: {0}", method.Name);
- // Get method parameters.
- ParameterInfo param = method.GetParameters()[0];
- Type paramType = param.ParameterType;
- if (method.Name == "HandleT")
- paramType = paramType.MakePointerType();
- Console.WriteLine(" Parameter: {0}",
- paramType.FullName ??
- paramType.ToString() + " (unassigned)");
- }
- }
+ public static void Run()
+ {
+ Type t = typeof(GenericType1<>);
+ Console.WriteLine($"Type Name: {t.FullName}");
+ MethodInfo[] methods = t.GetMethods(BindingFlags.Instance |
+ BindingFlags.DeclaredOnly |
+ BindingFlags.Public);
+ foreach (var method in methods)
+ {
+ Console.WriteLine($" Method: {method.Name}");
+ // Get method parameters.
+ ParameterInfo param = method.GetParameters()[0];
+ Type paramType = param.ParameterType;
+ if (method.Name == "HandleT")
+ paramType = paramType.MakePointerType();
+ Console.WriteLine($" Parameter: {paramType.FullName ??
+ paramType + " (unassigned)"}");
+ }
+ }
}
// The example displays the following output:
// Type Name: GenericType1`1
diff --git a/snippets/csharp/System/Type/FullName/Fullname5.cs b/snippets/csharp/System/Type/FullName/Fullname5.cs
index c2bd57eb565..90538136f52 100644
--- a/snippets/csharp/System/Type/FullName/Fullname5.cs
+++ b/snippets/csharp/System/Type/FullName/Fullname5.cs
@@ -1,51 +1,43 @@
//
using System;
-using System.Reflection;
+
public class Base { }
public class Derived : Base { }
-public class Example
+public class FullName5Example
{
- public static void Main()
- {
- Type t = typeof(Derived<>);
- Console.WriteLine("Generic Class: {0}", t.FullName);
- Console.WriteLine(" Contains Generic Paramters: {0}",
- t.ContainsGenericParameters);
- Console.WriteLine(" Generic Type Definition: {0}\n",
- t.IsGenericTypeDefinition);
+ public static void Run()
+ {
+ Type t = typeof(Derived<>);
+ Console.WriteLine($"Generic Class: {t.FullName}");
+ Console.WriteLine($" Contains Generic Paramters: {t.ContainsGenericParameters}");
+ Console.WriteLine($" Generic Type Definition: {t.IsGenericTypeDefinition}\n");
- Type baseType = t.BaseType;
- Console.WriteLine("Its Base Class: {0}",
- baseType.FullName ??
- "(unassigned) " + baseType.ToString());
- Console.WriteLine(" Contains Generic Paramters: {0}",
- baseType.ContainsGenericParameters);
- Console.WriteLine(" Generic Type Definition: {0}",
- baseType.IsGenericTypeDefinition);
- Console.WriteLine(" Full Name: {0}\n",
- baseType.GetGenericTypeDefinition().FullName);
+ Type baseType = t.BaseType;
+ Console.WriteLine($"Its Base Class: {baseType.FullName ??
+ "(unassigned) " + baseType}");
+ Console.WriteLine($" Contains Generic Paramters: {baseType.ContainsGenericParameters}");
+ Console.WriteLine($" Generic Type Definition: {baseType.IsGenericTypeDefinition}");
+ Console.WriteLine($" Full Name: {baseType.GetGenericTypeDefinition().FullName}\n");
- t = typeof(Base<>);
- Console.WriteLine("Generic Class: {0}", t.FullName);
- Console.WriteLine(" Contains Generic Paramters: {0}",
- t.ContainsGenericParameters);
- Console.WriteLine(" Generic Type Definition: {0}\n",
- t.IsGenericTypeDefinition);
- }
+ t = typeof(Base<>);
+ Console.WriteLine($"Generic Class: {t.FullName}");
+ Console.WriteLine($" Contains Generic Paramters: {t.ContainsGenericParameters}");
+ Console.WriteLine($" Generic Type Definition: {t.IsGenericTypeDefinition}\n");
+ }
}
// The example displays the following output:
// Generic Class: Derived`1
// Contains Generic Paramters: True
// Generic Type Definition: True
-//
+//
// Its Base Class: (unassigned) Base`1[T]
// Contains Generic Paramters: True
// Generic Type Definition: False
// Full Name: Base`1
-//
+//
// Generic Class: Base`1
// Contains Generic Paramters: True
// Generic Type Definition: True
diff --git a/snippets/csharp/System/Type/FullName/Program.cs b/snippets/csharp/System/Type/FullName/Program.cs
new file mode 100644
index 00000000000..7356154ae2f
--- /dev/null
+++ b/snippets/csharp/System/Type/FullName/Program.cs
@@ -0,0 +1,5 @@
+FullName3Example.Run();
+FullName4Example.Run();
+FullName5Example.Run();
+FullNameEx1Example.Run();
+TestFullName.Run();
diff --git a/snippets/csharp/System/Type/FullName/Project.csproj b/snippets/csharp/System/Type/FullName/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/FullName/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/FullName/fullnameex1.cs b/snippets/csharp/System/Type/FullName/fullnameex1.cs
index ef2b91e4e60..612ee255318 100644
--- a/snippets/csharp/System/Type/FullName/fullnameex1.cs
+++ b/snippets/csharp/System/Type/FullName/fullnameex1.cs
@@ -2,18 +2,18 @@
using System;
using System.Collections.Generic;
-public class Example
+public class FullNameEx1Example
{
- public static void Main()
- {
- Type t = typeof(List<>);
- Console.WriteLine(t.FullName);
- Console.WriteLine();
+ public static void Run()
+ {
+ Type t = typeof(List<>);
+ Console.WriteLine(t.FullName);
+ Console.WriteLine();
- List list = new List();
- t = list.GetType();
- Console.WriteLine(t.FullName);
- }
+ List list = new();
+ t = list.GetType();
+ Console.WriteLine(t.FullName);
+ }
}
// The example displays the following output:
// System.Collections.Generic.List`1
diff --git a/snippets/csharp/System/Type/FullName/testfullname.cs b/snippets/csharp/System/Type/FullName/testfullname.cs
index cd4311ff848..770a078fd45 100644
--- a/snippets/csharp/System/Type/FullName/testfullname.cs
+++ b/snippets/csharp/System/Type/FullName/testfullname.cs
@@ -2,10 +2,10 @@
using System;
class TestFullName
{
-public static void Main()
+ public static void Run()
{
- Type t = typeof(Array);
- Console.WriteLine("The full name of the Array type is {0}.", t.FullName);
+ Type t = typeof(Array);
+ Console.WriteLine($"The full name of the Array type is {t.FullName}.");
}
}
@@ -13,4 +13,4 @@ public static void Main()
The full name of the Array type is System.Array.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GUID/type_guid.cs b/snippets/csharp/System/Type/GUID/type_guid.cs
index 3d8d9ae108f..338f32dcfee 100644
--- a/snippets/csharp/System/Type/GUID/type_guid.cs
+++ b/snippets/csharp/System/Type/GUID/type_guid.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
class MyGetTypeFromCLSID
@@ -14,9 +14,9 @@ public static void Main()
// Get the type corresponding to the class MyClass.
Type myType = typeof(MyClass1);
// Get the object of the Guid.
- Guid myGuid =(Guid) myType.GUID;
- Console.WriteLine("The name of the class is "+myType.ToString());
- Console.WriteLine("The ClassId of MyClass is "+myType.GUID);
+ Guid myGuid = (Guid)myType.GUID;
+ Console.WriteLine("The name of the class is " + myType);
+ Console.WriteLine("The ClassId of MyClass is " + myType.GUID);
}
}
//
diff --git a/snippets/csharp/System/Type/GenericParameterAttributes/source.cs b/snippets/csharp/System/Type/GenericParameterAttributes/source.cs
index de9251c2277..a7706371fc2 100644
--- a/snippets/csharp/System/Type/GenericParameterAttributes/source.cs
+++ b/snippets/csharp/System/Type/GenericParameterAttributes/source.cs
@@ -3,24 +3,25 @@
using System.Reflection;
// Define a sample interface to use as an interface constraint.
-public interface ITest {}
+public interface ITest { }
// Define a base type to use as a base class constraint.
-public class Base {}
+public class Base { }
// Define the generic type to examine. The first generic type parameter,
// T, derives from the class Base and implements ITest. This demonstrates
-// a base class constraint and an interface constraint. The second generic
-// type parameter, U, must be a reference type (class) and must have a
+// a base class constraint and an interface constraint. The second generic
+// type parameter, U, must be a reference type (class) and must have a
// default constructor (new()). This demonstrates special constraints.
//
-public class Test
- where T : Base, ITest
- where U : class, new() {}
+public class Test
+ where T : Base, ITest
+ where U : class, new()
+{ }
// Define a type that derives from Base and implements ITest. This type
// satisfies the constraints on T in class Test.
-public class Derived : Base, ITest {}
+public class Derived : Base, ITest { }
public class Example
{
@@ -28,10 +29,10 @@ public static void Main()
{
// To get the generic type definition, omit the type
// arguments but retain the comma to indicate the number
- // of type arguments.
+ // of type arguments.
//
Type def = typeof(Test<,>);
- Console.WriteLine("\r\nExamining generic type {0}", def);
+ Console.WriteLine($"\r\nExamining generic type {def}");
// Get the type parameters of the generic type definition,
// and display them.
@@ -39,30 +40,29 @@ public static void Main()
Type[] defparams = def.GetGenericArguments();
foreach (Type tp in defparams)
{
- Console.WriteLine("\r\nType parameter: {0}", tp.Name);
- Console.WriteLine("\t{0}",
- ListGenericParameterAttributes(tp));
+ Console.WriteLine($"\r\nType parameter: {tp.Name}");
+ Console.WriteLine($"\t{ListGenericParameterAttributes(tp)}");
// List the base class and interface constraints. The
- // constraints are returned in no particular order. If
+ // constraints are returned in no particular order. If
// there are no class or interface constraints, an empty
// array is returned.
//
Type[] tpConstraints = tp.GetGenericParameterConstraints();
foreach (Type tpc in tpConstraints)
{
- Console.WriteLine("\t{0}", tpc);
+ Console.WriteLine($"\t{tpc}");
}
}
}
- // List the variance and special constraint flags.
+ // List the variance and special constraint flags.
//
private static string ListGenericParameterAttributes(Type t)
{
string retval;
GenericParameterAttributes gpa = t.GenericParameterAttributes;
- GenericParameterAttributes variance = gpa &
+ GenericParameterAttributes variance = gpa &
GenericParameterAttributes.VarianceMask;
// Select the variance flags.
@@ -78,8 +78,8 @@ private static string ListGenericParameterAttributes(Type t)
retval = "Contravariant;";
}
- // Select
- GenericParameterAttributes constraints = gpa &
+ // Select
+ GenericParameterAttributes constraints = gpa &
GenericParameterAttributes.SpecialConstraintMask;
if (constraints == GenericParameterAttributes.None)
diff --git a/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs b/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs
index 007f013977c..5966452546e 100644
--- a/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs
+++ b/snippets/csharp/System/Type/GenericParameterPosition/remarks.cs
@@ -1,17 +1,14 @@
-using System;
+
//
public class B { }
public class A
{
- public B GetSomething()
- {
- return new B();
- }
+ public B GetSomething() => new B();
}
//
class ProgStubClass
{
- public static void Main() {}
-}
\ No newline at end of file
+ public static void Main() { }
+}
diff --git a/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs b/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs
index 0048d76a9dc..ce178bbc8e8 100644
--- a/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs
+++ b/snippets/csharp/System/Type/GetArrayRank/type_getarrayrank.cs
@@ -7,19 +7,19 @@ public static void Main()
{
try
{
- int[,,] myArray = new int[,,] {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}};
+ int[,,] myArray = new int[,,] { { { 12, 2, 35 }, { 300, 78, 33 } }, { { 92, 42, 135 }, { 30, 7, 3 } } };
Type myType = myArray.GetType();
Console.WriteLine("Contents of myArray: {{{12,2,35},{300,78,33}},{{92,42,135},{30,7,3}}}");
- Console.WriteLine("myArray has {0} dimensions.", myType.GetArrayRank());
+ Console.WriteLine($"myArray has {myType.GetArrayRank()} dimensions.");
}
- catch(NotSupportedException e)
+ catch (NotSupportedException e)
{
Console.WriteLine("NotSupportedException raised.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception raised.");
Console.WriteLine("Source: " + e.Source);
diff --git a/snippets/csharp/System/Type/GetConstructors/Program.cs b/snippets/csharp/System/Type/GetConstructors/Program.cs
new file mode 100644
index 00000000000..4c65e4bcd95
--- /dev/null
+++ b/snippets/csharp/System/Type/GetConstructors/Program.cs
@@ -0,0 +1,2 @@
+ConstructorSample1.Run();
+ConstructorSample2.Run();
diff --git a/snippets/csharp/System/Type/GetConstructors/Project.csproj b/snippets/csharp/System/Type/GetConstructors/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetConstructors/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetConstructors/source1.cs b/snippets/csharp/System/Type/GetConstructors/source1.cs
index 64bca042ab6..884433d1674 100644
--- a/snippets/csharp/System/Type/GetConstructors/source1.cs
+++ b/snippets/csharp/System/Type/GetConstructors/source1.cs
@@ -1,19 +1,21 @@
//
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
- public class t {
- public t() {}
- static t() {}
- public t(int i) {}
+public class ConstructorSample1
+{
+ public ConstructorSample1() { }
+ static ConstructorSample1() { }
+ public ConstructorSample1(int i) { }
+ public static void Run()
+ {
+ ConstructorInfo[] p = typeof(ConstructorSample1).GetConstructors();
+ Console.WriteLine(p.Length);
- public static void Main() {
- ConstructorInfo[] p = typeof(t).GetConstructors();
- Console.WriteLine(p.Length);
-
- for (int i=0;i
diff --git a/snippets/csharp/System/Type/GetConstructors/source2.cs b/snippets/csharp/System/Type/GetConstructors/source2.cs
index 4a8a66813cd..ebecc5c5ca9 100644
--- a/snippets/csharp/System/Type/GetConstructors/source2.cs
+++ b/snippets/csharp/System/Type/GetConstructors/source2.cs
@@ -1,21 +1,23 @@
//
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
- public class t {
- public t() {}
- static t() {}
- public t(int i) {}
+public class ConstructorSample2
+{
+ public ConstructorSample2() { }
+ static ConstructorSample2() { }
+ public ConstructorSample2(int i) { }
+ public static void Run()
+ {
+ ConstructorInfo[] p = typeof(ConstructorSample2).GetConstructors(
+ BindingFlags.Public | BindingFlags.Static |
+ BindingFlags.NonPublic | BindingFlags.Instance);
+ Console.WriteLine(p.Length);
- public static void Main() {
- ConstructorInfo[] p = typeof(t).GetConstructors(
- BindingFlags.Public | BindingFlags.Static |
- BindingFlags.NonPublic | BindingFlags.Instance);
- Console.WriteLine(p.Length);
-
- for (int i=0;i
diff --git a/snippets/csharp/System/Type/GetDefaultMembers/source2.cs b/snippets/csharp/System/Type/GetDefaultMembers/source2.cs
index e5be6267577..7bc4770e6c5 100644
--- a/snippets/csharp/System/Type/GetDefaultMembers/source2.cs
+++ b/snippets/csharp/System/Type/GetDefaultMembers/source2.cs
@@ -15,15 +15,9 @@ public Class1()
sval = "6040";
}
- public int GetIVal()
- {
- return ival;
- }
+ public int GetIVal() => ival;
- public string GetSVal()
- {
- return sval;
- }
+ public string GetSVal() => sval;
}
//
@@ -32,10 +26,10 @@ public class GetMemberExample
public static void Main()
{
//
- Class1 c = new Class1();
+ Class1 c = new();
object o;
o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, null, c, new object[0]);
- Console.WriteLine("Default member result: {0}", o);
+ Console.WriteLine($"Default member result: {o}");
//
GetDefMemberExample1();
@@ -52,9 +46,9 @@ public static void GetDefMemberExample1()
(DefaultMemberAttribute)Attribute.GetCustomAttribute((MemberInfo)classType, attribType);
MemberInfo[] memInfo = classType.GetMember(defMem.MemberName);
//
- if ( memInfo.Length > 0)
+ if (memInfo.Length > 0)
{
- Console.WriteLine("Default Member: {0}", memInfo[0].Name);
+ Console.WriteLine($"Default Member: {memInfo[0].Name}");
}
}
@@ -64,9 +58,9 @@ public static void GetDefMemberExample2()
Type t = typeof(Class1);
MemberInfo[] memInfo = t.GetDefaultMembers();
//
- if ( memInfo.Length > 0)
+ if (memInfo.Length > 0)
{
- Console.WriteLine("Default Member: {0}", memInfo[0].Name);
+ Console.WriteLine($"Default Member: {memInfo[0].Name}");
}
}
@@ -81,7 +75,7 @@ public static void GetDefMemberExample3()
MemberInfo[] memInfo = t.GetMember(defMem.MemberName);
if (memInfo.Length > 0)
{
- Console.WriteLine("Default Member: {0}", memInfo[0].Name);
+ Console.WriteLine($"Default Member: {memInfo[0].Name}");
}
}
//
diff --git a/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs b/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs
index 11ac59b32f6..2d6817171e9 100644
--- a/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs
+++ b/snippets/csharp/System/Type/GetDefaultMembers/type_getdefaultmembers.cs
@@ -6,25 +6,19 @@
[DefaultMemberAttribute("Age")]
public class MyClass
{
- public void Name(String s) {}
- public int Age
- {
- get
- {
- return 20;
- }
- }
+ public void Name(string s) { }
+ public int Age => 20;
public static void Main()
{
try
{
- Type myType = typeof(MyClass);
+ Type myType = typeof(MyClass);
MemberInfo[] memberInfoArray = myType.GetDefaultMembers();
if (memberInfoArray.Length > 0)
{
- foreach(MemberInfo memberInfoObj in memberInfoArray)
+ foreach (MemberInfo memberInfoObj in memberInfoArray)
{
- Console.WriteLine("The default member name is: " + memberInfoObj.ToString());
+ Console.WriteLine("The default member name is: " + memberInfoObj);
}
}
else
@@ -32,18 +26,18 @@ public static void Main()
Console.WriteLine("No default members are available.");
}
}
- catch(InvalidOperationException e)
+ catch (InvalidOperationException e)
{
Console.WriteLine("InvalidOperationException: " + e.Message);
}
- catch(IOException e)
+ catch (IOException e)
{
Console.WriteLine("IOException: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs b/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs
index fa98300952f..acc79ca852e 100644
--- a/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs
+++ b/snippets/csharp/System/Type/GetElementType/testgetelementtype.cs
@@ -4,14 +4,14 @@ class TestGetElementType
{
public static void Main()
{
- int[] array = {1,2,3};
+ int[] array = [1, 2, 3];
Type t = array.GetType();
Type t2 = t.GetElementType();
- Console.WriteLine("The element type of {0} is {1}.",array, t2.ToString());
- TestGetElementType newMe = new TestGetElementType();
+ Console.WriteLine($"The element type of {array} is {t2}.");
+ TestGetElementType newMe = new();
t = newMe.GetType();
t2 = t.GetElementType();
- Console.WriteLine("The element type of {0} is {1}.", newMe, t2==null? "null" : t2.ToString());
+ Console.WriteLine($"The element type of {newMe} is {(t2 == null ? "null" : t2.ToString())}.");
}
}
@@ -20,4 +20,4 @@ public static void Main()
The element type of System.Int32[] is System.Int32.
The element type of TestGetElementType is null.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetEvent/Program.cs b/snippets/csharp/System/Type/GetEvent/Program.cs
new file mode 100644
index 00000000000..d36c4a66d43
--- /dev/null
+++ b/snippets/csharp/System/Type/GetEvent/Program.cs
@@ -0,0 +1,2 @@
+EventExample.Run();
+EventExample1.Run();
diff --git a/snippets/csharp/System/Type/GetEvent/Project.csproj b/snippets/csharp/System/Type/GetEvent/Project.csproj
new file mode 100644
index 00000000000..1ef5ac9aa71
--- /dev/null
+++ b/snippets/csharp/System/Type/GetEvent/Project.csproj
@@ -0,0 +1,7 @@
+
+
+ Exe
+ net10.0-windows
+ true
+
+
diff --git a/snippets/csharp/System/Type/GetEvent/type_getevent.cs b/snippets/csharp/System/Type/GetEvent/type_getevent.cs
index 159dad978ab..a9a65b4ef60 100644
--- a/snippets/csharp/System/Type/GetEvent/type_getevent.cs
+++ b/snippets/csharp/System/Type/GetEvent/type_getevent.cs
@@ -3,38 +3,38 @@
using System.Reflection;
using System.Security;
-class MyEventExample
+class EventExample
{
- public static void Main()
+ public static void Run()
{
try
{
Type myType = typeof(System.Windows.Forms.Button);
EventInfo myEvent = myType.GetEvent("Click");
- if(myEvent != null)
+ if (myEvent != null)
{
Console.WriteLine("Looking for the Click event in the Button class.");
- Console.WriteLine(myEvent.ToString());
+ Console.WriteLine(myEvent);
}
else
{
Console.WriteLine("The Click event is not available in the Button class.");
}
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message :"+e.Message);
+ Console.WriteLine("Message :" + e.Message);
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message :"+e.Message);
+ Console.WriteLine("Message :" + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("The following exception was raised : {0}",e.Message);
+ Console.WriteLine($"The following exception was raised : {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/GetEvent/type_getevent1.cs b/snippets/csharp/System/Type/GetEvent/type_getevent1.cs
index 336fb59f405..b15ee9b115d 100644
--- a/snippets/csharp/System/Type/GetEvent/type_getevent1.cs
+++ b/snippets/csharp/System/Type/GetEvent/type_getevent1.cs
@@ -3,9 +3,9 @@
using System.Reflection;
using System.Security;
-class MyEventExample
+class EventExample1
{
- public static void Main()
+ public static void Run()
{
try
{
@@ -14,29 +14,29 @@ public static void Main()
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type myTypeBindingFlags = typeof(System.Windows.Forms.Button);
EventInfo myEventBindingFlags = myTypeBindingFlags.GetEvent("Click", myBindingFlags);
- if(myEventBindingFlags != null)
+ if (myEventBindingFlags != null)
{
Console.WriteLine("Looking for the Click event in the Button class with the specified BindingFlags.");
- Console.WriteLine(myEventBindingFlags.ToString());
+ Console.WriteLine(myEventBindingFlags);
}
else
{
Console.WriteLine("The Click event is not available with the Button class.");
}
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message :"+e.Message);
+ Console.WriteLine("Message :" + e.Message);
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message :"+e.Message);
+ Console.WriteLine("Message :" + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("The following exception was raised : {0}",e.Message);
+ Console.WriteLine($"The following exception was raised : {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/GetEvents/Program.cs b/snippets/csharp/System/Type/GetEvents/Program.cs
new file mode 100644
index 00000000000..25e38f87f7b
--- /dev/null
+++ b/snippets/csharp/System/Type/GetEvents/Program.cs
@@ -0,0 +1,2 @@
+EventsSample1.Run();
+EventsSample2.Run();
diff --git a/snippets/csharp/System/Type/GetEvents/Project.csproj b/snippets/csharp/System/Type/GetEvents/Project.csproj
new file mode 100644
index 00000000000..1ef5ac9aa71
--- /dev/null
+++ b/snippets/csharp/System/Type/GetEvents/Project.csproj
@@ -0,0 +1,7 @@
+
+
+ Exe
+ net10.0-windows
+ true
+
+
diff --git a/snippets/csharp/System/Type/GetEvents/type_getevents1.cs b/snippets/csharp/System/Type/GetEvents/type_getevents1.cs
index 35382b881ce..0ef51c21f60 100644
--- a/snippets/csharp/System/Type/GetEvents/type_getevents1.cs
+++ b/snippets/csharp/System/Type/GetEvents/type_getevents1.cs
@@ -3,9 +3,9 @@
using System.Reflection;
using System.Security;
-class EventsSample
+class EventsSample1
{
- public static void Main()
+ public static void Run()
{
try
{
@@ -16,21 +16,21 @@ public static void Main()
Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are : ");
for (int index = 0; index < myEventsBindingFlags.Length; index++)
{
- Console.WriteLine(myEventsBindingFlags[index].ToString());
+ Console.WriteLine(myEventsBindingFlags[index]);
}
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.WriteLine("SecurityException :" + e.Message);
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException : " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception : " + e.Message);
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetEvents/type_getevents2.cs b/snippets/csharp/System/Type/GetEvents/type_getevents2.cs
index 3ab6230ee4f..741a70c984b 100644
--- a/snippets/csharp/System/Type/GetEvents/type_getevents2.cs
+++ b/snippets/csharp/System/Type/GetEvents/type_getevents2.cs
@@ -3,9 +3,9 @@
using System.Reflection;
using System.Security;
-class EventsSample
+class EventsSample2
{
- public static void Main()
+ public static void Run()
{
try
{
@@ -16,21 +16,21 @@ public static void Main()
Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are:");
for (int index = 0; index < myEventsBindingFlags.Length; index++)
{
- Console.WriteLine(myEventsBindingFlags[index].ToString());
+ Console.WriteLine(myEventsBindingFlags[index]);
}
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.WriteLine("SecurityException:" + e.Message);
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetField/type_getfield.cs b/snippets/csharp/System/Type/GetField/type_getfield.cs
index fcd7cc1a842..8af2e2b7908 100644
--- a/snippets/csharp/System/Type/GetField/type_getfield.cs
+++ b/snippets/csharp/System/Type/GetField/type_getfield.cs
@@ -14,15 +14,12 @@ public class MyFieldClassB
private string field = "B Field";
public string Field
{
- get
- {
- return field;
- }
+ get => field;
set
{
- if (field!=value)
+ if (field != value)
{
- field=value;
+ field = value;
}
}
}
@@ -32,8 +29,8 @@ public class MyFieldInfoClass
{
public static void Main()
{
- MyFieldClassB myFieldObjectB = new MyFieldClassB();
- MyFieldClassA myFieldObjectA = new MyFieldClassA();
+ MyFieldClassB myFieldObjectB = new();
+ MyFieldClassA myFieldObjectA = new();
Type myTypeA = typeof(MyFieldClassA);
FieldInfo myFieldInfo = myTypeA.GetField("Field");
@@ -42,10 +39,8 @@ public static void Main()
FieldInfo myFieldInfo1 = myTypeB.GetField("field",
BindingFlags.NonPublic | BindingFlags.Instance);
- Console.WriteLine("The value of the public field is: '{0}'",
- myFieldInfo.GetValue(myFieldObjectA));
- Console.WriteLine("The value of the private field is: '{0}'",
- myFieldInfo1.GetValue(myFieldObjectB));
+ Console.WriteLine($"The value of the public field is: '{myFieldInfo.GetValue(myFieldObjectA)}'");
+ Console.WriteLine($"The value of the private field is: '{myFieldInfo1.GetValue(myFieldObjectB)}'");
}
}
//
diff --git a/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs b/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs
index 7b01efe830f..577256cc55a 100644
--- a/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs
+++ b/snippets/csharp/System/Type/GetFields/fieldinfo_isspecialname.cs
@@ -16,20 +16,19 @@ public static void Main()
FieldInfo[] myField = myType.GetFields();
Console.WriteLine("\nDisplaying fields that have SpecialName attributes:\n");
- for(int i = 0; i < myField.Length; i++)
+ for (int i = 0; i < myField.Length; i++)
{
// Determine whether or not each field is a special name.
- if(myField[i].IsSpecialName)
+ if (myField[i].IsSpecialName)
{
- Console.WriteLine("The field {0} has a SpecialName attribute.",
- myField[i].Name);
+ Console.WriteLine($"The field {myField[i].Name} has a SpecialName attribute.");
}
}
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("Exception : {0} " , e.Message);
+ Console.WriteLine($"Exception : {e.Message} ");
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetFields/source.cs b/snippets/csharp/System/Type/GetFields/source.cs
index bc3aefc9d1d..b0af8444d62 100644
--- a/snippets/csharp/System/Type/GetFields/source.cs
+++ b/snippets/csharp/System/Type/GetFields/source.cs
@@ -1,18 +1,15 @@
-//
+//
using System;
using System.Reflection;
class AttributesSample
{
- public void Mymethod (int int1m, out string str2m, ref string str3m)
- {
- str2m = "in Mymethod";
- }
+ public void Mymethod(int int1m, out string str2m, ref string str3m) => str2m = "in Mymethod";
public static int Main(string[] args)
{
- Console.WriteLine ("Reflection.MethodBase.Attributes Sample");
+ Console.WriteLine("Reflection.MethodBase.Attributes Sample");
// Get the type.
Type MyType = Type.GetType("AttributesSample");
@@ -27,7 +24,7 @@ public static int Main(string[] args)
MethodAttributes Myattributes = Mymethodbase.Attributes;
// Display the flags that are set.
- PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
+ PrintAttributes(typeof(System.Reflection.MethodAttributes), (int)Myattributes);
return 0;
}
diff --git a/snippets/csharp/System/Type/GetGenericArguments/source.cs b/snippets/csharp/System/Type/GetGenericArguments/source.cs
index aff8b688c19..b129230bb08 100644
--- a/snippets/csharp/System/Type/GetGenericArguments/source.cs
+++ b/snippets/csharp/System/Type/GetGenericArguments/source.cs
@@ -1,19 +1,17 @@
//
using System;
-using System.Reflection;
+
using System.Collections.Generic;
public class Test
{
private static void DisplayGenericTypeInfo(Type t)
{
- Console.WriteLine("\r\n{0}", t);
+ Console.WriteLine($"\r\n{t}");
- Console.WriteLine("\tIs this a generic type definition? {0}",
- t.IsGenericTypeDefinition);
+ Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}");
- Console.WriteLine("\tIs it a generic type? {0}",
- t.IsGenericType);
+ Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}");
//
if (t.IsGenericType)
@@ -22,8 +20,7 @@ private static void DisplayGenericTypeInfo(Type t)
//
Type[] typeArguments = t.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):",
- typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
@@ -32,13 +29,11 @@ private static void DisplayGenericTypeInfo(Type t)
//
if (tParam.IsGenericParameter)
{
- Console.WriteLine("\t\t{0}\t(unassigned - parameter position {1})",
- tParam,
- tParam.GenericParameterPosition);
+ Console.WriteLine($"\t\t{tParam}\t(unassigned - parameter position {tParam.GenericParameterPosition})");
}
else
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
@@ -51,8 +46,8 @@ public static void Main()
Console.WriteLine(" generic type definition, and an ordinary type.");
// Create a Dictionary of Test objects, using strings for the
- // keys.
- Dictionary d = new Dictionary();
+ // keys.
+ Dictionary d = new();
// Display information for the constructed type and its generic
// type definition.
diff --git a/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs b/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs
index cb7b7df42ce..98438f97aba 100644
--- a/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs
+++ b/snippets/csharp/System/Type/GetGenericTypeDefinition/source.cs
@@ -1,6 +1,6 @@
//
using System;
-using System.Reflection;
+
using System.Collections.Generic;
public class Test
@@ -10,8 +10,8 @@ public static void Main()
Console.WriteLine("\r\n--- Get the generic type that defines a constructed type.");
// Create a Dictionary of Test objects, using strings for the
- // keys.
- Dictionary d = new Dictionary();
+ // keys.
+ Dictionary d = new();
// Get a Type object representing the constructed type.
//
@@ -24,16 +24,14 @@ public static void Main()
private static void DisplayTypeInfo(Type t)
{
- Console.WriteLine("\r\n{0}", t);
- Console.WriteLine("\tIs this a generic type definition? {0}",
- t.IsGenericTypeDefinition);
- Console.WriteLine("\tIs it a generic type? {0}",
- t.IsGenericType);
+ Console.WriteLine($"\r\n{t}");
+ Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}");
+ Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}");
Type[] typeArguments = t.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
diff --git a/snippets/csharp/System/Type/GetHashCode/Project.csproj b/snippets/csharp/System/Type/GetHashCode/Project.csproj
new file mode 100644
index 00000000000..1ef5ac9aa71
--- /dev/null
+++ b/snippets/csharp/System/Type/GetHashCode/Project.csproj
@@ -0,0 +1,7 @@
+
+
+ Exe
+ net10.0-windows
+ true
+
+
diff --git a/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs b/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs
index 779f730e297..9dd0048525b 100644
--- a/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs
+++ b/snippets/csharp/System/Type/GetHashCode/type_gethashcode_getfields.cs
@@ -5,37 +5,36 @@
class FieldsSample
{
- public static void Main()
+ public static void Main()
{
Type myType = typeof(System.Net.IPAddress);
- FieldInfo [] myFields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
- Console.WriteLine ("\nThe IPAddress class has the following nonpublic fields: ");
+ FieldInfo[] myFields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
+ Console.WriteLine("\nThe IPAddress class has the following nonpublic fields: ");
foreach (FieldInfo myField in myFields)
{
- Console.WriteLine(myField.ToString());
+ Console.WriteLine(myField);
}
Type myType1 = typeof(System.Net.IPAddress);
- FieldInfo [] myFields1 = myType1.GetFields();
- Console.WriteLine ("\nThe IPAddress class has the following public fields: ");
+ FieldInfo[] myFields1 = myType1.GetFields();
+ Console.WriteLine("\nThe IPAddress class has the following public fields: ");
foreach (FieldInfo myField in myFields1)
{
- Console.WriteLine(myField.ToString());
+ Console.WriteLine(myField);
}
try
{
- Console.WriteLine("The HashCode of the System.Windows.Forms.Button type is: {0}",
- typeof(System.Windows.Forms.Button).GetHashCode());
- }
- catch(SecurityException e)
+ Console.WriteLine($"The HashCode of the System.Windows.Forms.Button type is: {typeof(System.Windows.Forms.Button).GetHashCode()}");
+ }
+ catch (SecurityException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message: "+e.Message);
+ Console.WriteLine("Message: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Message: "+e.Message);
- }
+ Console.WriteLine("Message: " + e.Message);
+ }
}
-}
+}
//
diff --git a/snippets/csharp/System/Type/GetInterface/Project.csproj b/snippets/csharp/System/Type/GetInterface/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetInterface/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetInterface/type_getinterface.cs b/snippets/csharp/System/Type/GetInterface/type_getinterface.cs
index 010de7d835e..72060d5ddd9 100644
--- a/snippets/csharp/System/Type/GetInterface/type_getinterface.cs
+++ b/snippets/csharp/System/Type/GetInterface/type_getinterface.cs
@@ -13,42 +13,42 @@ with the specified name. Then prints the method name of that interface.
class MyInterfaceClass
{
-//
-//
-//
+ //
+ //
+ //
public static void Main()
{
- Hashtable hashtableObj = new Hashtable();
+ Hashtable hashtableObj = new();
Type objType = hashtableObj.GetType();
MethodInfo[] arrayMethodInfo;
MemberInfo[] arrayMemberInfo;
try
{
// Get the methods implemented in 'IDeserializationCallback' interface.
- arrayMethodInfo =objType.GetInterface("IDeserializationCallback").GetMethods();
- Console.WriteLine ("\nMethods of 'IDeserializationCallback' Interface :");
- foreach(MethodInfo methodInfo in arrayMethodInfo)
- Console.WriteLine (methodInfo);
+ arrayMethodInfo = objType.GetInterface("IDeserializationCallback").GetMethods();
+ Console.WriteLine("\nMethods of 'IDeserializationCallback' Interface :");
+ foreach (MethodInfo methodInfo in arrayMethodInfo)
+ Console.WriteLine(methodInfo);
// Get FullName for interface by using Ignore case search.
- Console.WriteLine ("\nMethods of 'IEnumerable' Interface");
- arrayMethodInfo = objType.GetInterface("ienumerable",true).GetMethods();
- foreach(MethodInfo methodInfo in arrayMethodInfo)
- Console.WriteLine (methodInfo);
+ Console.WriteLine("\nMethods of 'IEnumerable' Interface");
+ arrayMethodInfo = objType.GetInterface("ienumerable", true).GetMethods();
+ foreach (MethodInfo methodInfo in arrayMethodInfo)
+ Console.WriteLine(methodInfo);
//Get the Interface methods for 'IDictionary' interface
- InterfaceMapping interfaceMappingOb = objType.GetInterfaceMap(typeof(IDictionary));
+ InterfaceMapping interfaceMappingObj = objType.GetInterfaceMap(typeof(IDictionary));
arrayMemberInfo = interfaceMappingObj.InterfaceMethods;
- Console.WriteLine ("\nHashtable class Implements the following IDictionary Interface methods :");
- foreach(MemberInfo memberInfo in arrayMemberInfo)
- Console.WriteLine (memberInfo);
+ Console.WriteLine("\nHashtable class Implements the following IDictionary Interface methods :");
+ foreach (MemberInfo memberInfo in arrayMemberInfo)
+ Console.WriteLine(memberInfo);
}
catch (Exception e)
{
- Console.WriteLine ("Exception : " + e.ToString());
+ Console.WriteLine("Exception : " + e);
}
}
-//
-//
-//
+ //
+ //
+ //
}
diff --git a/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj b/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetInterfaceMap/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs b/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs
index 1ce9ac58388..aa607622e13 100644
--- a/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs
+++ b/snippets/csharp/System/Type/GetInterfaceMap/interfacemapping1.cs
@@ -5,50 +5,32 @@
public class Example
{
- public static void Main()
- {
- Type[] interf = { typeof(IFormatProvider), typeof(IAppDomainSetup) };
- Type[] impl = { typeof(CultureInfo), typeof(AppDomainSetup) };
+ public static void Main()
+ {
+ Type[] interf = [typeof(IFormatProvider), typeof(IFormattable)];
+ Type[] impl = [typeof(CultureInfo), typeof(DateTime)];
- for (int ctr = 0; ctr < interf.Length; ctr++)
- ShowInterfaceMapping(interf[ctr], impl[ctr]);
- }
+ for (int ctr = 0; ctr < interf.Length; ctr++)
+ ShowInterfaceMapping(interf[ctr], impl[ctr]);
+ }
- private static void ShowInterfaceMapping(Type intType, Type implType)
- {
- InterfaceMapping map = implType.GetInterfaceMap(intType);
- Console.WriteLine("Mapping of {0} to {1}: ", map.InterfaceType, map.TargetType);
- for (int ctr = 0; ctr < map.InterfaceMethods.Length; ctr++) {
- MethodInfo im = map.InterfaceMethods[ctr];
- MethodInfo tm = map.TargetMethods[ctr];
- Console.WriteLine(" {0} --> {1}", im.Name,tm.Name);
- }
- Console.WriteLine();
- }
+ private static void ShowInterfaceMapping(Type intType, Type implType)
+ {
+ InterfaceMapping map = implType.GetInterfaceMap(intType);
+ Console.WriteLine($"Mapping of {map.InterfaceType} to {map.TargetType}: ");
+ for (int ctr = 0; ctr < map.InterfaceMethods.Length; ctr++)
+ {
+ MethodInfo im = map.InterfaceMethods[ctr];
+ MethodInfo tm = map.TargetMethods[ctr];
+ Console.WriteLine($" {im.Name} --> {tm.Name}");
+ }
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// Mapping of System.IFormatProvider to System.Globalization.CultureInfo:
// GetFormat --> GetFormat
//
-// Mapping of System.IAppDomainSetup to System.AppDomainSetup:
-// get_ApplicationBase --> get_ApplicationBase
-// set_ApplicationBase --> set_ApplicationBase
-// get_ApplicationName --> get_ApplicationName
-// set_ApplicationName --> set_ApplicationName
-// get_CachePath --> get_CachePath
-// set_CachePath --> set_CachePath
-// get_ConfigurationFile --> get_ConfigurationFile
-// set_ConfigurationFile --> set_ConfigurationFile
-// get_DynamicBase --> get_DynamicBase
-// set_DynamicBase --> set_DynamicBase
-// get_LicenseFile --> get_LicenseFile
-// set_LicenseFile --> set_LicenseFile
-// get_PrivateBinPath --> get_PrivateBinPath
-// set_PrivateBinPath --> set_PrivateBinPath
-// get_PrivateBinPathProbe --> get_PrivateBinPathProbe
-// set_PrivateBinPathProbe --> set_PrivateBinPathProbe
-// get_ShadowCopyDirectories --> get_ShadowCopyDirectories
-// set_ShadowCopyDirectories --> set_ShadowCopyDirectories
-// get_ShadowCopyFiles --> get_ShadowCopyFiles
-// set_ShadowCopyFiles --> set_ShadowCopyFiles
+// Mapping of System.IFormattable to System.DateTime:
+// ToString --> ToString
//
diff --git a/snippets/csharp/System/Type/GetMember/type_getmember.cs b/snippets/csharp/System/Type/GetMember/type_getmember.cs
index 745de08fe85..e9df7340968 100644
--- a/snippets/csharp/System/Type/GetMember/type_getmember.cs
+++ b/snippets/csharp/System/Type/GetMember/type_getmember.cs
@@ -8,32 +8,32 @@ public class MyMemberSample
{
public static void Main()
{
- MyMemberSample myClass = new MyMemberSample();
+ MyMemberSample myClass = new();
try
{
myClass.GetMemberInfo();
- myClass.GetPublicStaticMemberInfo();
- myClass.GetPublicInstanceMethodMemberInfo();
+ myClass.GetPublicStaticMemberInfo();
+ myClass.GetPublicInstanceMethodMemberInfo();
}
- catch(ArgumentNullException e)
+ catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException occurred.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
- catch(NotSupportedException e)
+ catch (NotSupportedException e)
{
Console.WriteLine("NotSupportedException occurred.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
- catch(SecurityException e)
+ catch (SecurityException e)
{
Console.WriteLine("SecurityException occurred.");
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("Message: " + e.Message);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("Exception occurred.");
Console.WriteLine("Source: " + e.Source);
@@ -43,16 +43,16 @@ public static void Main()
public void GetMemberInfo()
{
- String myString = "GetMember_String";
+ string myString = "GetMember_String";
Type myType = myString.GetType();
// Get the members for myString starting with the letter C.
MemberInfo[] myMembers = myType.GetMember("C*");
- if(myMembers.Length > 0)
+ if (myMembers.Length > 0)
{
- Console.WriteLine("\nThe member(s) starting with the letter C for type {0}:", myType);
- for(int index=0; index < myMembers.Length; index++)
- Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString());
+ Console.WriteLine($"\nThe member(s) starting with the letter C for type {myType}:");
+ for (int index = 0; index < myMembers.Length; index++)
+ Console.WriteLine($"Member {index + 1}: {myMembers[index]}");
}
else
{
@@ -64,16 +64,16 @@ public void GetMemberInfo()
//
public void GetPublicStaticMemberInfo()
{
- String myString = "GetMember_String_BindingFlag";
+ string myString = "GetMember_String_BindingFlag";
Type myType = myString.GetType();
// Get the public static members for the class myString starting with the letter C.
MemberInfo[] myMembers = myType.GetMember("C*",
- BindingFlags.Public |BindingFlags.Static);
- if(myMembers.Length > 0)
+ BindingFlags.Public | BindingFlags.Static);
+ if (myMembers.Length > 0)
{
- Console.WriteLine("\nThe public static member(s) starting with the letter C for type {0}:", myType);
- for(int index=0; index < myMembers.Length; index++)
- Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString());
+ Console.WriteLine($"\nThe public static member(s) starting with the letter C for type {myType}:");
+ for (int index = 0; index < myMembers.Length; index++)
+ Console.WriteLine($"Member {index + 1}: {myMembers[index]}");
}
else
{
@@ -85,16 +85,16 @@ public void GetPublicStaticMemberInfo()
//
public void GetPublicInstanceMethodMemberInfo()
{
- String myString = "GetMember_String_MemberType_BindingFlag";
+ string myString = "GetMember_String_MemberType_BindingFlag";
Type myType = myString.GetType();
// Get the public instance methods for myString starting with the letter C.
MemberInfo[] myMembers = myType.GetMember("C*", MemberTypes.Method,
BindingFlags.Public | BindingFlags.Instance);
- if(myMembers.Length > 0)
+ if (myMembers.Length > 0)
{
- Console.WriteLine("\nThe public instance method(s) starting with the letter C for type {0}:", myType);
- for(int index=0; index < myMembers.Length; index++)
- Console.WriteLine("Member {0}: {1}", index + 1, myMembers[index].ToString());
+ Console.WriteLine($"\nThe public instance method(s) starting with the letter C for type {myType}:");
+ for (int index = 0; index < myMembers.Length; index++)
+ Console.WriteLine($"Member {index + 1}: {myMembers[index]}");
}
else
{
@@ -102,4 +102,4 @@ public void GetPublicInstanceMethodMemberInfo()
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetMembers/Program.cs b/snippets/csharp/System/Type/GetMembers/Program.cs
new file mode 100644
index 00000000000..5407163430d
--- /dev/null
+++ b/snippets/csharp/System/Type/GetMembers/Program.cs
@@ -0,0 +1,2 @@
+Type_GetMembers.Run();
+Type_GetMembers_BindingFlags.Run();
diff --git a/snippets/csharp/System/Type/GetMembers/Project.csproj b/snippets/csharp/System/Type/GetMembers/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetMembers/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs b/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs
index 370d3130ecb..f95358629b9 100644
--- a/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs
+++ b/snippets/csharp/System/Type/GetMembers/type_getmembers1.cs
@@ -11,45 +11,45 @@ of the class 'MyClass' and displays the same to the console.
using System.Security;
//
-class MyClass
+class MembersSampleClass
{
- public int myInt = 0;
- public string myString = null;
-
- public MyClass()
- {
- }
- public void Myfunction()
- {
- }
+ public int myInt = 0;
+ public string myString = null;
+
+ public MembersSampleClass()
+ {
+ }
+ public void Myfunction()
+ {
+ }
}
class Type_GetMembers
{
- public static void Main()
- {
- try
- {
- MyClass myObject = new MyClass();
- MemberInfo[] myMemberInfo;
-
- // Get the type of 'MyClass'.
- Type myType = myObject.GetType();
-
- // Get the information related to all public member's of 'MyClass'.
- myMemberInfo = myType.GetMembers();
-
- Console.WriteLine( "\nThe members of class '{0}' are :\n", myType);
- for (int i =0 ; i < myMemberInfo.Length ; i++)
- {
- // Display name and type of the concerned member.
- Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType);
- }
- }
- catch(SecurityException e)
- {
- Console.WriteLine("Exception : " + e.Message );
- }
- }
+ public static void Run()
+ {
+ try
+ {
+ MembersSampleClass myObject = new();
+ MemberInfo[] myMemberInfo;
+
+ // Get the type of 'MyClass'.
+ Type myType = myObject.GetType();
+
+ // Get the information related to all public member's of 'MyClass'.
+ myMemberInfo = myType.GetMembers();
+
+ Console.WriteLine($"\nThe members of class '{myType}' are :\n");
+ for (int i = 0; i < myMemberInfo.Length; i++)
+ {
+ // Display name and type of the concerned member.
+ Console.WriteLine($"'{myMemberInfo[i].Name}' is a {myMemberInfo[i].MemberType}");
+ }
+ }
+ catch (SecurityException e)
+ {
+ Console.WriteLine("Exception : " + e.Message);
+ }
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs b/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs
index 5c51ce13c01..7f941571765 100644
--- a/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs
+++ b/snippets/csharp/System/Type/GetMembers/type_getmembers2.cs
@@ -13,58 +13,58 @@ the console.
//
-class MyClass
+class MembersBindingFlagsSampleClass
{
- public int myInt = 0;
- public string myString = null;
+ public int myInt = 0;
+ public string myString = null;
- public MyClass()
- {
- }
- public void Myfunction()
- {
- }
+ public MembersBindingFlagsSampleClass()
+ {
+ }
+ public void Myfunction()
+ {
+ }
}
class Type_GetMembers_BindingFlags
{
- public static void Main()
- {
- try
- {
- MyClass MyObject = new MyClass();
- MemberInfo [] myMemberInfo;
+ public static void Run()
+ {
+ try
+ {
+ MembersBindingFlagsSampleClass MyObject = new();
+ MemberInfo[] myMemberInfo;
- // Get the type of the class 'MyClass'.
- Type myType = MyObject.GetType();
+ // Get the type of the class 'MyClass'.
+ Type myType = MyObject.GetType();
- // Get the public instance members of the class 'MyClass'.
- myMemberInfo = myType.GetMembers(BindingFlags.Public|BindingFlags.Instance);
+ // Get the public instance members of the class 'MyClass'.
+ myMemberInfo = myType.GetMembers(BindingFlags.Public | BindingFlags.Instance);
- Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", myType);
- for (int i =0 ; i < myMemberInfo.Length ; i++)
- {
- // Display name and type of the member of 'MyClass'.
- Console.WriteLine( "'{0}' is a {1}", myMemberInfo[i].Name, myMemberInfo[i].MemberType);
- }
- }
- catch (SecurityException e)
- {
- Console.WriteLine("SecurityException : " + e.Message );
- }
+ Console.WriteLine($"\nThe public instance members of class '{myType}' are : \n");
+ for (int i = 0; i < myMemberInfo.Length; i++)
+ {
+ // Display name and type of the member of 'MyClass'.
+ Console.WriteLine($"'{myMemberInfo[i].Name}' is a {myMemberInfo[i].MemberType}");
+ }
+ }
+ catch (SecurityException e)
+ {
+ Console.WriteLine("SecurityException : " + e.Message);
+ }
- //Output:
- //The public instance members of class 'MyClass' are :
+ //Output:
+ //The public instance members of class 'MyClass' are :
- //'Myfunction' is a Method
- //'ToString' is a Method
- //'Equals' is a Method
- //'GetHashCode' is a Method
- //'GetType' is a Method
- //'.ctor' is a Constructor
- //'myInt' is a Field
- //'myString' is a Field
- }
+ //'Myfunction' is a Method
+ //'ToString' is a Method
+ //'Equals' is a Method
+ //'GetHashCode' is a Method
+ //'GetType' is a Method
+ //'.ctor' is a Constructor
+ //'myInt' is a Field
+ //'myString' is a Field
+ }
}
//
diff --git a/snippets/csharp/System/Type/GetMethod/GetMethod1.cs b/snippets/csharp/System/Type/GetMethod/GetMethod1.cs
index f1fea4624d6..2dba736e77e 100644
--- a/snippets/csharp/System/Type/GetMethod/GetMethod1.cs
+++ b/snippets/csharp/System/Type/GetMethod/GetMethod1.cs
@@ -6,53 +6,55 @@
public class Example
{
- public static void Main()
- {
- // Get a Type object that represents a non-generic type.
- GetAddMethod(typeof(ArrayList));
+ public static void Main()
+ {
+ // Get a Type object that represents a non-generic type.
+ GetAddMethod(typeof(ArrayList));
- var list = new List();
- // Get a Type object that represents a constructed generic type.
- Type closed = list.GetType();
- GetAddMethod(closed);
-
- // Get a Type object that represents an open generic type.
- Type open = typeof(List<>);
- GetAddMethod(open);
- }
+ var list = new List();
+ // Get a Type object that represents a constructed generic type.
+ Type closed = list.GetType();
+ GetAddMethod(closed);
- private static void GetAddMethod(Type typ)
- {
- MethodInfo method;
- // Determine if this is a generic type.
- if (typ.IsGenericType) {
- // Is it an open generic type?
- if (typ.ContainsGenericParameters)
- method = typ.GetMethod("Add", typ.GetGenericArguments());
- // Get closed generic type arguments.
- else
- method = typ.GetMethod("Add", typ.GenericTypeArguments);
- }
- // This is not a generic type.
- else {
- method = typ.GetMethod("Add", new Type[] { typeof(Object) } );
- }
+ // Get a Type object that represents an open generic type.
+ Type open = typeof(List<>);
+ GetAddMethod(open);
+ }
- // Test if an Add method was found.
- if (method == null) {
- Console.WriteLine("No Add method found.");
- return;
- }
-
- Type t = method.ReflectedType;
- Console.Write("{0}.{1}.{2}(", t.Namespace, t.Name, method.Name);
- ParameterInfo[] parms = method.GetParameters();
- for (int ctr = 0; ctr < parms.Length; ctr++)
- Console.Write("{0}{1}", parms[ctr].ParameterType.Name,
- ctr < parms.Length - 1 ? ", " : "");
+ private static void GetAddMethod(Type typ)
+ {
+ MethodInfo method;
+ // Determine if this is a generic type.
+ if (typ.IsGenericType)
+ {
+ // Is it an open generic type?
+ if (typ.ContainsGenericParameters)
+ method = typ.GetMethod("Add", typ.GetGenericArguments());
+ // Get closed generic type arguments.
+ else
+ method = typ.GetMethod("Add", typ.GenericTypeArguments);
+ }
+ // This is not a generic type.
+ else
+ {
+ method = typ.GetMethod("Add", [typeof(object)]);
+ }
- Console.WriteLine(")");
- }
+ // Test if an Add method was found.
+ if (method == null)
+ {
+ Console.WriteLine("No Add method found.");
+ return;
+ }
+
+ Type t = method.ReflectedType;
+ Console.Write($"{t.Namespace}.{t.Name}.{method.Name}(");
+ ParameterInfo[] parms = method.GetParameters();
+ for (int ctr = 0; ctr < parms.Length; ctr++)
+ Console.Write($"{parms[ctr].ParameterType.Name}{(ctr < parms.Length - 1 ? ", " : "")}");
+
+ Console.WriteLine(")");
+ }
}
// The example displays the following output:
// System.Collections.ArrayList.Add(Object)
diff --git a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs
index e54e8d6d12a..3c6b0b60463 100644
--- a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs
+++ b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads1.cs
@@ -4,25 +4,13 @@
public class TestClass
{
- public void DisplayValue(String s)
- {
- Console.WriteLine(s);
- }
+ public void DisplayValue(string s) => Console.WriteLine(s);
- public void DisplayValue(String s, params Object[] values)
- {
- Console.WriteLine(s, values);
- }
+ public void DisplayValue(string s, params object[] values) => Console.WriteLine(s, values);
- public static bool Equals(TestClass t1, TestClass t2)
- {
- return Object.ReferenceEquals(t1, t2);
- }
+ public static bool Equals(TestClass t1, TestClass t2) => object.ReferenceEquals(t1, t2);
- public bool Equals(TestClass t)
- {
- return Object.ReferenceEquals(this, t);
- }
+ public bool Equals(TestClass t) => object.ReferenceEquals(this, t);
}
public class Example1
@@ -40,14 +28,14 @@ public static void Main()
RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Static);
}
- private static void RetrieveMethod(Type t, String name, BindingFlags flags)
+ private static void RetrieveMethod(Type t, string name, BindingFlags flags)
{
try
{
MethodInfo m = t.GetMethod(name, flags);
if (m != null)
{
- Console.Write("{0}.{1}(", t.Name, m.Name);
+ Console.Write($"{t.Name}.{m.Name}(");
ParameterInfo[] parms = m.GetParameters();
for (int ctr = 0; ctr < parms.Length; ctr++)
{
@@ -70,7 +58,7 @@ private static void RetrieveMethod(Type t, String name, BindingFlags flags)
{
if (method.Name != name) continue;
- Console.Write(" {0}.{1}(", t.Name, method.Name);
+ Console.Write($" {t.Name}.{method.Name}(");
ParameterInfo[] parms = method.GetParameters();
for (int ctr = 0; ctr < parms.Length; ctr++)
{
@@ -88,12 +76,12 @@ private static void RetrieveMethod(Type t, String name, BindingFlags flags)
// The following duplicate matches were found:
// TestClass.DisplayValue(String)
// TestClass.DisplayValue(String, Object[])
-//
+//
// The following duplicate matches were found:
// TestClass.Equals(TestClass)
// TestClass.Equals(Object)
-//
+//
// TestClass.Equals(TestClass)
-//
+//
// TestClass.Equals(TestClass, TestClass)
//
diff --git a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs
index a20302fe188..76fee533016 100644
--- a/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs
+++ b/snippets/csharp/System/Type/GetMethod/GetMethodWithOverloads2.cs
@@ -4,13 +4,10 @@
public class Person
{
- public String FirstName;
- public String LastName;
+ public string FirstName;
+ public string LastName;
- public override String ToString()
- {
- return (FirstName + " " + LastName).Trim();
- }
+ public override string ToString() => (FirstName + " " + LastName).Trim();
}
public class Example2
@@ -20,25 +17,23 @@ public static void Main()
Type t = typeof(Person);
RetrieveMethod(t, "ToString");
- t = typeof(Int32);
+ t = typeof(int);
RetrieveMethod(t, "ToString");
}
- private static void RetrieveMethod(Type t, String name)
+ private static void RetrieveMethod(Type t, string name)
{
try
{
MethodInfo m = t.GetMethod(name);
if (m != null)
- Console.WriteLine("{0}.{1}: {2} method", m.ReflectedType.Name,
- m.Name, m.IsStatic ? "Static" : "Instance");
+ Console.WriteLine($"{m.ReflectedType.Name}.{m.Name}: {(m.IsStatic ? "Static" : "Instance")} method");
else
- Console.WriteLine("{0}.ToString method not found", t.Name);
+ Console.WriteLine($"{t.Name}.ToString method not found");
}
catch (AmbiguousMatchException)
{
- Console.WriteLine("{0}.{1} has multiple public overloads.",
- t.Name, name);
+ Console.WriteLine($"{t.Name}.{name} has multiple public overloads.");
}
}
}
diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs
index daa6c4a49ff..02904730e99 100644
--- a/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs
+++ b/snippets/csharp/System/Type/GetMethod/type_getmethod1.cs
@@ -14,7 +14,7 @@ static void Main(string[] args)
// Get MethodA()
MethodInfo mInfo = typeof(Program).GetMethod("MethodA");
- Console.WriteLine("Found method: {0}", mInfo);
+ Console.WriteLine($"Found method: {mInfo}");
}
}
//
diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs
index 90bca4d28cb..2b71ad9dbd6 100644
--- a/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs
+++ b/snippets/csharp/System/Type/GetMethod/type_getmethod2.cs
@@ -12,7 +12,7 @@ static void Main(string[] args)
// Get MethodA()
MethodInfo mInfo = typeof(Program).GetMethod("MethodA",
BindingFlags.Public | BindingFlags.Instance);
- Console.WriteLine("Found method: {0}", mInfo);
+ Console.WriteLine($"Found method: {mInfo}");
}
}
//
diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs
index 71abd1f72aa..ff7b8bdf725 100644
--- a/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs
+++ b/snippets/csharp/System/Type/GetMethod/type_getmethod3.cs
@@ -13,59 +13,59 @@ public void MethodA(int[] i) { }
public unsafe void MethodA(int* i) { }
- public void MethodA(ref int r) {}
+ public void MethodA(ref int r) { }
// Method that takes an out parameter:
- public void MethodA(int i, out int o) { o = 100;}
+ public void MethodA(int i, out int o) => o = 100;
- static void Main(string[] args)
- {
- MethodInfo mInfo;
+ static void Main(string[] args)
+ {
+ MethodInfo mInfo;
- // Get MethodA(int i, int j)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- CallingConventions.Any,
- new Type[] { typeof(int), typeof(int) },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int i, int j)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ CallingConventions.Any,
+ [typeof(int), typeof(int)],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int[] i)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- CallingConventions.Any,
- new Type[] { typeof(int[]) },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int[] i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ CallingConventions.Any,
+ [typeof(int[])],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int* i)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- CallingConventions.Any,
- new Type[] { typeof(int).MakePointerType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int* i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ CallingConventions.Any,
+ [typeof(int).MakePointerType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(ref int r)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- CallingConventions.Any,
- new Type[] { typeof(int).MakeByRefType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(ref int r)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ CallingConventions.Any,
+ [typeof(int).MakeByRefType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int i, out int o)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- CallingConventions.Any,
- new Type[] { typeof(int), typeof(int).MakeByRefType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
- }
+ // Get MethodA(int i, out int o)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ CallingConventions.Any,
+ [typeof(int), typeof(int).MakeByRefType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
+ }
}
//
diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs
index 9275c15de43..c22aec78060 100644
--- a/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs
+++ b/snippets/csharp/System/Type/GetMethod/type_getmethod4.cs
@@ -13,39 +13,39 @@ public void MethodA(int[] i) { }
public unsafe void MethodA(int* i) { }
- public void MethodA(ref int r) {}
+ public void MethodA(ref int r) { }
// Method that takes an out parameter:
- public void MethodA(int i, out int o) { o = 100;}
-
- static void Main(string[] args)
- {
- MethodInfo mInfo;
-
- // Get MethodA(int i, int i)
- mInfo = typeof(Program).GetMethod("MethodA",
- new Type[] { typeof(int), typeof(int) });
- Console.WriteLine("Found method: {0}", mInfo);
-
- // Get MethodA(int[] i)
- mInfo = typeof(Program).GetMethod("MethodA",
- new Type[] { typeof(int[]) });
- Console.WriteLine("Found method: {0}", mInfo);
-
- // Get MethodA(int* i)
- mInfo = typeof(Program).GetMethod("MethodA",
- new Type[] { typeof(int).MakePointerType() });
- Console.WriteLine("Found method: {0}", mInfo);
-
- // Get MethodA(ref int r)
- mInfo = typeof(Program).GetMethod("MethodA",
- new Type[] { typeof(int).MakeByRefType() });
- Console.WriteLine("Found method: {0}", mInfo);
-
- // Get MethodA(int i, out int o)
- mInfo = typeof(Program).GetMethod("MethodA",
- new Type[] { typeof(int), typeof(int).MakeByRefType() });
- Console.WriteLine("Found method: {0}", mInfo);
- }
+ public void MethodA(int i, out int o) => o = 100;
+
+ static void Main(string[] args)
+ {
+ MethodInfo mInfo;
+
+ // Get MethodA(int i, int i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ [typeof(int), typeof(int)]);
+ Console.WriteLine($"Found method: {mInfo}");
+
+ // Get MethodA(int[] i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ [typeof(int[])]);
+ Console.WriteLine($"Found method: {mInfo}");
+
+ // Get MethodA(int* i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ [typeof(int).MakePointerType()]);
+ Console.WriteLine($"Found method: {mInfo}");
+
+ // Get MethodA(ref int r)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ [typeof(int).MakeByRefType()]);
+ Console.WriteLine($"Found method: {mInfo}");
+
+ // Get MethodA(int i, out int o)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ [typeof(int), typeof(int).MakeByRefType()]);
+ Console.WriteLine($"Found method: {mInfo}");
+ }
}
//
diff --git a/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs b/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs
index bdd2e23efcb..b130195db1e 100644
--- a/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs
+++ b/snippets/csharp/System/Type/GetMethod/type_getmethod5.cs
@@ -13,54 +13,54 @@ public void MethodA(int[] i) { }
public unsafe void MethodA(int* i) { }
- public void MethodA(ref int r) {}
+ public void MethodA(ref int r) { }
// Method that takes an out parameter.
- public void MethodA(int i, out int o) { o = 100; }
+ public void MethodA(int i, out int o) => o = 100;
- static void Main(string[] args)
- {
- MethodInfo mInfo;
+ static void Main(string[] args)
+ {
+ MethodInfo mInfo;
- // Get MethodA(int i, int j)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new Type[] { typeof(int), typeof(int) },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int i, int j)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ [typeof(int), typeof(int)],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int[] i)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new Type[] { typeof(int[]) },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int[] i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ [typeof(int[])],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int* i)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new Type[] { typeof(int).MakePointerType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(int* i)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ [typeof(int).MakePointerType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(ref int r)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new Type[] { typeof(int).MakeByRefType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
+ // Get MethodA(ref int r)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ [typeof(int).MakeByRefType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
- // Get MethodA(int i, out int o)
- mInfo = typeof(Program).GetMethod("MethodA",
- BindingFlags.Public | BindingFlags.Instance,
- null,
- new Type[] { typeof(int), typeof(int).MakeByRefType() },
- null);
- Console.WriteLine("Found method: {0}", mInfo);
- }
+ // Get MethodA(int i, out int o)
+ mInfo = typeof(Program).GetMethod("MethodA",
+ BindingFlags.Public | BindingFlags.Instance,
+ null,
+ [typeof(int), typeof(int).MakeByRefType()],
+ null);
+ Console.WriteLine($"Found method: {mInfo}");
+ }
}
//
diff --git a/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs b/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs
index f50aed0e5f4..952b4f26bfc 100644
--- a/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs
+++ b/snippets/csharp/System/Type/GetMethods/type_getmethods2.cs
@@ -1,7 +1,7 @@
//
using System;
using System.Reflection;
-using System.Reflection.Emit;
+
// Create a class having two public methods and one protected method.
public class MyTypeClass
@@ -9,38 +9,32 @@ public class MyTypeClass
public void MyMethods()
{
}
- public int MyMethods1()
- {
- return 3;
- }
- protected String MyMethods2()
- {
- return "hello";
- }
+ public int MyMethods1() => 3;
+ protected string MyMethods2() => "hello";
}
public class TypeMain
{
public static void Main()
{
- Type myType =(typeof(MyTypeClass));
+ Type myType = (typeof(MyTypeClass));
// Get the public methods.
- MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly);
- Console.WriteLine("\nThe number of public methods is {0}.", myArrayMethodInfo.Length);
+ MethodInfo[] myArrayMethodInfo = myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
+ Console.WriteLine($"\nThe number of public methods is {myArrayMethodInfo.Length}.");
// Display all the methods.
DisplayMethodInfo(myArrayMethodInfo);
// Get the nonpublic methods.
- MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly);
- Console.WriteLine("\nThe number of protected methods is {0}.", myArrayMethodInfo1.Length);
+ MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
+ Console.WriteLine($"\nThe number of protected methods is {myArrayMethodInfo1.Length}.");
// Display information for all methods.
- DisplayMethodInfo(myArrayMethodInfo1);
+ DisplayMethodInfo(myArrayMethodInfo1);
}
public static void DisplayMethodInfo(MethodInfo[] myArrayMethodInfo)
{
// Display information for all methods.
- for(int i=0;i
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs b/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs
index 0815b133ce2..dc0981e5a4d 100644
--- a/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs
+++ b/snippets/csharp/System/Type/GetNestedTypes/type_getnestedtypes.cs
@@ -1,15 +1,15 @@
//
using System;
-using System.Reflection;
+
public class MyClass
{
public class NestClass
{
- public static int myPublicInt=0;
+ public static int myPublicInt = 0;
}
public struct NestStruct
{
- public static int myPublicInt=0;
+ public static int myPublicInt = 0;
}
}
@@ -20,16 +20,16 @@ public static void Main()
try
{
// Get the Type object corresponding to MyClass.
- Type myType=typeof(MyClass);
+ Type myType = typeof(MyClass);
// Get an array of nested type objects in MyClass.
- Type[] nestType=myType.GetNestedTypes();
- Console.WriteLine("The number of nested types is {0}.", nestType.Length);
- foreach(Type t in nestType)
- Console.WriteLine("Nested type is {0}.", t.ToString());
+ Type[] nestType = myType.GetNestedTypes();
+ Console.WriteLine($"The number of nested types is {nestType.Length}.");
+ foreach (Type t in nestType)
+ Console.WriteLine($"Nested type is {t}.");
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("Error"+e.Message);
+ Console.WriteLine("Error" + e.Message);
}
}
}
diff --git a/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs b/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs
index 0ccfc43b7ee..0296cbaba17 100644
--- a/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs
+++ b/snippets/csharp/System/Type/GetProperties/type_getproperties2.cs
@@ -5,35 +5,17 @@
// Create a class having six properties.
public class PropertyClass
{
- public String Property1
- {
- get { return "hello"; }
- }
+ public string Property1 => "hello";
- public String Property2
- {
- get { return "hello"; }
- }
+ public string Property2 => "hello";
- protected String Property3
- {
- get { return "hello"; }
- }
+ protected string Property3 => "hello";
- private Int32 Property4
- {
- get { return 32; }
- }
+ private int Property4 => 32;
- internal String Property5
- {
- get { return "value"; }
- }
+ internal string Property5 => "value";
- protected internal String Property6
- {
- get { return "value"; }
- }
+ protected internal string Property6 => "value";
}
public class Example
@@ -42,16 +24,14 @@ public static void Main()
{
Type t = typeof(PropertyClass);
// Get the public properties.
- PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public|BindingFlags.Instance);
- Console.WriteLine("The number of public properties: {0}.\n",
- propInfos.Length);
+ PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
+ Console.WriteLine($"The number of public properties: {propInfos.Length}.\n");
// Display the public properties.
DisplayPropertyInfo(propInfos);
// Get the nonpublic properties.
- PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
- Console.WriteLine("The number of non-public properties: {0}.\n",
- propInfos1.Length);
+ PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
+ Console.WriteLine($"The number of non-public properties: {propInfos1.Length}.\n");
// Display all the nonpublic properties.
DisplayPropertyInfo(propInfos1);
}
@@ -59,39 +39,40 @@ public static void Main()
public static void DisplayPropertyInfo(PropertyInfo[] propInfos)
{
// Display information for all properties.
- foreach (var propInfo in propInfos) {
+ foreach (var propInfo in propInfos)
+ {
bool readable = propInfo.CanRead;
bool writable = propInfo.CanWrite;
- Console.WriteLine(" Property name: {0}", propInfo.Name);
- Console.WriteLine(" Property type: {0}", propInfo.PropertyType);
- Console.WriteLine(" Read-Write: {0}", readable & writable);
- if (readable) {
- MethodInfo getAccessor = propInfo.GetMethod;
- Console.WriteLine(" Visibility: {0}",
- GetVisibility(getAccessor));
+ Console.WriteLine($" Property name: {propInfo.Name}");
+ Console.WriteLine($" Property type: {propInfo.PropertyType}");
+ Console.WriteLine($" Read-Write: {readable & writable}");
+ if (readable)
+ {
+ MethodInfo getAccessor = propInfo.GetMethod;
+ Console.WriteLine($" Visibility: {GetVisibility(getAccessor)}");
}
- if (writable) {
- MethodInfo setAccessor = propInfo.SetMethod;
- Console.WriteLine(" Visibility: {0}",
- GetVisibility(setAccessor));
+ if (writable)
+ {
+ MethodInfo setAccessor = propInfo.SetMethod;
+ Console.WriteLine($" Visibility: {GetVisibility(setAccessor)}");
}
Console.WriteLine();
}
}
- public static String GetVisibility(MethodInfo accessor)
+ public static string GetVisibility(MethodInfo accessor)
{
- if (accessor.IsPublic)
- return "Public";
- else if (accessor.IsPrivate)
- return "Private";
- else if (accessor.IsFamily)
- return "Protected";
- else if (accessor.IsAssembly)
- return "Internal/Friend";
- else
- return "Protected Internal/Friend";
+ if (accessor.IsPublic)
+ return "Public";
+ else if (accessor.IsPrivate)
+ return "Private";
+ else if (accessor.IsFamily)
+ return "Protected";
+ else if (accessor.IsAssembly)
+ return "Internal/Friend";
+ else
+ return "Protected Internal/Friend";
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs b/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs
index ea1d3e67d35..be9dba71888 100644
--- a/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs
+++ b/snippets/csharp/System/Type/GetProperties/type_gettypecode.cs
@@ -20,49 +20,49 @@ class MyClass
{
static void Main(string[] args)
{
-//
+ //
// Create an object of 'Type' class.
Type myType1 = Type.GetType("System.Int32");
// Get the 'TypeCode' of the 'Type' class object created above.
TypeCode myTypeCode = Type.GetTypeCode(myType1);
- Console.WriteLine("TypeCode is: {0}",myTypeCode);
-//
-//
+ Console.WriteLine($"TypeCode is: {myTypeCode}");
+ //
+ //
PropertyInfo[] myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = Type.GetType("System.Type").GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
- Console.WriteLine(myPropertyInfo[i].ToString());
+ Console.WriteLine(myPropertyInfo[i]);
}
-//
-//
- Object[] myObject = new Object[3];
+ //
+ //
+ object[] myObject = new object[3];
myObject[0] = 66;
myObject[1] = "puri";
myObject[2] = 33.33;
// Get the array of 'Type' class objects.
Type[] myTypeArray = Type.GetTypeArray(myObject);
Console.WriteLine("Full names of the 'Type' objects in the array are:");
- for(int h = 0; h < myTypeArray.Length ; h++)
+ for (int h = 0; h < myTypeArray.Length; h++)
{
Console.WriteLine(myTypeArray[h].FullName);
}
-//
-//
+ //
+ //
try
{
// Throws 'TypeLoadException' because of case-sensitive search.
- Type myType2 = Type.GetType("sYSTem.iNT32",true,false);
+ Type myType2 = Type.GetType("sYSTem.iNT32", true, false);
Console.WriteLine(myType2.FullName);
}
- catch(TypeLoadException e)
+ catch (TypeLoadException e)
{
Console.WriteLine(e.Message);
}
-//
- catch(Exception e)
+ //
+ catch (Exception e)
{
Console.WriteLine(e.Message);
}
diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs
index c1d1196f3c8..60794e62ad2 100644
--- a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs
+++ b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs
@@ -21,7 +21,7 @@ public static void Main(string[] args)
PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
// Display the property name.
- Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.Name);
+ Console.WriteLine($"The {myPropInfo.Name} property exists in MyClass1.");
}
catch (NullReferenceException e)
{
diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs
index 6d5fdbebbba..f543aa0017b 100644
--- a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs
+++ b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs
@@ -25,7 +25,7 @@ public static void Main(string[] args)
);
// Display Name property to console.
- Console.WriteLine("{0} is a property of MyClass2.", myPropInfo.Name);
+ Console.WriteLine($"{myPropInfo.Name} is a property of MyClass2.");
}
catch (NullReferenceException e)
{
diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs
index 5f7ee5d3e84..4279b28123f 100644
--- a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs
+++ b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs
@@ -4,18 +4,12 @@
public class MyPropertyClass
{
- private readonly int [,] _myPropertyArray = new int[10,10];
+ private readonly int[,] _myPropertyArray = new int[10, 10];
// Declare an indexer.
- public int this [int i,int j]
+ public int this[int i, int j]
{
- get
- {
- return _myPropertyArray[i,j];
- }
- set
- {
- _myPropertyArray[i,j] = value;
- }
+ get => _myPropertyArray[i, j];
+ set => _myPropertyArray[i, j] = value;
}
}
@@ -25,22 +19,22 @@ public static void Main()
{
try
{
- Type myType=typeof(MyPropertyClass);
+ Type myType = typeof(MyPropertyClass);
Type[] myTypeArray = new Type[2];
// Create an instance of the Type array representing the number, order
// and type of the parameters for the property.
- myTypeArray.SetValue(typeof(int),0);
- myTypeArray.SetValue(typeof(int),1);
+ myTypeArray.SetValue(typeof(int), 0);
+ myTypeArray.SetValue(typeof(int), 1);
// Search for the indexed property whose parameters match the
// specified argument types and modifiers.
PropertyInfo myPropertyInfo = myType.GetProperty("Item",
- typeof(int),myTypeArray,null);
+ typeof(int), myTypeArray, null);
Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name +
" has a property type of " + myPropertyInfo.PropertyType);
- }
- catch(Exception ex)
+ }
+ catch (Exception ex)
{
Console.WriteLine("An exception occurred " + ex.Message);
}
diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs
index b30e4da0e67..c29675280b8 100644
--- a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs
+++ b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs
@@ -9,14 +9,8 @@ class MyClass3
// Declare an indexer.
public int this[int i, int j]
{
- get
- {
- return _myArray[i, j];
- }
- set
- {
- _myArray[i, j] = value;
- }
+ get => _myArray[i, j];
+ set => _myArray[i, j] = value;
}
}
@@ -38,14 +32,13 @@ public static void Main(string[] args)
PropertyInfo myPropInfo = myType.GetProperty("Item", myTypeArr);
// Display the property.
- Console.WriteLine("The {0} property exists in MyClass3.",
- myPropInfo.ToString());
+ Console.WriteLine($"The {myPropInfo} property exists in MyClass3.");
}
catch (NullReferenceException e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Source : {0}", e.Source);
- Console.WriteLine("Message : {0}", e.Message);
+ Console.WriteLine($"Source : {e.Source}");
+ Console.WriteLine($"Message : {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs
index 5bd74bc952a..2a7433a34e7 100644
--- a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs
+++ b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs
@@ -19,10 +19,8 @@ static void Main()
// Get the PropertyInfo object representing MyProperty1.
PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1", typeof(string));
- Console.WriteLine("The name of the first property of MyPropertyTypeClass is {0}.",
- myStringProperties1.Name);
- Console.WriteLine("The type of the first property of MyPropertyTypeClass is {0}.",
- myStringProperties1.PropertyType);
+ Console.WriteLine($"The name of the first property of MyPropertyTypeClass is {myStringProperties1.Name}.");
+ Console.WriteLine($"The type of the first property of MyPropertyTypeClass is {myStringProperties1.PropertyType}.");
}
catch (ArgumentNullException e)
{
@@ -34,12 +32,12 @@ static void Main()
}
catch (NullReferenceException e)
{
- Console.WriteLine("Source : {0}", e.Source);
- Console.WriteLine("Message : {0}", e.Message);
+ Console.WriteLine($"Source : {e.Source}");
+ Console.WriteLine($"Message : {e.Message}");
}
//Output:
//The name of the first property of MyPropertyTypeClass is MyProperty1.
//The type of the first property of MyPropertyTypeClass is System.String.
}
}
-//
+//
diff --git a/snippets/csharp/System/Type/GetType/Project.csproj b/snippets/csharp/System/Type/GetType/Project.csproj
index 874c98f3477..1eddf5e00ac 100644
--- a/snippets/csharp/System/Type/GetType/Project.csproj
+++ b/snippets/csharp/System/Type/GetType/Project.csproj
@@ -1,8 +1,6 @@
-
Library
net10.0
-
-
+
diff --git a/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs b/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs
index 7141baf6e99..83b7a06f4be 100644
--- a/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs
+++ b/snippets/csharp/System/Type/GetType/mypath/v5.0/myassembly.cs
@@ -1,6 +1,6 @@
-using System;
+
namespace MyNamespace
{
- public class MyType {}
+ public class MyType { }
}
diff --git a/snippets/csharp/System/Type/GetType/source.cs b/snippets/csharp/System/Type/GetType/source.cs
index cdf553928e0..29486be664c 100644
--- a/snippets/csharp/System/Type/GetType/source.cs
+++ b/snippets/csharp/System/Type/GetType/source.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Reflection;
class Example
diff --git a/snippets/csharp/System/Type/GetType/type_gettype.cs b/snippets/csharp/System/Type/GetType/type_gettype.cs
index c0345bf6a7a..77611966ab3 100644
--- a/snippets/csharp/System/Type/GetType/type_gettype.cs
+++ b/snippets/csharp/System/Type/GetType/type_gettype.cs
@@ -3,27 +3,30 @@
class GetTypeExample
{
- public static void Main()
- {
- try {
- // Get the type of a specified class.
- Type myType1 = Type.GetType("System.Int32");
- Console.WriteLine("The full name is {0}.\n", myType1.FullName);
- }
- catch (TypeLoadException e)
- {
- Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name);
- }
+ public static void Main()
+ {
+ try
+ {
+ // Get the type of a specified class.
+ Type myType1 = Type.GetType("System.Int32");
+ Console.WriteLine($"The full name is {myType1.FullName}.\n");
+ }
+ catch (TypeLoadException e)
+ {
+ Console.WriteLine($"{e.GetType().Name}: Unable to load type System.Int32");
+ }
- try {
- // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
- Type myType2 = Type.GetType("NoneSuch", true);
- Console.WriteLine("The full name is {0}.", myType2.FullName);
- }
- catch(TypeLoadException e) {
- Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name);
- }
- }
+ try
+ {
+ // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
+ Type myType2 = Type.GetType("NoneSuch", true);
+ Console.WriteLine($"The full name is {myType2.FullName}.");
+ }
+ catch (TypeLoadException e)
+ {
+ Console.WriteLine($"{e.GetType().Name}: Unable to load type NoneSuch");
+ }
+ }
}
// The example displays the following output:
// The full name is System.Int32.
diff --git a/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs b/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs
index 66c93790914..c9396ce0e7b 100644
--- a/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs
+++ b/snippets/csharp/System/Type/GetTypeCode/iconvertible.cs
@@ -7,8 +7,8 @@ namespace ConsoleApplication2
/// Class that implements IConvertible
class Complex : IConvertible
{
- double x;
- double y;
+ double x;
+ double y;
public Complex(double x, double y)
{
@@ -16,98 +16,47 @@ public Complex(double x, double y)
this.y = y;
}
- public TypeCode GetTypeCode()
- {
- return TypeCode.Object;
- }
+ public TypeCode GetTypeCode() => TypeCode.Object;
bool IConvertible.ToBoolean(IFormatProvider provider)
{
- if( (x != 0.0) || (y != 0.0) )
+ if ((x != 0.0) || (y != 0.0))
return true;
else
return false;
}
- double GetDoubleValue()
- {
- return Math.Sqrt(x*x + y*y);
- }
+ double GetDoubleValue() => Math.Sqrt(x * x + y * y);
- byte IConvertible.ToByte(IFormatProvider provider)
- {
- return Convert.ToByte(GetDoubleValue());
- }
+ byte IConvertible.ToByte(IFormatProvider provider) => Convert.ToByte(GetDoubleValue());
- char IConvertible.ToChar(IFormatProvider provider)
- {
- return Convert.ToChar(GetDoubleValue());
- }
+ char IConvertible.ToChar(IFormatProvider provider) => Convert.ToChar(GetDoubleValue());
- DateTime IConvertible.ToDateTime(IFormatProvider provider)
- {
- return Convert.ToDateTime(GetDoubleValue());
- }
+ DateTime IConvertible.ToDateTime(IFormatProvider provider) => Convert.ToDateTime(GetDoubleValue());
- decimal IConvertible.ToDecimal(IFormatProvider provider)
- {
- return Convert.ToDecimal(GetDoubleValue());
- }
+ decimal IConvertible.ToDecimal(IFormatProvider provider) => Convert.ToDecimal(GetDoubleValue());
- double IConvertible.ToDouble(IFormatProvider provider)
- {
- return GetDoubleValue();
- }
+ double IConvertible.ToDouble(IFormatProvider provider) => GetDoubleValue();
- short IConvertible.ToInt16(IFormatProvider provider)
- {
- return Convert.ToInt16(GetDoubleValue());
- }
+ short IConvertible.ToInt16(IFormatProvider provider) => Convert.ToInt16(GetDoubleValue());
- int IConvertible.ToInt32(IFormatProvider provider)
- {
- return Convert.ToInt32(GetDoubleValue());
- }
+ int IConvertible.ToInt32(IFormatProvider provider) => Convert.ToInt32(GetDoubleValue());
- long IConvertible.ToInt64(IFormatProvider provider)
- {
- return Convert.ToInt64(GetDoubleValue());
- }
+ long IConvertible.ToInt64(IFormatProvider provider) => Convert.ToInt64(GetDoubleValue());
- sbyte IConvertible.ToSByte(IFormatProvider provider)
- {
- return Convert.ToSByte(GetDoubleValue());
- }
+ sbyte IConvertible.ToSByte(IFormatProvider provider) => Convert.ToSByte(GetDoubleValue());
- float IConvertible.ToSingle(IFormatProvider provider)
- {
- return Convert.ToSingle(GetDoubleValue());
- }
+ float IConvertible.ToSingle(IFormatProvider provider) => Convert.ToSingle(GetDoubleValue());
- string IConvertible.ToString(IFormatProvider provider)
- {
- return "( " + x.ToString() + " , " + y.ToString() + " )";
- }
+ string IConvertible.ToString(IFormatProvider provider) => "( " + x + " , " + y + " )";
- object IConvertible.ToType(Type conversionType, IFormatProvider provider)
- {
- return Convert.ChangeType(GetDoubleValue(),conversionType);
- }
+ object IConvertible.ToType(Type conversionType, IFormatProvider provider) => Convert.ChangeType(GetDoubleValue(), conversionType);
- ushort IConvertible.ToUInt16(IFormatProvider provider)
- {
- return Convert.ToUInt16(GetDoubleValue());
- }
+ ushort IConvertible.ToUInt16(IFormatProvider provider) => Convert.ToUInt16(GetDoubleValue());
- uint IConvertible.ToUInt32(IFormatProvider provider)
- {
- return Convert.ToUInt32(GetDoubleValue());
- }
+ uint IConvertible.ToUInt32(IFormatProvider provider) => Convert.ToUInt32(GetDoubleValue());
- ulong IConvertible.ToUInt64(IFormatProvider provider)
- {
- return Convert.ToUInt64(GetDoubleValue());
- }
+ ulong IConvertible.ToUInt64(IFormatProvider provider) => Convert.ToUInt64(GetDoubleValue());
}
///
@@ -118,34 +67,34 @@ class Class1
static void Main(string[] args)
{
- Complex testComplex = new Complex(4,7);
+ Complex testComplex = new(4, 7);
WriteObjectInfo(testComplex);
WriteObjectInfo(Convert.ToBoolean(testComplex));
WriteObjectInfo(Convert.ToDecimal(testComplex));
WriteObjectInfo(Convert.ToString(testComplex));
}
-//
+ //
static void WriteObjectInfo(object testObject)
{
- TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
+ TypeCode typeCode = Type.GetTypeCode(testObject.GetType());
- switch( typeCode )
+ switch (typeCode)
{
case TypeCode.Boolean:
- Console.WriteLine("Boolean: {0}", testObject);
+ Console.WriteLine($"Boolean: {testObject}");
break;
case TypeCode.Double:
- Console.WriteLine("Double: {0}", testObject);
+ Console.WriteLine($"Double: {testObject}");
break;
default:
- Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
+ Console.WriteLine($"{typeCode}: {testObject}");
break;
}
}
-//
+ //
}
}
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs
new file mode 100644
index 00000000000..e5bc219e3f2
--- /dev/null
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/Program.cs
@@ -0,0 +1,5 @@
+GetTypeFromClsidExample1.Run();
+GetTypeFromClsidExample11.Run();
+GetTypeFromClsidExample2.Run();
+GetTypeFromClsidExample3.Run();
+GetTypeFromClsidExample4.Run();
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj b/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs
index ef6f4b99acd..af508f946cc 100644
--- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid1.cs
@@ -1,26 +1,25 @@
//
using System;
using System.Reflection;
-using System.Runtime.InteropServices;
-public class Example
+
+public class GetTypeFromClsidExample1
{
- private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
-
- public static void Main()
- {
- // Start an instance of the Word application.
- var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID));
- Console.WriteLine("Instantiated Type object from CLSID {0}",
- WORD_CLSID);
- Object wordObj = Activator.CreateInstance(word);
- Console.WriteLine("Instantiated {0}",
- wordObj.GetType().FullName);
-
- // Close Word.
- word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
- wordObj, new object[] { 0, 0, false } );
- }
+ private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
+
+ public static void Run()
+ {
+ // Start an instance of the Word application.
+ var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID));
+ Console.WriteLine("Instantiated Type object from CLSID {0}",
+ WORD_CLSID);
+ object wordObj = Activator.CreateInstance(word);
+ Console.WriteLine($"Instantiated {wordObj.GetType().FullName}");
+
+ // Close Word.
+ word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
+ wordObj, [0, 0, false]);
+ }
}
// The example displays the following output:
// Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs
index f6b20ed2b01..cd4851d6a74 100644
--- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid11.cs
@@ -2,7 +2,7 @@
using System;
using System.Runtime.InteropServices;
-[assembly:ComVisible(true)]
+[assembly: ComVisible(true)]
// Define two classes, and assign one an explicit GUID.
[GuidAttribute("d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4")]
@@ -12,69 +12,67 @@ public class ExplicitGuid
public class NoExplicitGuid
{ }
-public class Example
+public class GetTypeFromClsidExample11
{
- public static void Main()
- {
- Type explicitType = typeof(ExplicitGuid);
- Guid explicitGuid = explicitType.GUID;
-
- // Get type of ExplicitGuid from its GUID.
- Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
- Console.WriteLine("Created {0} type from CLSID {1}",
- explicitCOM.Name, explicitGuid);
-
- // Compare the two type objects.
- Console.WriteLine("{0} and {1} equal: {2}",
- explicitType.Name, explicitCOM.Name,
- explicitType.Equals(explicitCOM));
-
- // Instantiate an ExplicitGuid object.
- try {
- Object obj = Activator.CreateInstance(explicitCOM);
- Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
- }
- catch (COMException e) {
- Console.WriteLine("COM Exception:\n{0}\n", e.Message);
- }
-
- Type notExplicit = typeof(NoExplicitGuid);
- Guid notExplicitGuid = notExplicit.GUID;
-
- // Get type of ExplicitGuid from its GUID.
- Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
- Console.WriteLine("Created {0} type from CLSID {1}",
- notExplicitCOM.Name, notExplicitGuid);
-
- // Compare the two type objects.
- Console.WriteLine("{0} and {1} equal: {2}",
- notExplicit.Name, notExplicitCOM.Name,
- notExplicit.Equals(notExplicitCOM));
-
- // Instantiate an ExplicitGuid object.
- try {
- Object obj = Activator.CreateInstance(notExplicitCOM);
- Console.WriteLine("Instantiated a {0} object", obj.GetType().Name);
- }
- catch (COMException e) {
- Console.WriteLine("COM Exception:\n{0}\n", e.Message);
- }
- }
+ public static void Run()
+ {
+ Type explicitType = typeof(ExplicitGuid);
+ Guid explicitGuid = explicitType.GUID;
+
+ // Get type of ExplicitGuid from its GUID.
+ Type explicitCOM = Type.GetTypeFromCLSID(explicitGuid);
+ Console.WriteLine($"Created {explicitCOM.Name} type from CLSID {explicitGuid}");
+
+ // Compare the two type objects.
+ Console.WriteLine($"{explicitType.Name} and {explicitCOM.Name} equal: {explicitType.Equals(explicitCOM)}");
+
+ // Instantiate an ExplicitGuid object.
+ try
+ {
+ object obj = Activator.CreateInstance(explicitCOM);
+ Console.WriteLine($"Instantiated a {obj.GetType().Name} object");
+ }
+ catch (COMException e)
+ {
+ Console.WriteLine($"COM Exception:\n{e.Message}\n");
+ }
+
+ Type notExplicit = typeof(NoExplicitGuid);
+ Guid notExplicitGuid = notExplicit.GUID;
+
+ // Get type of ExplicitGuid from its GUID.
+ Type notExplicitCOM = Type.GetTypeFromCLSID(notExplicitGuid);
+ Console.WriteLine($"Created {notExplicitCOM.Name} type from CLSID {notExplicitGuid}");
+
+ // Compare the two type objects.
+ Console.WriteLine($"{notExplicit.Name} and {notExplicitCOM.Name} equal: {notExplicit.Equals(notExplicitCOM)}");
+
+ // Instantiate an ExplicitGuid object.
+ try
+ {
+ object obj = Activator.CreateInstance(notExplicitCOM);
+ Console.WriteLine($"Instantiated a {obj.GetType().Name} object");
+ }
+ catch (COMException e)
+ {
+ Console.WriteLine($"COM Exception:\n{e.Message}\n");
+ }
+ }
}
// The example displays the following output:
// Created __ComObject type from CLSID d055cba3-1f83-4bd7-ba19-e22b1b8ec3c4
// ExplicitGuid and __ComObject equal: False
// COM Exception:
-// Retrieving the COM class factory for component with CLSID
-// {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error:
-// 80040154 Class not registered
+// Retrieving the COM class factory for component with CLSID
+// {D055CBA3-1F83-4BD7-BA19-E22B1B8EC3C4} failed due to the following error:
+// 80040154 Class not registered
// (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
-//
+//
// Created __ComObject type from CLSID 74f03346-a718-3516-ac78-f351c7459ffb
// NoExplicitGuid and __ComObject equal: False
// COM Exception:
-// Retrieving the COM class factory for component with CLSID
-// {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error:
-// 80040154 Class not registered
+// Retrieving the COM class factory for component with CLSID
+// {74F03346-A718-3516-AC78-F351C7459FFB} failed due to the following error:
+// 80040154 Class not registered
// (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
//
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs
index 721c6fbd9a9..a1f9728aad0 100644
--- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex2.cs
@@ -1,31 +1,33 @@
//
using System;
using System.Reflection;
-using System.Runtime.InteropServices;
-public class Example
+
+public class GetTypeFromClsidExample2
{
- private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
-
- public static void Main()
- {
- try {
- // Start an instance of the Word application.
- var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), true);
- Console.WriteLine("Instantiated Type object from CLSID {0}",
- WORD_CLSID);
- Object wordObj = Activator.CreateInstance(word);
- Console.WriteLine("Instantiated {0}",
- wordObj.GetType().FullName, WORD_CLSID);
-
- // Close Word.
- word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
- wordObj, new object[] { 0, 0, false } );
- }
- catch (Exception) {
- Console.WriteLine("Unable to instantiate an object for {0}", WORD_CLSID);
- }
- }
+ private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
+
+ public static void Run()
+ {
+ try
+ {
+ // Start an instance of the Word application.
+ var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), true);
+ Console.WriteLine("Instantiated Type object from CLSID {0}",
+ WORD_CLSID);
+ object wordObj = Activator.CreateInstance(word);
+ Console.WriteLine("Instantiated {0}",
+ wordObj.GetType().FullName, WORD_CLSID);
+
+ // Close Word.
+ word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
+ wordObj, [0, 0, false]);
+ }
+ catch (Exception)
+ {
+ Console.WriteLine("Unable to instantiate an object for {0}", WORD_CLSID);
+ }
+ }
}
// The example displays the following output:
// Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs
index 1f82da2f08e..f5f2672cb1d 100644
--- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex3.cs
@@ -3,29 +3,31 @@
using System.Reflection;
using System.Runtime.InteropServices;
-public class Example
+public class GetTypeFromClsidExample3
{
- private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
-
- public static void Main()
- {
- // Start an instance of the Word application.
- var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), "computer17.central.contoso.com");
- Console.WriteLine("Instantiated Type object from CLSID {0}",
- WORD_CLSID);
- try {
- Object wordObj = Activator.CreateInstance(word);
- Console.WriteLine("Instantiated {0}",
- wordObj.GetType().FullName, WORD_CLSID);
-
- // Close Word.
- word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
- wordObj, new object[] { 0, 0, false } );
- }
- catch (COMException) {
- Console.WriteLine("Unable to instantiate object.");
- }
- }
+ private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
+
+ public static void Run()
+ {
+ // Start an instance of the Word application.
+ var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID), "computer17.central.contoso.com");
+ Console.WriteLine("Instantiated Type object from CLSID {0}",
+ WORD_CLSID);
+ try
+ {
+ object wordObj = Activator.CreateInstance(word);
+ Console.WriteLine("Instantiated {0}",
+ wordObj.GetType().FullName, WORD_CLSID);
+
+ // Close Word.
+ word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
+ wordObj, [0, 0, false]);
+ }
+ catch (COMException)
+ {
+ Console.WriteLine("Unable to instantiate object.");
+ }
+ }
}
// The example displays the following output:
// Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
diff --git a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs
index ca61680bb07..2f5f32e40bf 100644
--- a/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs
+++ b/snippets/csharp/System/Type/GetTypeFromCLSID/gettypefromclsid_ex4.cs
@@ -1,35 +1,37 @@
//
using System;
using System.Reflection;
-using System.Runtime.InteropServices;
-public class Example
+
+public class GetTypeFromClsidExample4
{
- private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
-
- public static void Main()
- {
- try {
- // Start an instance of the Word application.
- var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID),
- "computer17.central.contoso.com",
- true);
- Console.WriteLine("Instantiated Type object from CLSID {0}",
- WORD_CLSID);
- Object wordObj = Activator.CreateInstance(word);
- Console.WriteLine("Instantiated {0}",
- wordObj.GetType().FullName, WORD_CLSID);
-
- // Close Word.
- word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
- wordObj, new object[] { 0, 0, false } );
- }
- // The method can throw any of a variety of exceptions.
- catch (Exception e) {
- Console.WriteLine("{0}: Unable to instantiate an object for {1}",
- e.GetType().Name, WORD_CLSID);
- }
- }
+ private const string WORD_CLSID = "{000209FF-0000-0000-C000-000000000046}";
+
+ public static void Run()
+ {
+ try
+ {
+ // Start an instance of the Word application.
+ var word = Type.GetTypeFromCLSID(Guid.Parse(WORD_CLSID),
+ "computer17.central.contoso.com",
+ true);
+ Console.WriteLine("Instantiated Type object from CLSID {0}",
+ WORD_CLSID);
+ object wordObj = Activator.CreateInstance(word);
+ Console.WriteLine("Instantiated {0}",
+ wordObj.GetType().FullName, WORD_CLSID);
+
+ // Close Word.
+ word.InvokeMember("Quit", BindingFlags.InvokeMethod, null,
+ wordObj, [0, 0, false]);
+ }
+ // The method can throw any of a variety of exceptions.
+ catch (Exception e)
+ {
+ Console.WriteLine("{0}: Unable to instantiate an object for {1}",
+ e.GetType().Name, WORD_CLSID);
+ }
+ }
}
// The example displays the following output:
// Instantiated Type object from CLSID {000209FF-0000-0000-C000-000000000046}
diff --git a/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs b/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs
index 5cc5c7b802a..9912d73d65b 100644
--- a/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs
+++ b/snippets/csharp/System/Type/GetTypeFromHandle/type_gettypefromhandle.cs
@@ -9,20 +9,20 @@ returns the type referenced by the specified type handle.
*/
using System;
-using System.Reflection;
+
public class MyClass1
{
}
public class MyClass2
{
- public static void Main()
- {
-//
- MyClass1 myClass1 = new MyClass1();
- // Get the type referenced by the specified type handle.
+ public static void Main()
+ {
+ //
+ MyClass1 myClass1 = new();
+ // Get the type referenced by the specified type handle.
Type myClass1Type = Type.GetTypeFromHandle(Type.GetTypeHandle(myClass1));
- Console.WriteLine("The Names of the Attributes :"+myClass1Type.Attributes);
-//
- }
+ Console.WriteLine("The Names of the Attributes :" + myClass1Type.Attributes);
+ //
+ }
}
diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs b/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs
new file mode 100644
index 00000000000..20ffc263a18
--- /dev/null
+++ b/snippets/csharp/System/Type/GetTypeFromProgID/Program.cs
@@ -0,0 +1,3 @@
+ProgIdExample2.Run();
+ProgIdExample3.Run();
+ProgIdExample4.Run();
diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj b/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/GetTypeFromProgID/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs
index 79fae7f6198..d319b5442c5 100644
--- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs
+++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid2.cs
@@ -1,27 +1,27 @@
//
using System;
-class MainApp
+class ProgIdExample2
{
- public static void Main()
+ public static void Run()
{
try
{
// Use the ProgID HKEY_CLASSES_ROOT\DirControl.DirList.1.
- string myString1 ="DIRECT.ddPalette.3";
+ string myString1 = "DIRECT.ddPalette.3";
// Use a nonexistent ProgID WrongProgID.
- string myString2 ="WrongProgID";
+ string myString2 = "WrongProgID";
// Make a call to the method to get the type information of the given ProgID.
- Type myType1 =Type.GetTypeFromProgID(myString1,true);
- Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType1.GUID);
+ Type myType1 = Type.GetTypeFromProgID(myString1, true);
+ Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType1.GUID}.");
// Throw an exception because the ProgID is invalid and the throwOnError
// parameter is set to True.
- Type myType2 =Type.GetTypeFromProgID(myString2,true);
+ Type myType2 = Type.GetTypeFromProgID(myString2, true);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Source: {0}", e.Source);
- Console.WriteLine("Message: {0}", e.Message);
+ Console.WriteLine($"Source: {e.Source}");
+ Console.WriteLine($"Message: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs
index c393f182998..ee9e294fe37 100644
--- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs
+++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid3.cs
@@ -1,29 +1,29 @@
//
using System;
-class MainApp
+class ProgIdExample3
{
- public static void Main()
+ public static void Run()
{
try
{
// Use the ProgID localhost\HKEY_CLASSES_ROOT\DirControl.DirList.1.
- string theProgramID ="DirControl.DirList.1";
+ string theProgramID = "DirControl.DirList.1";
// Use the server name localhost.
- string theServer="localhost";
+ string theServer = "localhost";
// Make a call to the method to get the type information for the given ProgID.
- Type myType =Type.GetTypeFromProgID(theProgramID,theServer);
- if(myType==null)
+ Type myType = Type.GetTypeFromProgID(theProgramID, theServer);
+ if (myType == null)
{
throw new Exception("Invalid ProgID or Server.");
}
- Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType.GUID);
+ Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType.GUID}.");
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("An exception occurred.");
- Console.WriteLine("Source: {0}" , e.Source);
- Console.WriteLine("Message: {0}" , e.Message);
- }
+ Console.WriteLine($"Source: {e.Source}");
+ Console.WriteLine($"Message: {e.Message}");
+ }
}
}
//
diff --git a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs
index 614ad868a87..8f2b49274f7 100644
--- a/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs
+++ b/snippets/csharp/System/Type/GetTypeFromProgID/type_gettypefromprogid4.cs
@@ -1,30 +1,30 @@
//
using System;
-class MainApp
+class ProgIdExample4
{
- public static void Main()
+ public static void Run()
{
try
{
// Use server localhost.
- string theServer="localhost";
+ string theServer = "localhost";
// Use ProgID HKEY_CLASSES_ROOT\DirControl.DirList.1.
- string myString1 ="DirControl.DirList.1";
+ string myString1 = "DirControl.DirList.1";
// Use a wrong ProgID WrongProgID.
- string myString2 ="WrongProgID";
+ string myString2 = "WrongProgID";
// Make a call to the method to get the type information for the given ProgID.
- Type myType1 =Type.GetTypeFromProgID(myString1,theServer,true);
- Console.WriteLine("GUID for ProgID DirControl.DirList.1 is {0}.", myType1.GUID);
+ Type myType1 = Type.GetTypeFromProgID(myString1, theServer, true);
+ Console.WriteLine($"GUID for ProgID DirControl.DirList.1 is {myType1.GUID}.");
// Throw an exception because the ProgID is invalid and the throwOnError
// parameter is set to True.
- Type myType2 =Type.GetTypeFromProgID(myString2, theServer, true);
+ Type myType2 = Type.GetTypeFromProgID(myString2, theServer, true);
}
- catch(Exception e)
+ catch (Exception e)
{
Console.WriteLine("An exception occurred. The ProgID is wrong.");
- Console.WriteLine("Source: {0}" , e.Source);
- Console.WriteLine("Message: {0}" , e.Message);
+ Console.WriteLine($"Source: {e.Source}");
+ Console.WriteLine($"Message: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/HasElementType/Project.csproj b/snippets/csharp/System/Type/HasElementType/Project.csproj
new file mode 100644
index 00000000000..44b6b69ca6f
--- /dev/null
+++ b/snippets/csharp/System/Type/HasElementType/Project.csproj
@@ -0,0 +1,7 @@
+
+
+ Exe
+ net10.0
+ true
+
+
diff --git a/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs b/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs
index 72580e41191..4217e994597 100644
--- a/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs
+++ b/snippets/csharp/System/Type/HasElementType/type_haselementtype.cs
@@ -7,29 +7,26 @@
public class Example
{
// This method is for demonstration purposes.
- unsafe public void Test(ref int x, out int y, int* z)
- {
- *z = x = y = 0;
- }
+ unsafe public void Test(ref int x, out int y, int* z) => *z = x = y = 0;
public static void Main()
{
// All of the following display 'True'.
// Define an array, get its type, and display HasElementType.
- int[] nums = {1, 1, 2, 3, 5, 8, 13};
+ int[] nums = [1, 1, 2, 3, 5, 8, 13];
Type t = nums.GetType();
- Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types.");
// Test an array type without defining an array.
t = typeof(Example[]);
- Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types.");
// When you use Reflection Emit to emit dynamic methods and
// assemblies, you can create array types using MakeArrayType.
// The following creates the type 'array of Example'.
t = typeof(Example).MakeArrayType();
- Console.WriteLine("HasElementType is '{0}' for array types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for array types.");
// When you reflect over methods, HasElementType is true for
// ref, out, and pointer parameter types. The following
@@ -38,19 +35,19 @@ public static void Main()
MethodInfo mi = typeof(Example).GetMethod("Test");
ParameterInfo[] parms = mi.GetParameters();
t = parms[0].ParameterType;
- Console.WriteLine("HasElementType is '{0}' for ref parameter types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for ref parameter types.");
t = parms[1].ParameterType;
- Console.WriteLine("HasElementType is '{0}' for out parameter types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for out parameter types.");
t = parms[2].ParameterType;
- Console.WriteLine("HasElementType is '{0}' for pointer parameter types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for pointer parameter types.");
// When you use Reflection Emit to emit dynamic methods and
// assemblies, you can create pointer and ByRef types to use
// when you define method parameters.
t = typeof(Example).MakePointerType();
- Console.WriteLine("HasElementType is '{0}' for pointer types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for pointer types.");
t = typeof(Example).MakeByRefType();
- Console.WriteLine("HasElementType is '{0}' for ByRef types.", t.HasElementType);
+ Console.WriteLine($"HasElementType is '{t.HasElementType}' for ByRef types.");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs b/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs
index 18df3d3db3c..9dee37ed1ed 100644
--- a/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs
+++ b/snippets/csharp/System/Type/HasElementTypeImpl/type_haselementtypeimpl.cs
@@ -4,28 +4,25 @@
public class MyTypeDelegator : TypeDelegator
{
public string myElementType = null;
- private Type myType = null ;
- public MyTypeDelegator(Type myType) : base(myType)
- {
- this.myType = myType;
- }
+ private Type myType = null;
+ public MyTypeDelegator(Type myType) : base(myType) => this.myType = myType;
// Override Type.HasElementTypeImpl().
protected override bool HasElementTypeImpl()
{
// Determine whether the type is an array.
- if(myType.IsArray)
+ if (myType.IsArray)
{
myElementType = "array";
return true;
}
// Determine whether the type is a reference.
- if(myType.IsByRef)
+ if (myType.IsByRef)
{
myElementType = "reference";
return true;
}
// Determine whether the type is a pointer.
- if(myType.IsPointer)
+ if (myType.IsPointer)
{
myElementType = "pointer";
return true;
@@ -40,25 +37,25 @@ public static void Main()
{
try
{
- int myInt = 0 ;
+ int myInt = 0;
int[] myArray = new int[5];
- MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType());
+ MyTypeDelegator myType = new(myArray.GetType());
// Determine whether myType is an array, pointer, reference type.
Console.WriteLine("\nDetermine whether a variable is an array, pointer, or reference type.\n");
- if( myType.HasElementType)
- Console.WriteLine("The type of myArray is {0}.", myType.myElementType);
+ if (myType.HasElementType)
+ Console.WriteLine($"The type of myArray is {myType.myElementType}.");
else
Console.WriteLine("myArray is not an array, pointer, or reference type.");
- myType = new MyTypeDelegator(myInt.GetType());
+ myType = new(myInt.GetType());
// Determine whether myType is an array, pointer, reference type.
- if( myType.HasElementType)
- Console.WriteLine("The type of myInt is {0}.", myType.myElementType);
+ if (myType.HasElementType)
+ Console.WriteLine($"The type of myInt is {myType.myElementType}.");
else
Console.WriteLine("myInt is not an array, pointer, or reference type.");
}
- catch( Exception e )
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message);
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/InvokeMember/invokemem.cs b/snippets/csharp/System/Type/InvokeMember/invokemem.cs
index 69618c33a7a..b9b9282fb9c 100644
--- a/snippets/csharp/System/Type/InvokeMember/invokemem.cs
+++ b/snippets/csharp/System/Type/InvokeMember/invokemem.cs
@@ -5,12 +5,12 @@
// This sample class has a field, constructor, method, and property.
class MyType
{
- Int32 myField;
- public MyType(ref Int32 x) {x *= 5;}
- public override String ToString() {return myField.ToString();}
- public Int32 MyProp
+ int myField;
+ public MyType(ref int x) => x *= 5;
+ public override string ToString() => myField.ToString();
+ public int MyProp
{
- get {return myField;}
+ get => myField;
set
{
if (value < 1)
@@ -26,28 +26,28 @@ static void Main()
{
Type t = typeof(MyType);
// Create an instance of a type.
- Object[] args = new Object[] {8};
- Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
- Object obj = t.InvokeMember(null,
+ object[] args = [8];
+ Console.WriteLine($"The value of x before the constructor is called is {args[0]}.");
+ object obj = t.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
- Console.WriteLine("Type: " + obj.GetType().ToString());
- Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);
+ Console.WriteLine("Type: " + obj.GetType());
+ Console.WriteLine($"The value of x after the constructor returns is {args[0]}.");
// Read and write to a field.
t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5});
- Int32 v = (Int32) t.InvokeMember("myField",
+ BindingFlags.Instance | BindingFlags.SetField, null, obj, [5]);
+ int v = (int)t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
Console.WriteLine("myField: " + v);
// Call a method.
- String s = (String) t.InvokeMember("ToString",
+ string s = (string)t.InvokeMember("ToString",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
@@ -67,7 +67,7 @@ static void Main()
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0});
+ BindingFlags.Instance | BindingFlags.SetProperty, null, obj, [0]);
}
catch (TargetInvocationException e)
{
@@ -81,12 +81,12 @@ static void Main()
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2});
- v = (Int32) t.InvokeMember("MyProp",
+ BindingFlags.Instance | BindingFlags.SetProperty, null, obj, [2]);
+ v = (int)t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
Console.WriteLine("MyProp: " + v);
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsAbstract/isabstract1.cs b/snippets/csharp/System/Type/IsAbstract/isabstract1.cs
index e8fd4bc0b3b..795f13a3810 100644
--- a/snippets/csharp/System/Type/IsAbstract/isabstract1.cs
+++ b/snippets/csharp/System/Type/IsAbstract/isabstract1.cs
@@ -2,43 +2,39 @@
using System;
public abstract class AbstractClass
-{}
+{ }
public class DerivedClass : AbstractClass
-{}
+{ }
public sealed class SingleClass
-{}
+{ }
public interface ITypeInfo
{
- string GetName();
+ string GetName();
}
public class ImplementingClass : ITypeInfo
{
- public string GetName()
- {
- return this.GetType().FullName;
- }
+ public string GetName() => this.GetType().FullName;
}
delegate string InputOutput(string inp);
public class Example
{
- public static void Main()
- {
- Type[] types= { typeof(AbstractClass),
- typeof(DerivedClass),
- typeof(ITypeInfo),
- typeof(SingleClass),
- typeof(ImplementingClass),
- typeof(InputOutput) };
- foreach (var type in types)
- Console.WriteLine("{0} is abstract: {1}",
- type.Name, type.IsAbstract);
- }
+ public static void Main()
+ {
+ Type[] types = [typeof(AbstractClass),
+ typeof(DerivedClass),
+ typeof(ITypeInfo),
+ typeof(SingleClass),
+ typeof(ImplementingClass),
+ typeof(InputOutput)];
+ foreach (var type in types)
+ Console.WriteLine($"{type.Name} is abstract: {type.IsAbstract}");
+ }
}
// The example displays the following output:
// AbstractClass is abstract: True
diff --git a/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs b/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs
index d42efe9efe2..e5b06e91157 100644
--- a/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs
+++ b/snippets/csharp/System/Type/IsAnsiClass/type_isansiclass.cs
@@ -3,7 +3,7 @@
using System.Reflection;
public class MyClass
{
- protected string myField = "A sample protected field." ;
+ protected string myField = "A sample protected field.";
}
public class MyType_IsAnsiClass
{
@@ -11,19 +11,19 @@ public static void Main()
{
try
{
- MyClass myObject = new MyClass();
+ MyClass myObject = new();
// Get the type of the 'MyClass'.
Type myType = typeof(MyClass);
// Get the field information and the attributes associated with MyClass.
- FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.NonPublic|BindingFlags.Instance);
- Console.WriteLine( "\nChecking for the AnsiClass attribute for a field.\n");
+ FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.NonPublic | BindingFlags.Instance);
+ Console.WriteLine("\nChecking for the AnsiClass attribute for a field.\n");
// Get and display the name, field, and the AnsiClass attribute.
- Console.WriteLine("Name of Class: {0} \nValue of Field: {1} \nIsAnsiClass = {2}", myType.FullName, myFieldInfo.GetValue(myObject), myType.IsAnsiClass);
+ Console.WriteLine($"Name of Class: {myType.FullName} \nValue of Field: {myFieldInfo.GetValue(myObject)} \nIsAnsiClass = {myType.IsAnsiClass}");
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}",e.Message);
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsArray/isarray2.cs b/snippets/csharp/System/Type/IsArray/isarray2.cs
index feed53d1423..66907266053 100644
--- a/snippets/csharp/System/Type/IsArray/isarray2.cs
+++ b/snippets/csharp/System/Type/IsArray/isarray2.cs
@@ -5,16 +5,15 @@
public class Example
{
- public static void Main()
- {
- Type[] types = { typeof(String), typeof(int[]),
- typeof(ArrayList), typeof(Array),
- typeof(List),
- typeof(IEnumerable) };
- foreach (var t in types)
- Console.WriteLine("{0,-15} IsArray = {1}", t.Name + ":",
- t.IsArray);
- }
+ public static void Main()
+ {
+ Type[] types = [typeof(string), typeof(int[]),
+ typeof(ArrayList), typeof(Array),
+ typeof(List),
+ typeof(IEnumerable)];
+ foreach (var t in types)
+ Console.WriteLine($"{t.Name + ":",-15} IsArray = {t.IsArray}");
+ }
}
// The example displays the following output:
// String: IsArray = False
diff --git a/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs b/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs
index bf078734e26..4b52c4981fd 100644
--- a/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs
+++ b/snippets/csharp/System/Type/IsArrayImpl/type_isarrayimpl.cs
@@ -5,15 +5,12 @@ public class MyTypeDelegator : TypeDelegator
{
public string myElementType = null;
public Type myType;
- public MyTypeDelegator(Type myType) : base(myType)
- {
- this.myType = myType;
- }
+ public MyTypeDelegator(Type myType) : base(myType) => this.myType = myType;
// Override IsArrayImpl().
protected override bool IsArrayImpl()
{
// Determine whether the type is an array.
- if(myType.IsArray)
+ if (myType.IsArray)
{
myElementType = "array";
return true;
@@ -28,27 +25,27 @@ public static void Main()
{
try
{
- int myInt = 0 ;
+ int myInt = 0;
// Create an instance of an array element.
int[] myArray = new int[5];
- MyTypeDelegator myType = new MyTypeDelegator(myArray.GetType());
+ MyTypeDelegator myType = new(myArray.GetType());
Console.WriteLine("\nDetermine whether the variable is an array.\n");
// Determine whether myType is an array type.
- if( myType.IsArray)
- Console.WriteLine("The type of myArray is {0}.", myType.myElementType);
+ if (myType.IsArray)
+ Console.WriteLine($"The type of myArray is {myType.myElementType}.");
else
Console.WriteLine("myArray is not an array.");
- myType = new MyTypeDelegator(myInt.GetType());
+ myType = new(myInt.GetType());
// Determine whether myType is an array type.
- if( myType.IsArray)
- Console.WriteLine("The type of myInt is {0}.", myType.myElementType);
+ if (myType.IsArray)
+ Console.WriteLine($"The type of myInt is {myType.myElementType}.");
else
Console.WriteLine("myInt is not an array.");
}
- catch( Exception e )
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message );
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs
index aa1219c81c6..1571176e7ab 100644
--- a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs
+++ b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom2.cs
@@ -2,18 +2,18 @@
using System;
using System.IO;
-public class Example
+public class IsAssignableFromExample2
{
- public static void Main()
- {
- Type t = typeof(Stream);
- Type genericT = typeof(GenericWithConstraint<>);
- Type genericParam = genericT.GetGenericArguments()[0];
- Console.WriteLine(t.IsAssignableFrom(genericParam));
- // Displays True.
- }
+ public static void Run()
+ {
+ Type t = typeof(Stream);
+ Type genericT = typeof(GenericWithConstraint<>);
+ Type genericParam = genericT.GetGenericArguments()[0];
+ Console.WriteLine(t.IsAssignableFrom(genericParam));
+ // Displays True.
+ }
}
public class GenericWithConstraint where T : Stream
-{}
+{ }
//
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs
index 15c10742cc7..8e946b32725 100644
--- a/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs
+++ b/snippets/csharp/System/Type/IsAssignableFrom/IsAssignableFrom3.cs
@@ -2,19 +2,19 @@
using System;
using System.Collections;
-public class Example
+public class IsAssignableFromExample3
{
- public static void Main()
- {
- Type t = typeof(IEnumerable);
- Type c = typeof(Array);
-
- IEnumerable instanceOfT;
- int[] instanceOfC = { 1, 2, 3, 4 };
- if (t.IsAssignableFrom(c))
- //
- instanceOfT = instanceOfC;
- //
- }
+ public static void Run()
+ {
+ Type t = typeof(IEnumerable);
+ Type c = typeof(Array);
+
+ IEnumerable instanceOfT;
+ int[] instanceOfC = [1, 2, 3, 4];
+ if (t.IsAssignableFrom(c))
+ //
+ instanceOfT = instanceOfC;
+ //
+ }
}
//
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/Program.cs b/snippets/csharp/System/Type/IsAssignableFrom/Program.cs
new file mode 100644
index 00000000000..b26637a8463
--- /dev/null
+++ b/snippets/csharp/System/Type/IsAssignableFrom/Program.cs
@@ -0,0 +1,4 @@
+IsAssignableFromExample1.Run();
+IsAssignableFromExample2.Run();
+IsAssignableFromExample3.Run();
+IsAssignableFromTest.Run();
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj b/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/IsAssignableFrom/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs b/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs
index 51246e4ac4e..a3bde43aec2 100644
--- a/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs
+++ b/snippets/csharp/System/Type/IsAssignableFrom/isassignablefrom_ex1.cs
@@ -4,26 +4,27 @@
using System.Reflection.Emit;
public class A
-{}
+{ }
-public class Example
+public class IsAssignableFromExample1
{
- public static void Main()
- {
- AppDomain domain = AppDomain.CurrentDomain;
- AssemblyName assemName = new AssemblyName();
- assemName.Name = "TempAssembly";
+ public static void Run()
+ {
+ AssemblyName assemName = new()
+ {
+ Name = "TempAssembly"
+ };
- // Define a dynamic assembly in the current application domain.
- AssemblyBuilder assemBuilder = domain.DefineDynamicAssembly(assemName,
- AssemblyBuilderAccess.Run);
+ // Define a dynamic assembly.
+ AssemblyBuilder assemBuilder = AssemblyBuilder.DefineDynamicAssembly(
+ assemName, AssemblyBuilderAccess.Run);
- // Define a dynamic module in this assembly.
- ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("TempModule");
+ // Define a dynamic module in this assembly.
+ ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("TempModule");
- TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A));
- Console.WriteLine(typeof(A).IsAssignableFrom(b1));
- }
+ TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A));
+ Console.WriteLine(typeof(A).IsAssignableFrom(b1));
+ }
}
// The example displays the following output:
// True
diff --git a/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs b/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs
index eedfa2553f0..3c7161f9043 100644
--- a/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs
+++ b/snippets/csharp/System/Type/IsAssignableFrom/testisassignablefrom.cs
@@ -1,64 +1,64 @@
//
using System;
using System.Collections.Generic;
-class Program
+class IsAssignableFromTest
{
- public static void Main()
+ public static void Run()
{
- // Demonstrate classes:
- Console.WriteLine("Defined Classes:");
- Room room1 = new Room();
- Kitchen kitchen1 = new Kitchen();
- Bedroom bedroom1 = new Bedroom();
- Guestroom guestroom1 = new Guestroom();
- MasterBedroom masterbedroom1 = new MasterBedroom();
-
- Type room1Type = room1.GetType();
- Type kitchen1Type = kitchen1.GetType();
- Type bedroom1Type = bedroom1.GetType();
- Type guestroom1Type = guestroom1.GetType();
- Type masterbedroom1Type = masterbedroom1.GetType();
-
- Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type));
- Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type));
- Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type));
-
- // Demonstrate arrays:
- Console.WriteLine();
- Console.WriteLine("Integer arrays:");
-
- int[] array2 = new int[2];
- int[] array10 = new int[10];
- int[,] array22 = new int[2, 2];
- int[,] array24 = new int[2, 4];
-
- Type array2Type = array2.GetType();
- Type array10Type = array10.GetType();
- Type array22Type = array22.GetType();
- Type array24Type = array24.GetType();
-
- Console.WriteLine("int[2] assignable from int[10]: {0}", array2Type.IsAssignableFrom(array10Type));
- Console.WriteLine("int[2] assignable from int[2,4]: {0}", array2Type.IsAssignableFrom(array24Type));
- Console.WriteLine("int[2,4] assignable from int[2,2]: {0}", array24Type.IsAssignableFrom(array22Type));
-
- // Demonstrate generics:
- Console.WriteLine();
- Console.WriteLine("Generics:");
-
- // Note that "int?[]" is the same as "Nullable[]"
- int?[] arrayNull = new int?[10];
- List genIntList = new List();
- List genTList = new List();
-
- Type arrayNullType = arrayNull.GetType();
- Type genIntListType = genIntList.GetType();
- Type genTListType = genTList.GetType();
-
- Console.WriteLine("int[10] assignable from int?[10]: {0}", array10Type.IsAssignableFrom(arrayNullType));
- Console.WriteLine("List assignable from List: {0}", genIntListType.IsAssignableFrom(genTListType));
- Console.WriteLine("List assignable from List: {0}", genTListType.IsAssignableFrom(genIntListType));
-
- Console.ReadLine();
+ // Demonstrate classes:
+ Console.WriteLine("Defined Classes:");
+ Room room1 = new();
+ Kitchen kitchen1 = new();
+ Bedroom bedroom1 = new();
+ Guestroom guestroom1 = new();
+ MasterBedroom masterbedroom1 = new();
+
+ Type room1Type = room1.GetType();
+ Type kitchen1Type = kitchen1.GetType();
+ Type bedroom1Type = bedroom1.GetType();
+ Type guestroom1Type = guestroom1.GetType();
+ Type masterbedroom1Type = masterbedroom1.GetType();
+
+ Console.WriteLine($"room assignable from kitchen: {room1Type.IsAssignableFrom(kitchen1Type)}");
+ Console.WriteLine($"bedroom assignable from guestroom: {bedroom1Type.IsAssignableFrom(guestroom1Type)}");
+ Console.WriteLine($"kitchen assignable from masterbedroom: {kitchen1Type.IsAssignableFrom(masterbedroom1Type)}");
+
+ // Demonstrate arrays:
+ Console.WriteLine();
+ Console.WriteLine("Integer arrays:");
+
+ int[] array2 = new int[2];
+ int[] array10 = new int[10];
+ int[,] array22 = new int[2, 2];
+ int[,] array24 = new int[2, 4];
+
+ Type array2Type = array2.GetType();
+ Type array10Type = array10.GetType();
+ Type array22Type = array22.GetType();
+ Type array24Type = array24.GetType();
+
+ Console.WriteLine($"int[2] assignable from int[10]: {array2Type.IsAssignableFrom(array10Type)}");
+ Console.WriteLine($"int[2] assignable from int[2,4]: {array2Type.IsAssignableFrom(array24Type)}");
+ Console.WriteLine($"int[2,4] assignable from int[2,2]: {array24Type.IsAssignableFrom(array22Type)}");
+
+ // Demonstrate generics:
+ Console.WriteLine();
+ Console.WriteLine("Generics:");
+
+ // Note that "int?[]" is the same as "Nullable[]"
+ int?[] arrayNull = new int?[10];
+ List genIntList = new();
+ List genTList = new();
+
+ Type arrayNullType = arrayNull.GetType();
+ Type genIntListType = genIntList.GetType();
+ Type genTListType = genTList.GetType();
+
+ Console.WriteLine($"int[10] assignable from int?[10]: {array10Type.IsAssignableFrom(arrayNullType)}");
+ Console.WriteLine($"List assignable from List: {genIntListType.IsAssignableFrom(genTListType)}");
+ Console.WriteLine($"List assignable from List: {genTListType.IsAssignableFrom(genIntListType)}");
+
+ Console.ReadLine();
}
}
class Room
@@ -97,4 +97,4 @@ class MasterBedroom : Bedroom
// int[10] assignable from int?[10]: False
// List assignable from List: False
// List assignable from List: False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs b/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs
index 184d4e2dadc..906dbd9bd12 100644
--- a/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs
+++ b/snippets/csharp/System/Type/IsAutoLayout/type_isautolayout.cs
@@ -13,11 +13,10 @@ public class Example
public static void Main()
{
// Create an instance of the Type class using the GetType method.
- Type myType=typeof(Demo);
+ Type myType = typeof(Demo);
// Get and display the IsAutoLayout property of the
// Demoinstance.
- Console.WriteLine("\nThe AutoLayout property for the Demo class is {0}.",
- myType.IsAutoLayout);
+ Console.WriteLine($"\nThe AutoLayout property for the Demo class is {myType.IsAutoLayout}.");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsClass/type_isclass.cs b/snippets/csharp/System/Type/IsClass/type_isclass.cs
index 9898d0a5235..5140bcbb8fc 100644
--- a/snippets/csharp/System/Type/IsClass/type_isclass.cs
+++ b/snippets/csharp/System/Type/IsClass/type_isclass.cs
@@ -1,8 +1,8 @@
//
using System;
-using System.Reflection;
-public class MyDemoClass
+
+public class MyDemoClass
{
}
@@ -12,13 +12,13 @@ public static void Main(string[] args)
{
try
{
- Type myType = typeof(MyDemoClass);
+ Type myType = typeof(MyDemoClass);
// Get and display the 'IsClass' property of the 'MyDemoClass' instance.
- Console.WriteLine("\nIs the specified type a class? {0}.", myType.IsClass);
+ Console.WriteLine($"\nIs the specified type a class? {myType.IsClass}.");
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("\nAn exception occurred: {0}." ,e.Message);
+ Console.WriteLine($"\nAn exception occurred: {e.Message}.");
}
}
}
diff --git a/snippets/csharp/System/Type/IsContextful/Project.csproj b/snippets/csharp/System/Type/IsContextful/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/IsContextful/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs b/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs
index 08ebbbb8854..c88c6521f04 100644
--- a/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs
+++ b/snippets/csharp/System/Type/IsContextful/type_iscontextful.cs
@@ -1,8 +1,8 @@
//
using System;
-using System.Runtime.Remoting.Contexts;
-public class ContextBoundClass: ContextBoundObject
+
+public class ContextBoundClass : ContextBoundObject
{
public string Value = "The Value property.";
}
@@ -11,23 +11,17 @@ public class Example
{
public static void Main()
{
- // Determine whether the types can be hosted in a Context.
- Console.WriteLine("The IsContextful property for the {0} type is {1}.",
- typeof(Example).Name, typeof(Example).IsContextful);
- Console.WriteLine("The IsContextful property for the {0} type is {1}.",
- typeof(ContextBoundClass).Name, typeof(ContextBoundClass).IsContextful);
+ // Determine whether the types can be hosted in a Context.
+ Console.WriteLine($"The IsContextful property for the {typeof(Example).Name} type is {typeof(Example).IsContextful}.");
+ Console.WriteLine($"The IsContextful property for the {typeof(ContextBoundClass).Name} type is {typeof(ContextBoundClass).IsContextful}.");
- // Determine whether the types are marshalled by reference.
- Console.WriteLine("The IsMarshalByRef property of {0} is {1}.",
- typeof(Example).Name, typeof(Example).IsMarshalByRef);
- Console.WriteLine("The IsMarshalByRef property of {0} is {1}.",
- typeof(ContextBoundClass).Name, typeof(ContextBoundClass).IsMarshalByRef);
+ // Determine whether the types are marshalled by reference.
+ Console.WriteLine($"The IsMarshalByRef property of {typeof(Example).Name} is {typeof(Example).IsMarshalByRef}.");
+ Console.WriteLine($"The IsMarshalByRef property of {typeof(ContextBoundClass).Name} is {typeof(ContextBoundClass).IsMarshalByRef}.");
- // Determine whether the types are primitive datatypes.
- Console.WriteLine("{0} is a primitive data type: {1}.",
- typeof(int).Name, typeof(int).IsPrimitive);
- Console.WriteLine("{0} is a primitive data type: {1}.",
- typeof(string).Name, typeof(string).IsPrimitive);
+ // Determine whether the types are primitive datatypes.
+ Console.WriteLine($"{typeof(int).Name} is a primitive data type: {typeof(int).IsPrimitive}.");
+ Console.WriteLine($"{typeof(string).Name} is a primitive data type: {typeof(string).IsPrimitive}.");
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs b/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs
index fc0890ba3af..1e1e69c06ee 100644
--- a/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs
+++ b/snippets/csharp/System/Type/IsContextfulImpl/type_iscontextfulimpl.cs
@@ -4,17 +4,14 @@
public class MyTypeDelegatorClass : TypeDelegator
{
public string myElementType = null;
- private Type myType = null ;
+ private Type myType = null;
- public MyTypeDelegatorClass(Type myType) : base(myType)
- {
- this.myType = myType;
- }
+ public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType;
// Override IsContextfulImpl.
protected override bool IsContextfulImpl()
{
// Check whether the type is contextful.
- if(myType.IsContextful)
+ if (myType.IsContextful)
{
myElementType = " is contextful ";
return true;
@@ -29,10 +26,10 @@ public static void Main()
try
{
MyTypeDelegatorClass myType;
- Console.WriteLine ("Check whether MyContextBoundClass can be hosted in a context.");
+ Console.WriteLine("Check whether MyContextBoundClass can be hosted in a context.");
// Check whether MyContextBoundClass is contextful.
- myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass));
- if( myType.IsContextful)
+ myType = new(typeof(MyContextBoundClass));
+ if (myType.IsContextful)
{
Console.WriteLine(typeof(MyContextBoundClass) + " can be hosted in a context.");
}
@@ -41,9 +38,9 @@ public static void Main()
Console.WriteLine(typeof(MyContextBoundClass) + " cannot be hosted in a context.");
}
// Check whether the int type is contextful.
- myType = new MyTypeDelegatorClass(typeof(MyTypeDemoClass));
- Console.WriteLine ("\nCheck whether MyTypeDemoClass can be hosted in a context.");
- if( myType.IsContextful)
+ myType = new(typeof(MyTypeDemoClass));
+ Console.WriteLine("\nCheck whether MyTypeDemoClass can be hosted in a context.");
+ if (myType.IsContextful)
{
Console.WriteLine(typeof(MyTypeDemoClass) + " can be hosted in a context.");
}
@@ -52,9 +49,9 @@ public static void Main()
Console.WriteLine(typeof(MyTypeDemoClass) + " cannot be hosted in a context.");
}
}
- catch( Exception e )
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message);
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/IsEnum/testisenum.cs b/snippets/csharp/System/Type/IsEnum/testisenum.cs
index e084641434e..9881e6d3d21 100644
--- a/snippets/csharp/System/Type/IsEnum/testisenum.cs
+++ b/snippets/csharp/System/Type/IsEnum/testisenum.cs
@@ -7,13 +7,13 @@ class TestIsEnum
{
public static void Main()
{
- Type colorType = typeof(Color);
- Type enumType = typeof(Enum);
- Console.WriteLine("Is Color an enum? {0}.", colorType.IsEnum);
- Console.WriteLine("Is Color a value type? {0}.", colorType.IsValueType);
- Console.WriteLine("Is Enum an enum Type? {0}.", enumType.IsEnum);
- Console.WriteLine("Is Enum a value type? {0}.", enumType.IsValueType);
- }
+ Type colorType = typeof(Color);
+ Type enumType = typeof(Enum);
+ Console.WriteLine($"Is Color an enum? {colorType.IsEnum}.");
+ Console.WriteLine($"Is Color a value type? {colorType.IsValueType}.");
+ Console.WriteLine($"Is Enum an enum Type? {enumType.IsEnum}.");
+ Console.WriteLine($"Is Enum a value type? {enumType.IsValueType}.");
+ }
}
// The example displays the following output:
// Is Color an enum? True.
diff --git a/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs b/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs
index 7993cb6d7b3..2ba10268f88 100644
--- a/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs
+++ b/snippets/csharp/System/Type/IsExplicitLayout/type_isexplicitlayout.cs
@@ -1,21 +1,21 @@
//
using System;
-using System.Reflection;
-using System.ComponentModel;
+
+
using System.Runtime.InteropServices;
// Class to test for the ExplicitLayout property.
-[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
+[StructLayout(LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi)]
public class MySystemTime
{
- [FieldOffset(0)]public ushort wYear;
- [FieldOffset(2)]public ushort wMonth;
- [FieldOffset(4)]public ushort wDayOfWeek;
- [FieldOffset(6)]public ushort wDay;
- [FieldOffset(8)]public ushort wHour;
- [FieldOffset(10)]public ushort wMinute;
- [FieldOffset(12)]public ushort wSecond;
- [FieldOffset(14)]public ushort wMilliseconds;
+ [FieldOffset(0)] public ushort wYear;
+ [FieldOffset(2)] public ushort wMonth;
+ [FieldOffset(4)] public ushort wDayOfWeek;
+ [FieldOffset(6)] public ushort wDay;
+ [FieldOffset(8)] public ushort wHour;
+ [FieldOffset(10)] public ushort wMinute;
+ [FieldOffset(12)] public ushort wSecond;
+ [FieldOffset(14)] public ushort wMilliseconds;
}
public class Program
@@ -23,10 +23,9 @@ public class Program
public static void Main(string[] args)
{
// Create an instance of the type using the GetType method.
- Type t = typeof(MySystemTime);
+ Type t = typeof(MySystemTime);
// Get and display the IsExplicitLayout property.
- Console.WriteLine("\nIsExplicitLayout for MySystemTime is {0}.",
- t.IsExplicitLayout);
+ Console.WriteLine($"\nIsExplicitLayout for MySystemTime is {t.IsExplicitLayout}.");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsGenericParameter/source.cs b/snippets/csharp/System/Type/IsGenericParameter/source.cs
index aff8b688c19..b129230bb08 100644
--- a/snippets/csharp/System/Type/IsGenericParameter/source.cs
+++ b/snippets/csharp/System/Type/IsGenericParameter/source.cs
@@ -1,19 +1,17 @@
//
using System;
-using System.Reflection;
+
using System.Collections.Generic;
public class Test
{
private static void DisplayGenericTypeInfo(Type t)
{
- Console.WriteLine("\r\n{0}", t);
+ Console.WriteLine($"\r\n{t}");
- Console.WriteLine("\tIs this a generic type definition? {0}",
- t.IsGenericTypeDefinition);
+ Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}");
- Console.WriteLine("\tIs it a generic type? {0}",
- t.IsGenericType);
+ Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}");
//
if (t.IsGenericType)
@@ -22,8 +20,7 @@ private static void DisplayGenericTypeInfo(Type t)
//
Type[] typeArguments = t.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):",
- typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
@@ -32,13 +29,11 @@ private static void DisplayGenericTypeInfo(Type t)
//
if (tParam.IsGenericParameter)
{
- Console.WriteLine("\t\t{0}\t(unassigned - parameter position {1})",
- tParam,
- tParam.GenericParameterPosition);
+ Console.WriteLine($"\t\t{tParam}\t(unassigned - parameter position {tParam.GenericParameterPosition})");
}
else
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
@@ -51,8 +46,8 @@ public static void Main()
Console.WriteLine(" generic type definition, and an ordinary type.");
// Create a Dictionary of Test objects, using strings for the
- // keys.
- Dictionary d = new Dictionary();
+ // keys.
+ Dictionary d = new();
// Display information for the constructed type and its generic
// type definition.
diff --git a/snippets/csharp/System/Type/IsGenericType/Program.cs b/snippets/csharp/System/Type/IsGenericType/Program.cs
new file mode 100644
index 00000000000..dd1327fdd6d
--- /dev/null
+++ b/snippets/csharp/System/Type/IsGenericType/Program.cs
@@ -0,0 +1,2 @@
+IsGenericTypeRemarksExample.Run();
+IsGenericTypeSourceExample.Run();
diff --git a/snippets/csharp/System/Type/IsGenericType/Project.csproj b/snippets/csharp/System/Type/IsGenericType/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Type/IsGenericType/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Type/IsGenericType/remarks.cs b/snippets/csharp/System/Type/IsGenericType/remarks.cs
index bfa44897d58..ec533145f53 100644
--- a/snippets/csharp/System/Type/IsGenericType/remarks.cs
+++ b/snippets/csharp/System/Type/IsGenericType/remarks.cs
@@ -1,22 +1,22 @@
-using System;
-using System.Reflection;
+
+
//
-public class Base {}
+public class RemarksBase { }
-public class Derived : Base
+public class RemarksDerived : RemarksBase
{
- public G> F;
+ public RemarksG> F;
- public class Nested {}
+ public class Nested { }
}
-public class G {}
+public class RemarksG { }
//
-class Example
+class IsGenericTypeRemarksExample
{
- public static void Main()
+ public static void Run()
{
}
-}
\ No newline at end of file
+}
diff --git a/snippets/csharp/System/Type/IsGenericType/source.cs b/snippets/csharp/System/Type/IsGenericType/source.cs
index da802f2948b..a2b5dc7a56f 100644
--- a/snippets/csharp/System/Type/IsGenericType/source.cs
+++ b/snippets/csharp/System/Type/IsGenericType/source.cs
@@ -1,21 +1,21 @@
//
using System;
-using System.Reflection;
-public class Base {}
+
+public class Base { }
public class Derived : Base
{
- public G> F;
+ public G> F;
- public class Nested {}
+ public class Nested { }
}
-public class G {}
+public class G { }
-class Example
+class IsGenericTypeSourceExample
{
- public static void Main()
+ public static void Run()
{
// Get the generic type definition for Derived, and the base
// type for Derived.
@@ -48,17 +48,13 @@ public static void Main()
public static void DisplayGenericType(Type t, string caption)
{
- Console.WriteLine("\n{0}", caption);
- Console.WriteLine(" Type: {0}", t);
-
- Console.WriteLine("\t IsGenericType: {0}",
- t.IsGenericType);
- Console.WriteLine("\t IsGenericTypeDefinition: {0}",
- t.IsGenericTypeDefinition);
- Console.WriteLine("\tContainsGenericParameters: {0}",
- t.ContainsGenericParameters);
- Console.WriteLine("\t IsGenericParameter: {0}",
- t.IsGenericParameter);
+ Console.WriteLine($"\n{caption}");
+ Console.WriteLine($" Type: {t}");
+
+ Console.WriteLine($"\t IsGenericType: {t.IsGenericType}");
+ Console.WriteLine($"\t IsGenericTypeDefinition: {t.IsGenericTypeDefinition}");
+ Console.WriteLine($"\tContainsGenericParameters: {t.ContainsGenericParameters}");
+ Console.WriteLine($"\t IsGenericParameter: {t.IsGenericParameter}");
}
}
diff --git a/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs b/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs
index 580f0dd5afa..04423ff0798 100644
--- a/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs
+++ b/snippets/csharp/System/Type/IsInstanceOfType/testisinstanceoftype.cs
@@ -1,11 +1,11 @@
//
using System;
-public interface IExample {}
+public interface IExample { }
-public class BaseClass : IExample {}
+public class BaseClass : IExample { }
-public class DerivedClass : BaseClass {}
+public class DerivedClass : BaseClass { }
public class Example
{
@@ -18,16 +18,11 @@ public static void Main()
var derived1Type = derived1.GetType();
int[] arr = new int[11];
- Console.WriteLine("Is int[] an instance of the Array class? {0}.",
- typeof(Array).IsInstanceOfType(arr));
- Console.WriteLine("Is base1 an instance of BaseClass? {0}.",
- base1Type.IsInstanceOfType(base1));
- Console.WriteLine("Is derived1 an instance of BaseClass? {0}.",
- base1Type.IsInstanceOfType(derived1));
- Console.WriteLine("Is base1 an instance of IExample? {0}.",
- interfaceType.IsInstanceOfType(base1));
- Console.WriteLine("Is derived1 an instance of IExample? {0}.",
- interfaceType.IsInstanceOfType(derived1));
+ Console.WriteLine($"Is int[] an instance of the Array class? {typeof(Array).IsInstanceOfType(arr)}.");
+ Console.WriteLine($"Is base1 an instance of BaseClass? {base1Type.IsInstanceOfType(base1)}.");
+ Console.WriteLine($"Is derived1 an instance of BaseClass? {base1Type.IsInstanceOfType(derived1)}.");
+ Console.WriteLine($"Is base1 an instance of IExample? {interfaceType.IsInstanceOfType(base1)}.");
+ Console.WriteLine($"Is derived1 an instance of IExample? {interfaceType.IsInstanceOfType(derived1)}.");
}
}
// The example displays the following output:
@@ -36,4 +31,4 @@ public static void Main()
// Is derived1 an instance of BaseClass? True.
// Is base1 an instance of IExample? True.
// Is derived1 an instance of IExample? True.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsInterface/type_isinterface.cs b/snippets/csharp/System/Type/IsInterface/type_isinterface.cs
index 555886437f5..da7ae8eca29 100644
--- a/snippets/csharp/System/Type/IsInterface/type_isinterface.cs
+++ b/snippets/csharp/System/Type/IsInterface/type_isinterface.cs
@@ -6,22 +6,22 @@ interface myIFace
}
class MyIsInterface
{
- public static void Main(string []args)
+ public static void Main(string[] args)
{
try
{
// Get the IsInterface attribute for myIFace.
bool myBool1 = typeof(myIFace).IsInterface;
//Display the IsInterface attribute for myIFace.
- Console.WriteLine("Is the specified type an interface? {0}.", myBool1);
+ Console.WriteLine($"Is the specified type an interface? {myBool1}.");
// Get the attribute IsInterface for MyIsInterface.
bool myBool2 = typeof(MyIsInterface).IsInterface;
//Display the IsInterface attribute for MyIsInterface.
- Console.WriteLine("Is the specified type an interface? {0}.", myBool2);
+ Console.WriteLine($"Is the specified type an interface? {myBool2}.");
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("\nAn exception occurred: {0}.", e.Message);
+ Console.WriteLine($"\nAn exception occurred: {e.Message}.");
}
}
}
@@ -30,4 +30,4 @@ public static void Main(string []args)
Is the specified type an interface? True.
Is the specified type an interface? False.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs b/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs
index 1b37af41198..efb0c46cf9f 100644
--- a/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs
+++ b/snippets/csharp/System/Type/IsLayoutSequential/type_islayoutsequential.cs
@@ -1,7 +1,7 @@
//
using System;
-using System.Reflection;
-using System.ComponentModel;
+
+
using System.Runtime.InteropServices;
class MyTypeSequential1
{
@@ -9,24 +9,24 @@ class MyTypeSequential1
[StructLayoutAttribute(LayoutKind.Sequential)]
class MyTypeSequential2
{
- public static void Main(string []args)
+ public static void Main(string[] args)
{
try
{
// Create an instance of myTypeSeq1.
- MyTypeSequential1 myObj1 = new MyTypeSequential1();
+ MyTypeSequential1 myObj1 = new();
Type myTypeObj1 = myObj1.GetType();
// Check for and display the SequentialLayout attribute.
- Console.WriteLine("\nThe object myObj1 has IsLayoutSequential: {0}.", myObj1.GetType().IsLayoutSequential);
+ Console.WriteLine($"\nThe object myObj1 has IsLayoutSequential: {myObj1.GetType().IsLayoutSequential}.");
// Create an instance of 'myTypeSeq2' class.
- MyTypeSequential2 myObj2 = new MyTypeSequential2();
+ MyTypeSequential2 myObj2 = new();
Type myTypeObj2 = myObj2.GetType();
// Check for and display the SequentialLayout attribute.
- Console.WriteLine("\nThe object myObj2 has IsLayoutSequential: {0}.", myObj2.GetType().IsLayoutSequential);
+ Console.WriteLine($"\nThe object myObj2 has IsLayoutSequential: {myObj2.GetType().IsLayoutSequential}.");
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("\nAn exception occurred: {0}", e.Message);
+ Console.WriteLine($"\nAn exception occurred: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs b/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs
index 02eb5237740..1a46e14a2a4 100644
--- a/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs
+++ b/snippets/csharp/System/Type/IsMarshalByRefImpl/type_ismarshalbyrefimpl.cs
@@ -4,16 +4,13 @@
public class MyTypeDelegatorClass : TypeDelegator
{
public string myElementType = null;
- private Type myType = null ;
- public MyTypeDelegatorClass(Type myType) : base(myType)
- {
- this.myType = myType;
- }
+ private Type myType = null;
+ public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType;
// Override IsMarshalByRefImpl.
protected override bool IsMarshalByRefImpl()
{
// Determine whether the type is marshalled by reference.
- if(myType.IsMarshalByRef)
+ if (myType.IsMarshalByRef)
{
myElementType = " marshalled by reference";
return true;
@@ -28,10 +25,10 @@ public static void Main()
try
{
MyTypeDelegatorClass myType;
- Console.WriteLine ("Determine whether MyContextBoundClass is marshalled by reference.");
+ Console.WriteLine("Determine whether MyContextBoundClass is marshalled by reference.");
// Determine whether MyContextBoundClass type is marshalled by reference.
- myType = new MyTypeDelegatorClass(typeof(MyContextBoundClass));
- if( myType.IsMarshalByRef )
+ myType = new(typeof(MyContextBoundClass));
+ if (myType.IsMarshalByRef)
{
Console.WriteLine(typeof(MyContextBoundClass) + " is marshalled by reference.");
}
@@ -41,9 +38,9 @@ public static void Main()
}
// Determine whether int type is marshalled by reference.
- myType = new MyTypeDelegatorClass(typeof(int));
- Console.WriteLine ("\nDetermine whether int is marshalled by reference.");
- if( myType.IsMarshalByRef)
+ myType = new(typeof(int));
+ Console.WriteLine("\nDetermine whether int is marshalled by reference.");
+ if (myType.IsMarshalByRef)
{
Console.WriteLine(typeof(int) + " is marshalled by reference.");
}
@@ -52,9 +49,9 @@ public static void Main()
Console.WriteLine(typeof(int) + " is not marshalled by reference.");
}
}
- catch( Exception e )
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message);
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
diff --git a/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs b/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs
index 46513f3d2d6..ef1cedea827 100644
--- a/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs
+++ b/snippets/csharp/System/Type/IsNested/isnestedfamilyandassembly1.cs
@@ -5,41 +5,42 @@
public class OuterClass
{
private class PrivateClass
- {}
+ { }
protected class ProtectedClass
- {}
+ { }
internal class InternalClass
- {}
+ { }
protected internal class ProtectedInternalClass
- {}
+ { }
public class PublicClass
- {}
+ { }
public static void Main()
{
// Create an array of Type objects for all the classes.
- Type[] types = { typeof(OuterClass),
- typeof(OuterClass.PublicClass),
- typeof(OuterClass.PrivateClass),
- typeof(OuterClass.ProtectedClass),
- typeof(OuterClass.InternalClass),
- typeof(OuterClass.ProtectedInternalClass) };
+ Type[] types = [typeof(OuterClass),
+ typeof(OuterClass.PublicClass),
+ typeof(OuterClass.PrivateClass),
+ typeof(OuterClass.ProtectedClass),
+ typeof(OuterClass.InternalClass),
+ typeof(OuterClass.ProtectedInternalClass)];
// Display the property values of each nested class.
- foreach (var type in types) {
- Console.WriteLine("\n{0} property values:", type.Name);
- Console.WriteLine(" Public Class: {0}", type.IsPublic);
- Console.WriteLine(" Not a Public Class: {0}", type.IsNotPublic);
- Console.WriteLine(" Nested Class: {0}", type.IsNested);
- Console.WriteLine(" Nested Private Class: {0}", type.IsNestedPrivate);
- Console.WriteLine(" Nested Internal Class: {0}", type.IsNestedAssembly);
- Console.WriteLine(" Nested Protected Class: {0}", type.IsNestedFamily);
- Console.WriteLine(" Nested Family Or Assembly Class: {0}", type.IsNestedFamORAssem);
- Console.WriteLine(" Nested Family And Assembly Class: {0}", type.IsNestedFamANDAssem);
- Console.WriteLine(" Nested Public Class: {0}", type.IsNestedPublic);
+ foreach (var type in types)
+ {
+ Console.WriteLine($"\n{type.Name} property values:");
+ Console.WriteLine($" Public Class: {type.IsPublic}");
+ Console.WriteLine($" Not a Public Class: {type.IsNotPublic}");
+ Console.WriteLine($" Nested Class: {type.IsNested}");
+ Console.WriteLine($" Nested Private Class: {type.IsNestedPrivate}");
+ Console.WriteLine($" Nested Internal Class: {type.IsNestedAssembly}");
+ Console.WriteLine($" Nested Protected Class: {type.IsNestedFamily}");
+ Console.WriteLine($" Nested Family Or Assembly Class: {type.IsNestedFamORAssem}");
+ Console.WriteLine($" Nested Family And Assembly Class: {type.IsNestedFamANDAssem}");
+ Console.WriteLine($" Nested Public Class: {type.IsNestedPublic}");
}
}
}
@@ -109,4 +110,4 @@ public static void Main()
// Nested Family Or Assembly Class: True
// Nested Family And Assembly Class: False
// Nested Public Class: False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsNotPublic/source.cs b/snippets/csharp/System/Type/IsNotPublic/source.cs
index 2076d9f9ff1..7f12663f242 100644
--- a/snippets/csharp/System/Type/IsNotPublic/source.cs
+++ b/snippets/csharp/System/Type/IsNotPublic/source.cs
@@ -1,6 +1,6 @@
//
using System;
-using System.IO;
+
using System.Reflection;
class Example
@@ -11,10 +11,8 @@ public static void Main()
Type t = Type.GetType("System.IO.File");
MemberInfo[] members = t.GetMembers();
// Get and display the DeclaringType method.
- Console.WriteLine("\nThere are {0} members in {1}.",
- members.Length, t.FullName);
- Console.WriteLine("Is {0} non-public? {1}",
- t.FullName, t.IsNotPublic);
+ Console.WriteLine($"\nThere are {members.Length} members in {t.FullName}.");
+ Console.WriteLine($"Is {t.FullName} non-public? {t.IsNotPublic}");
}
}
// The example displays output like the following:
diff --git a/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs b/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs
index 9dd4c38e560..9d4072cffe3 100644
--- a/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs
+++ b/snippets/csharp/System/Type/IsPrimitiveImpl/type_isprimitiveimpl.cs
@@ -4,16 +4,13 @@
public class MyTypeDelegatorClass : TypeDelegator
{
public string myElementType = null;
- private Type myType = null ;
- public MyTypeDelegatorClass(Type myType) : base(myType)
- {
- this.myType = myType;
- }
+ private Type myType = null;
+ public MyTypeDelegatorClass(Type myType) : base(myType) => this.myType = myType;
// Override the IsPrimitiveImpl.
protected override bool IsPrimitiveImpl()
{
// Determine whether the type is a primitive type.
- if(myType.IsPrimitive)
+ if (myType.IsPrimitive)
{
myElementType = "primitive";
return true;
@@ -27,11 +24,11 @@ public static void Main()
{
try
{
- Console.WriteLine ("Determine whether int is a primitive type.");
+ Console.WriteLine("Determine whether int is a primitive type.");
MyTypeDelegatorClass myType;
- myType = new MyTypeDelegatorClass(typeof(int));
+ myType = new(typeof(int));
// Determine whether int is a primitive type.
- if( myType.IsPrimitive)
+ if (myType.IsPrimitive)
{
Console.WriteLine(typeof(int) + " is a primitive type.");
}
@@ -39,10 +36,10 @@ public static void Main()
{
Console.WriteLine(typeof(int) + " is not a primitive type.");
}
- Console.WriteLine ("\nDetermine whether string is a primitive type.");
- myType = new MyTypeDelegatorClass(typeof(string));
+ Console.WriteLine("\nDetermine whether string is a primitive type.");
+ myType = new(typeof(string));
// Determine if string is a primitive type.
- if( myType.IsPrimitive)
+ if (myType.IsPrimitive)
{
Console.WriteLine(typeof(string) + " is a primitive type.");
}
@@ -51,10 +48,10 @@ public static void Main()
Console.WriteLine(typeof(string) + " is not a primitive type.");
}
}
- catch( Exception e )
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message);
+ Console.WriteLine($"Exception: {e.Message}");
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsPublic/type_ispublic.cs b/snippets/csharp/System/Type/IsPublic/type_ispublic.cs
index 40c87ffc257..ad92c0f08e9 100644
--- a/snippets/csharp/System/Type/IsPublic/type_ispublic.cs
+++ b/snippets/csharp/System/Type/IsPublic/type_ispublic.cs
@@ -7,15 +7,15 @@ public class TestClass
public class Example
{
- public static void Main()
- {
- TestClass testClassInstance = new TestClass();
- // Get the type of myTestClassInstance.
- Type testType = testClassInstance.GetType();
- // Get the IsPublic property of testClassInstance.
- bool isPublic = testType.IsPublic;
- Console.WriteLine("Is {0} public? {1}", testType.FullName, isPublic);
- }
+ public static void Main()
+ {
+ TestClass testClassInstance = new();
+ // Get the type of myTestClassInstance.
+ Type testType = testClassInstance.GetType();
+ // Get the IsPublic property of testClassInstance.
+ bool isPublic = testType.IsPublic;
+ Console.WriteLine($"Is {testType.FullName} public? {isPublic}");
+ }
}
// The example displays the following output:
// Is TestClass public? True
diff --git a/snippets/csharp/System/Type/IsSealed/type_issealed.cs b/snippets/csharp/System/Type/IsSealed/type_issealed.cs
index 90ddf688fc3..587338a1280 100644
--- a/snippets/csharp/System/Type/IsSealed/type_issealed.cs
+++ b/snippets/csharp/System/Type/IsSealed/type_issealed.cs
@@ -1,23 +1,23 @@
//
using System;
- public class Example
- {
- // Declare InnerClass as sealed.
- sealed public class InnerClass
- {
- }
+public class Example
+{
+ // Declare InnerClass as sealed.
+ sealed public class InnerClass
+ {
+ }
- public static void Main()
- {
- InnerClass inner = new InnerClass();
- // Get the type of InnerClass.
- Type innerType = inner.GetType();
- // Get the IsSealed property of innerClass.
- bool isSealed = innerType.IsSealed;
- Console.WriteLine("{0} is sealed: {1}.", innerType.FullName, isSealed);
- }
+ public static void Main()
+ {
+ InnerClass inner = new();
+ // Get the type of InnerClass.
+ Type innerType = inner.GetType();
+ // Get the IsSealed property of innerClass.
+ bool isSealed = innerType.IsSealed;
+ Console.WriteLine($"{innerType.FullName} is sealed: {isSealed}.");
+ }
}
// The example displays the following output:
// Example+InnerClass is sealed: True.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs b/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs
index 37ff4c1c38c..eecfa854b24 100644
--- a/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs
+++ b/snippets/csharp/System/Type/IsSubclassOf/issubclassof_interface1.cs
@@ -3,28 +3,23 @@
public interface IInterface
{
- void Display();
+ void Display();
}
public class Implementation : IInterface
{
- public void Display()
- {
- Console.WriteLine("The implementation...");
- }
+ public void Display() => Console.WriteLine("The implementation...");
}
public class Example
{
- public static void Main()
- {
- Console.WriteLine("Implementation is a subclass of IInterface: {0}",
- typeof(Implementation).IsSubclassOf(typeof(IInterface)));
- Console.WriteLine("IInterface is assignable from Implementation: {0}",
- typeof(IInterface).IsAssignableFrom(typeof(Implementation)));
- }
+ public static void Main()
+ {
+ Console.WriteLine($"Implementation is a subclass of IInterface: {typeof(Implementation).IsSubclassOf(typeof(IInterface))}");
+ Console.WriteLine($"IInterface is assignable from Implementation: {typeof(IInterface).IsAssignableFrom(typeof(Implementation))}");
+ }
}
// The example displays the following output:
// Implementation is a subclass of IInterface: False
// IInterface is assignable from Implementation: True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs b/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs
index 24d67175f8c..45b923c27ac 100644
--- a/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs
+++ b/snippets/csharp/System/Type/IsSubclassOf/testissubclassof.cs
@@ -6,12 +6,8 @@ public class DerivedC1 : Class1 { }
class IsSubclassTest
{
- public static void Main()
- {
- Console.WriteLine("DerivedC1 subclass of Class1: {0}",
- typeof(DerivedC1).IsSubclassOf(typeof(Class1)));
- }
+ public static void Main() => Console.WriteLine($"DerivedC1 subclass of Class1: {typeof(DerivedC1).IsSubclassOf(typeof(Class1))}");
}
// The example displays the following output:
// DerivedC1 subclass of Class1: True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs b/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs
index 79ba552d617..07c9ff64260 100644
--- a/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs
+++ b/snippets/csharp/System/Type/IsValueType/type_isvaluetype.cs
@@ -7,7 +7,7 @@ enum NumEnum { One, Two }
public class Example
{
- public static void Main(string []args)
+ public static void Main(string[] args)
{
bool flag = false;
NumEnum testEnum = NumEnum.One;
@@ -15,7 +15,7 @@ public static void Main(string []args)
Type t = testEnum.GetType();
// Get the IsValueType property of the testEnum variable.
flag = t.IsValueType;
- Console.WriteLine("{0} is a value type: {1}", t.FullName, flag);
+ Console.WriteLine($"{t.FullName} is a value type: {flag}");
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/Type/IsVisible/source.cs b/snippets/csharp/System/Type/IsVisible/source.cs
index 66278859ddc..39fc211220f 100644
--- a/snippets/csharp/System/Type/IsVisible/source.cs
+++ b/snippets/csharp/System/Type/IsVisible/source.cs
@@ -1,30 +1,22 @@
//
using System;
-internal class InternalOnly
+internal class InternalOnly
{
- public class Nested {}
+ public class Nested { }
}
public class Example
{
- public class Nested {}
+ public class Nested { }
public static void Main()
{
Type t = typeof(InternalOnly.Nested);
- Console.WriteLine(
- "Is the {0} class visible outside the assembly? {1}",
- t.FullName,
- t.IsVisible
- );
+ Console.WriteLine($"Is the {t.FullName} class visible outside the assembly? {t.IsVisible}");
t = typeof(Example.Nested);
- Console.WriteLine(
- "Is the {0} class visible outside the assembly? {1}",
- t.FullName,
- t.IsVisible
- );
+ Console.WriteLine($"Is the {t.FullName} class visible outside the assembly? {t.IsVisible}");
}
}
diff --git a/snippets/csharp/System/Type/MakeByRefType/source.cs b/snippets/csharp/System/Type/MakeByRefType/source.cs
index 7a9ee920685..d58029186c5 100644
--- a/snippets/csharp/System/Type/MakeByRefType/source.cs
+++ b/snippets/csharp/System/Type/MakeByRefType/source.cs
@@ -9,12 +9,12 @@ public static void Main()
// Create a Type object that represents a one-dimensional
// array of Example objects.
Type t = typeof(Example).MakeArrayType();
- Console.WriteLine("\r\nArray of Example: {0}", t);
+ Console.WriteLine($"\r\nArray of Example: {t}");
// Create a Type object that represents a two-dimensional
// array of Example objects.
t = typeof(Example).MakeArrayType(2);
- Console.WriteLine("\r\nTwo-dimensional array of Example: {0}", t);
+ Console.WriteLine($"\r\nTwo-dimensional array of Example: {t}");
// Demonstrate an exception when an invalid array rank is
// specified.
@@ -22,15 +22,15 @@ public static void Main()
{
t = typeof(Example).MakeArrayType(-1);
}
- catch(Exception ex)
+ catch (Exception ex)
{
- Console.WriteLine("\r\n{0}", ex);
+ Console.WriteLine($"\r\n{ex}");
}
// Create a Type object that represents a ByRef parameter
// of type Example.
t = typeof(Example).MakeByRefType();
- Console.WriteLine("\r\nByRef Example: {0}", t);
+ Console.WriteLine($"\r\nByRef Example: {t}");
// Get a Type object representing the Example class, a
// MethodInfo representing the "Test" method, a ParameterInfo
@@ -42,12 +42,12 @@ public static void Main()
MethodInfo mi = t2.GetMethod("Test");
ParameterInfo pi = mi.GetParameters()[0];
Type pt = pi.ParameterType;
- Console.WriteLine("Are the ByRef types equal? {0}", (t == pt));
+ Console.WriteLine($"Are the ByRef types equal? {(t == pt)}");
// Create a Type object that represents a pointer to an
// Example object.
t = typeof(Example).MakePointerType();
- Console.WriteLine("\r\nPointer to Example: {0}", t);
+ Console.WriteLine($"\r\nPointer to Example: {t}");
}
// A sample method with a ByRef parameter.
diff --git a/snippets/csharp/System/Type/MakeGenericType/remarks.cs b/snippets/csharp/System/Type/MakeGenericType/remarks.cs
index a9f8c04adb2..a6e7734a444 100644
--- a/snippets/csharp/System/Type/MakeGenericType/remarks.cs
+++ b/snippets/csharp/System/Type/MakeGenericType/remarks.cs
@@ -1,4 +1,4 @@
-using System;
+
//
public class Base { }
@@ -10,13 +10,13 @@ public class Outermost
{
public class Inner
{
- public class Innermost1 {}
- public class Innermost2 {}
+ public class Innermost1 { }
+ public class Innermost2 { }
}
}
//
class ProgStubClass
{
- public static void Main() {}
-}
\ No newline at end of file
+ public static void Main() { }
+}
diff --git a/snippets/csharp/System/Type/MakeGenericType/source.cs b/snippets/csharp/System/Type/MakeGenericType/source.cs
index 38ecc20de1c..357c5c9b176 100644
--- a/snippets/csharp/System/Type/MakeGenericType/source.cs
+++ b/snippets/csharp/System/Type/MakeGenericType/source.cs
@@ -1,6 +1,6 @@
//
using System;
-using System.Reflection;
+
using System.Collections.Generic;
public class Test
@@ -9,17 +9,17 @@ public static void Main()
{
Console.WriteLine("\r\n--- Create a constructed type from the generic Dictionary type.");
- // Create a type object representing the generic Dictionary
- // type, by omitting the type arguments (but keeping the
+ // Create a type object representing the generic Dictionary
+ // type, by omitting the type arguments (but keeping the
// comma that separates them, so the compiler can infer the
- // number of type parameters).
+ // number of type parameters).
Type generic = typeof(Dictionary<,>);
DisplayTypeInfo(generic);
// Create an array of types to substitute for the type
// parameters of Dictionary. The key is of type string, and
// the type to be contained in the Dictionary is Test.
- Type[] typeArgs = { typeof(string), typeof(Test) };
+ Type[] typeArgs = [typeof(string), typeof(Test)];
// Create a Type object representing the constructed generic
// type.
@@ -30,27 +30,24 @@ public static void Main()
// obtained using typeof() and GetGenericTypeDefinition().
Console.WriteLine("\r\n--- Compare types obtained by different methods:");
- Type t = typeof(Dictionary);
- Console.WriteLine("\tAre the constructed types equal? {0}", t == constructed);
- Console.WriteLine("\tAre the generic types equal? {0}",
- t.GetGenericTypeDefinition() == generic);
+ Type t = typeof(Dictionary);
+ Console.WriteLine($"\tAre the constructed types equal? {t == constructed}");
+ Console.WriteLine($"\tAre the generic types equal? {t.GetGenericTypeDefinition() == generic}");
}
private static void DisplayTypeInfo(Type t)
{
- Console.WriteLine("\r\n{0}", t);
+ Console.WriteLine($"\r\n{t}");
- Console.WriteLine("\tIs this a generic type definition? {0}",
- t.IsGenericTypeDefinition);
+ Console.WriteLine($"\tIs this a generic type definition? {t.IsGenericTypeDefinition}");
- Console.WriteLine("\tIs it a generic type? {0}",
- t.IsGenericType);
+ Console.WriteLine($"\tIs it a generic type? {t.IsGenericType}");
Type[] typeArguments = t.GetGenericArguments();
- Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
+ Console.WriteLine($"\tList type arguments ({typeArguments.Length}):");
foreach (Type tParam in typeArguments)
{
- Console.WriteLine("\t\t{0}", tParam);
+ Console.WriteLine($"\t\t{tParam}");
}
}
}
diff --git a/snippets/csharp/System/Type/Missing/Project.csproj b/snippets/csharp/System/Type/Missing/Project.csproj
new file mode 100644
index 00000000000..fca009c3149
--- /dev/null
+++ b/snippets/csharp/System/Type/Missing/Project.csproj
@@ -0,0 +1,9 @@
+
+
+ Exe
+ net10.0
+
+
+
+
+
diff --git a/snippets/csharp/System/Type/Missing/source.cs b/snippets/csharp/System/Type/Missing/source.cs
index 76b60861815..4f718aac1fd 100644
--- a/snippets/csharp/System/Type/Missing/source.cs
+++ b/snippets/csharp/System/Type/Missing/source.cs
@@ -27,9 +27,9 @@ public static void Main()
BindingFlags bf = BindingFlags.Public | BindingFlags.Instance |
BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding;
- t.InvokeMember("MyMethod", bf, null, o, new object[] {10, 55.3, 12});
- t.InvokeMember("MyMethod", bf, null, o, new object[] {10, 1.3, Type.Missing});
- t.InvokeMember("MyMethod", bf, null, o, new object[] {10, Type.Missing, Type.Missing});
+ t.InvokeMember("MyMethod", bf, null, o, [10, 55.3, 12]);
+ t.InvokeMember("MyMethod", bf, null, o, [10, 1.3, Type.Missing]);
+ t.InvokeMember("MyMethod", bf, null, o, [10, Type.Missing, Type.Missing]);
}
private static object GenerateObjectFromSource(string objectName,
@@ -37,10 +37,11 @@ private static object GenerateObjectFromSource(string objectName,
{
object genObject = null;
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider(providerName);
- CompilerParameters cp = new CompilerParameters();
-
- cp.GenerateExecutable = false;
- cp.GenerateInMemory = true;
+ CompilerParameters cp = new()
+ {
+ GenerateExecutable = false,
+ GenerateInMemory = true
+ };
CompilerResults results =
codeProvider.CompileAssemblyFromSource(cp, sourceLines);
@@ -52,4 +53,4 @@ private static object GenerateObjectFromSource(string objectName,
return genObject;
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Type/Module/type_tostring.cs b/snippets/csharp/System/Type/Module/type_tostring.cs
index fe2b9678d35..842d6a8883c 100644
--- a/snippets/csharp/System/Type/Module/type_tostring.cs
+++ b/snippets/csharp/System/Type/Module/type_tostring.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
namespace MyNamespace
@@ -12,14 +12,14 @@ public class Example
{
public static void Main()
{
- Type myType = typeof(MyNamespace.MyClass);
- Console.WriteLine("Displaying information about {0}:", myType);
- // Get the namespace of the myClass class.
- Console.WriteLine(" Namespace: {0}.", myType.Namespace);
- // Get the name of the module.
- Console.WriteLine(" Module: {0}.", myType.Module);
- // Get the fully qualified type name.
- Console.WriteLine(" Fully qualified name: {0}.", myType.ToString());
+ Type myType = typeof(MyNamespace.MyClass);
+ Console.WriteLine($"Displaying information about {myType}:");
+ // Get the namespace of the myClass class.
+ Console.WriteLine($" Namespace: {myType.Namespace}.");
+ // Get the name of the module.
+ Console.WriteLine($" Module: {myType.Module}.");
+ // Get the fully qualified type name.
+ Console.WriteLine($" Fully qualified name: {myType}.");
}
}
// The example displays the following output:
@@ -27,4 +27,4 @@ public static void Main()
// Namespace: MyNamespace.
// Module: type_tostring.exe.
// Fully qualified name: MyNamespace.MyClass.
-//
+//
diff --git a/snippets/csharp/System/Type/Overview/Equals1.cs b/snippets/csharp/System/Type/Overview/Equals1.cs
index e3a44d20d3f..ea5f7fc2644 100644
--- a/snippets/csharp/System/Type/Overview/Equals1.cs
+++ b/snippets/csharp/System/Type/Overview/Equals1.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
public class Example1
{
@@ -14,9 +14,9 @@ public static void Main()
Type t = number1.GetType();
// Compare types of all objects with number1.
- Console.WriteLine($"Type of number1 and number2 are equal: {Object.ReferenceEquals(t, number2.GetType())}");
- Console.WriteLine($"Type of number1 and number3 are equal: {Object.ReferenceEquals(t, number3.GetType())}");
- Console.WriteLine($"Type of number1 and number4 are equal: {Object.ReferenceEquals(t, number4.GetType())}");
+ Console.WriteLine($"Type of number1 and number2 are equal: {object.ReferenceEquals(t, number2.GetType())}");
+ Console.WriteLine($"Type of number1 and number3 are equal: {object.ReferenceEquals(t, number3.GetType())}");
+ Console.WriteLine($"Type of number1 and number4 are equal: {object.ReferenceEquals(t, number4.GetType())}");
// The example displays the following output:
// Type of number1 and number2 are equal: False
diff --git a/snippets/csharp/System/Type/Overview/GetType1.cs b/snippets/csharp/System/Type/Overview/GetType1.cs
index ecf2365b6d1..9bb0daa8f7e 100644
--- a/snippets/csharp/System/Type/Overview/GetType1.cs
+++ b/snippets/csharp/System/Type/Overview/GetType1.cs
@@ -1,12 +1,12 @@
-using System;
+using System;
public class Example2
{
public static void Main()
{
//
- object[] values = { "word", true, 120, 136.34, 'a' };
- foreach (var value in values)
+ object[] values = ["word", true, 120, 136.34, 'a'];
+ foreach (object value in values)
Console.WriteLine($"{value} - type {value.GetType().Name}");
// The example displays the following output:
diff --git a/snippets/csharp/System/Type/Overview/source.cs b/snippets/csharp/System/Type/Overview/source.cs
index 2e479978b80..303403b32fd 100644
--- a/snippets/csharp/System/Type/Overview/source.cs
+++ b/snippets/csharp/System/Type/Overview/source.cs
@@ -9,14 +9,14 @@ class Example3
{
static void Main()
{
- Type t = typeof(String);
+ Type t = typeof(string);
MethodInfo substr = t.GetMethod("Substring",
- new Type[] { typeof(int), typeof(int) });
+ [typeof(int), typeof(int)]);
- Object result =
- substr.Invoke("Hello, World!", new Object[] { 7, 5 });
- Console.WriteLine("{0} returned \"{1}\".", substr, result);
+ object result =
+ substr.Invoke("Hello, World!", [7, 5]);
+ Console.WriteLine($"{substr} returned \"{result}\".");
}
}
diff --git a/snippets/csharp/System/Type/ReflectedType/source.cs b/snippets/csharp/System/Type/ReflectedType/source.cs
index bf060d9a664..fb57e57ee7a 100644
--- a/snippets/csharp/System/Type/ReflectedType/source.cs
+++ b/snippets/csharp/System/Type/ReflectedType/source.cs
@@ -1,6 +1,6 @@
//
using System;
-using System.Reflection;
+
public abstract class MyClassA
{
@@ -11,8 +11,7 @@ public abstract class MyClassB
public static void Main(string[] args)
{
- Console.WriteLine("Reflected type of MyClassB is {0}",
- typeof(MyClassB).ReflectedType); //outputs MyClassA, the enclosing class
+ Console.WriteLine($"Reflected type of MyClassB is {typeof(MyClassB).ReflectedType}"); //outputs MyClassA, the enclosing class
}
}
//
diff --git a/snippets/csharp/System/Type/StructLayoutAttribute/source.cs b/snippets/csharp/System/Type/StructLayoutAttribute/source.cs
index 6d97f7ca5cc..66a8afe89b8 100644
--- a/snippets/csharp/System/Type/StructLayoutAttribute/source.cs
+++ b/snippets/csharp/System/Type/StructLayoutAttribute/source.cs
@@ -11,17 +11,15 @@ public static void Main()
DisplayLayoutAttribute(typeof(Test2).StructLayoutAttribute);
}
- private static void DisplayLayoutAttribute(StructLayoutAttribute sla)
- {
- Console.WriteLine("\r\nCharSet: "+sla.CharSet.ToString()+"\r\n Pack: "+sla.Pack.ToString()+"\r\n Size: "+sla.Size.ToString()+"\r\n Value: "+sla.Value.ToString());
- }
+ private static void DisplayLayoutAttribute(StructLayoutAttribute sla) => Console.WriteLine("\r\nCharSet: " + sla.CharSet + "\r\n Pack: " + sla.Pack + "\r\n Size: " + sla.Size + "\r\n Value: " + sla.Value);
public struct Test1
{
public byte B1;
public short S;
public byte B2;
}
- [StructLayout(LayoutKind.Explicit, Pack=1)] public struct Test2
+ [StructLayout(LayoutKind.Explicit, Pack = 1)]
+ public struct Test2
{
[FieldOffset(0)] public byte B1;
[FieldOffset(1)] public short S;
diff --git a/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs b/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs
index b734d2c81a9..3c3fcad33a9 100644
--- a/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs
+++ b/snippets/csharp/System/Type/TypeHandle/type_typehandle.cs
@@ -1,6 +1,6 @@
-//
+//
using System;
-using System.Reflection;
+
class MyClass
{
public int myField = 10;
@@ -12,7 +12,7 @@ public static void Main()
{
try
{
- MyClass myClass = new MyClass();
+ MyClass myClass = new();
// Get the type of MyClass.
Type myClassType = myClass.GetType();
@@ -22,9 +22,9 @@ public static void Main()
DisplayTypeHandle(myClassHandle);
}
- catch(Exception e)
+ catch (Exception e)
{
- Console.WriteLine("Exception: {0}", e.Message );
+ Console.WriteLine($"Exception: {e.Message}");
}
}
@@ -34,7 +34,7 @@ public static void DisplayTypeHandle(RuntimeTypeHandle myTypeHandle)
Type myType = Type.GetTypeFromHandle(myTypeHandle);
// Display the type.
Console.WriteLine("\nDisplaying the type from the handle:\n");
- Console.WriteLine("The type is {0}.", myType.ToString());
+ Console.WriteLine($"The type is {myType}.");
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs b/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs
index b6d72e3e237..dd617df1297 100644
--- a/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs
+++ b/snippets/csharp/System/TypeInitializationException/Overview/Missing1.cs
@@ -5,7 +5,7 @@ public class MissingEx1
{
public static void Main()
{
- Person p = new Person("John", "Doe");
+ Person p = new("John", "Doe");
Console.WriteLine(p);
}
}
@@ -17,10 +17,7 @@ public class Person
readonly string _fName;
readonly string _lName;
- static Person()
- {
- s_infoModule = new InfoModule(DateTime.UtcNow);
- }
+ static Person() => s_infoModule = new(DateTime.UtcNow);
public Person(string fName, string lName)
{
@@ -29,16 +26,13 @@ public Person(string fName, string lName)
s_infoModule.Increment();
}
- public override string ToString()
- {
- return string.Format("{0} {1}", _fName, _lName);
- }
+ public override string ToString() => $"{_fName} {_lName}";
}
// The example displays the following output if missing1a.dll is renamed or removed:
-// Unhandled Exception: System.TypeInitializationException:
-// The type initializer for 'Person' threw an exception. --->
-// System.IO.FileNotFoundException: Could not load file or assembly
-// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
+// Unhandled Exception: System.TypeInitializationException:
+// The type initializer for 'Person' threw an exception. --->
+// System.IO.FileNotFoundException: Could not load file or assembly
+// 'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
// or one of its dependencies. The system cannot find the file specified.
// at Person..cctor()
// --- End of inner exception stack trace ---
diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs b/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs
index 56903779fba..cbefba5bd3b 100644
--- a/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs
+++ b/snippets/csharp/System/TypeInitializationException/Overview/Missing1a.cs
@@ -3,22 +3,13 @@
public class InfoModule
{
- private DateTime firstUse;
- private int ctr = 0;
+ private DateTime firstUse;
+ private int ctr = 0;
- public InfoModule(DateTime dat)
- {
- firstUse = dat;
- }
-
- public int Increment()
- {
- return ++ctr;
- }
-
- public DateTime GetInitializationTime()
- {
- return firstUse;
- }
+ public InfoModule(DateTime dat) => firstUse = dat;
+
+ public int Increment() => ++ctr;
+
+ public DateTime GetInitializationTime() => firstUse;
}
//
diff --git a/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs b/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs
index dfeda845b44..0a82b45d2ec 100644
--- a/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs
+++ b/snippets/csharp/System/TypeInitializationException/Overview/Regex1.cs
@@ -1,7 +1,7 @@
//
using System;
using System.Text.RegularExpressions;
-using static System.Net.Mime.MediaTypeNames;
+
public class RegexEx1
{
@@ -11,8 +11,8 @@ public static void Run()
// Set a timeout interval of -2 seconds.
domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2));
- Regex rgx = new Regex("[aeiouy]");
- Console.WriteLine($"Regular expression pattern: {rgx.ToString()}");
+ Regex rgx = new("[aeiouy]");
+ Console.WriteLine($"Regular expression pattern: {rgx}");
Console.WriteLine($"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds");
}
}
diff --git a/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs b/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs
index ac866e10443..4a0392148a4 100644
--- a/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs
+++ b/snippets/csharp/System/TypeInitializationException/Overview/ctorException1.cs
@@ -3,28 +3,28 @@
public class Example
{
- private static TestClass test = new TestClass(3);
-
- public static void Main()
- {
- Example ex = new Example();
- Console.WriteLine(test.Value);
- }
+ private static TestClass test = new(3);
+
+ public static void Main()
+ {
+ Example ex = new();
+ Console.WriteLine(test.Value);
+ }
}
public class TestClass
{
- public readonly int Value;
-
- public TestClass(int value)
- {
- if (value < 0 || value > 1) throw new ArgumentOutOfRangeException(nameof(value));
- Value = value;
- }
+ public readonly int Value;
+
+ public TestClass(int value)
+ {
+ if (value < 0 || value > 1) throw new ArgumentOutOfRangeException(nameof(value));
+ Value = value;
+ }
}
// The example displays the following output:
-// Unhandled Exception: System.TypeInitializationException:
-// The type initializer for 'Example' threw an exception. --->
+// Unhandled Exception: System.TypeInitializationException:
+// The type initializer for 'Example' threw an exception. --->
// System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
// at TestClass..ctor(Int32 value)
// at Example..cctor()
diff --git a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs
index b8b4effd96b..1cbe390c379 100644
--- a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs
+++ b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor2.cs
@@ -3,25 +3,27 @@
public class Example
{
- public static void Main()
- {
- try {
- // Call a method that throws an exception.
- TypeLoadExceptionDemoClass.GenerateException();
- }
- catch (TypeLoadException e) {
- Console.WriteLine("TypeLoadException:\n {0}", e.Message);
- }
- }
+ public static void Main()
+ {
+ try
+ {
+ // Call a method that throws an exception.
+ TypeLoadExceptionDemoClass.GenerateException();
+ }
+ catch (TypeLoadException e)
+ {
+ Console.WriteLine($"TypeLoadException:\n {e.Message}");
+ }
+ }
}
class TypeLoadExceptionDemoClass
{
- public static bool GenerateException()
- {
- // Throw a TypeLoadException with a custom defined message.
- throw new TypeLoadException("This is a custom TypeLoadException error message.");
- }
+ public static bool GenerateException()
+ {
+ // Throw a TypeLoadException with a custom defined message.
+ throw new TypeLoadException("This is a custom TypeLoadException error message.");
+ }
}
// The example displays the following output:
// TypeLoadException:
diff --git a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs
index 51589e8ee66..5bb423a9c2d 100644
--- a/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs
+++ b/snippets/csharp/System/TypeLoadException/.ctor/typeloadexception_constructor3.cs
@@ -12,42 +12,42 @@ as an inner exception.*/
public class TypeLoadException_Constructor3
{
- public static void Main()
- {
- Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.");
- try
- {
- TypeLoadExceptionDemoClass3.GenerateException();
- }
- catch (TypeLoadException e)
- {
- Console.WriteLine ("TypeLoadException: \n\tError Message = " + e.Message);
- Console.WriteLine ("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message );
- }
- catch (Exception e)
- {
- Console.WriteLine ("Exception: \n\tError Message = " + e.Message);
- }
- }
+ public static void Main()
+ {
+ Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.");
+ try
+ {
+ TypeLoadExceptionDemoClass3.GenerateException();
+ }
+ catch (TypeLoadException e)
+ {
+ Console.WriteLine("TypeLoadException: \n\tError Message = " + e.Message);
+ Console.WriteLine("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message);
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("Exception: \n\tError Message = " + e.Message);
+ }
+ }
}
class TypeLoadExceptionDemoClass3
{
- // A call to this method will raise a TypeLoadException.
- [DllImport("NonExistentDLL.DLL", EntryPoint="MethodNotExists")]
- public static extern void NonExistentMethod();
+ // A call to this method will raise a TypeLoadException.
+ [DllImport("NonExistentDLL.DLL", EntryPoint = "MethodNotExists")]
+ public static extern void NonExistentMethod();
- public static void GenerateException()
- {
- try
- {
- NonExistentMethod();
- }
- catch (TypeLoadException e)
- {
- // Rethrow exception with the exception as inner exception
- throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e);
- }
- }
+ public static void GenerateException()
+ {
+ try
+ {
+ NonExistentMethod();
+ }
+ catch (TypeLoadException e)
+ {
+ // Rethrow exception with the exception as inner exception
+ throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e);
+ }
+ }
}
//
diff --git a/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs b/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs
index 0a4080a9a92..bc3ff020e9e 100644
--- a/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs
+++ b/snippets/csharp/System/TypeLoadException/Message/typeloadexception_typename.cs
@@ -14,28 +14,27 @@ values are displayed.
public class TypeLoadException_TypeName
{
- public static void Main()
- {
- // Get a reference to the assembly mscorlib.dll, which is always
- // loaded. (System.String is defined in mscorlib.)
- Assembly mscorlib = typeof(string).Assembly;
+ public static void Main()
+ {
+ // Get a reference to the assembly mscorlib.dll, which is always
+ // loaded. (System.String is defined in mscorlib.)
+ Assembly mscorlib = typeof(string).Assembly;
- try
- {
- Console.WriteLine("Attempting to load a type that does not exist in mscorlib.");
- // The boolean parameter causes an exception to be thrown if the
- // type is not found.
- Type myType = mscorlib.GetType("System.NonExistentType", true);
- }
- catch (TypeLoadException ex)
- {
- // Display the name of the type that was not found, and the
- // exception message.
- Console.WriteLine("TypeLoadException was caught. Type = '{0}'.",
- ex.TypeName);
- Console.WriteLine("Error Message = '{0}'", ex.Message);
- }
- }
+ try
+ {
+ Console.WriteLine("Attempting to load a type that does not exist in mscorlib.");
+ // The boolean parameter causes an exception to be thrown if the
+ // type is not found.
+ Type myType = mscorlib.GetType("System.NonExistentType", true);
+ }
+ catch (TypeLoadException ex)
+ {
+ // Display the name of the type that was not found, and the
+ // exception message.
+ Console.WriteLine($"TypeLoadException was caught. Type = '{ex.TypeName}'.");
+ Console.WriteLine($"Error Message = '{ex.Message}'");
+ }
+ }
}
/*
This code example produces output similar to the following:
diff --git a/snippets/csharp/System/TypedReference/Overview/source.cs b/snippets/csharp/System/TypedReference/Overview/source.cs
index 412e3377f61..70684dc3408 100644
--- a/snippets/csharp/System/TypedReference/Overview/source.cs
+++ b/snippets/csharp/System/TypedReference/Overview/source.cs
@@ -3,18 +3,18 @@
class TypedReferenceArray
{
- public static void Main()
+ public static void Main()
+ {
+ try
{
- try
- {
-//
- Assembly.Load("mscorlib.dll").GetType("System.TypedReference[]");
-//
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.WriteLine(ex.StackTrace);
- }
- }
-}
\ No newline at end of file
+ //
+ Assembly.Load("mscorlib.dll").GetType("System.TypedReference[]");
+ //
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.Message);
+ Console.WriteLine(ex.StackTrace);
+ }
+ }
+}
From 529ac6d2f65d6e7645f494bc672c56c1f4fcb969 Mon Sep 17 00:00:00 2001
From: Genevieve Warren <24882762+gewarren@users.noreply.github.com>
Date: Fri, 14 Aug 2026 09:55:55 -0700
Subject: [PATCH 5/9] Modernize C# code snippets - System/T* (#12972)
---
.../Overview/threadsafe2a.cs | 10 +-
.../csharp/System/TimeSpan/.ctor/ctoriii.cs | 40 +-
.../csharp/System/TimeSpan/.ctor/ctoriiii.cs | 40 +-
.../csharp/System/TimeSpan/.ctor/ctoriiiii.cs | 44 +-
.../csharp/System/TimeSpan/.ctor/ctorl.cs | 46 +-
snippets/csharp/System/TimeSpan/Add/add1.cs | 52 +-
.../System/TimeSpan/Compare/compare1.cs | 28 +-
.../System/TimeSpan/CompareTo/comp_equal.cs | 56 +-
.../System/TimeSpan/CompareTo/cto_eq_obj.cs | 59 +-
.../csharp/System/TimeSpan/Days/properties.cs | 38 +-
.../System/TimeSpan/Duration/dura_nega_una.cs | 46 +-
.../FromDays/System.TimeSpan.FromMinutes.cs | 90 +--
.../System/TimeSpan/FromDays/fromdays.cs | 56 +-
.../System/TimeSpan/FromDays/fromhours.cs | 56 +-
.../System/TimeSpan/FromDays/frommillisec.cs | 54 +-
.../System/TimeSpan/FromDays/fromminutes.cs | 56 +-
.../System/TimeSpan/FromDays/fromseconds.cs | 56 +-
.../System/TimeSpan/FromDays/fromticks.cs | 54 +-
.../System/TimeSpan/GetHashCode/hashcode.cs | 68 +-
.../csharp/System/TimeSpan/MaxValue/fields.cs | 64 +-
.../System/TimeSpan/Overview/instantiate1.cs | 141 ++--
.../System/TimeSpan/Overview/structure1.cs | 74 +-
.../csharp/System/TimeSpan/Overview/zero1.cs | 12 +-
.../csharp/System/TimeSpan/Parse/parse1.cs | 56 +-
.../csharp/System/TimeSpan/Parse/parse2.cs | 67 +-
.../System/TimeSpan/ParseExact/Program.cs | 4 +
.../System/TimeSpan/ParseExact/Project.csproj | 6 +
.../TimeSpan/ParseExact/parseexactexample1.cs | 304 ++++----
.../TimeSpan/ParseExact/parseexactexample2.cs | 319 +++++----
.../TimeSpan/ParseExact/parseexactexample3.cs | 50 +-
.../TimeSpan/ParseExact/parseexactexample4.cs | 52 +-
.../System/TimeSpan/Subtract/subtract1.cs | 54 +-
.../System/TimeSpan/ToString/Program.cs | 3 +
.../System/TimeSpan/ToString/Project.csproj | 6 +
.../System/TimeSpan/ToString/ToString1.cs | 88 +--
.../System/TimeSpan/ToString/tostring3.cs | 124 ++--
.../System/TimeSpan/ToString/tostring4.cs | 39 +-
.../System/TimeSpan/TotalDays/totaldays.cs | 46 +-
.../System/TimeSpan/TotalHours/totalhours.cs | 43 +-
.../TotalMilliseconds/totalmilliseconds.cs | 45 +-
.../TimeSpan/TotalMinutes/totalminutes.cs | 42 +-
.../TimeSpan/TotalSeconds/totalseconds.cs | 40 +-
.../System/TimeSpan/TryParse/TryParse1.cs | 64 +-
.../System/TimeSpan/TryParse/tryparse2.cs | 64 +-
.../System/TimeSpan/TryParseExact/Program.cs | 4 +
.../TimeSpan/TryParseExact/Project.csproj | 6 +
.../TryParseExact/tryparseexactexample1.cs | 168 ++---
.../TryParseExact/tryparseexactexample2.cs | 193 +++--
.../TryParseExact/tryparseexactexample3.cs | 35 +-
.../TryParseExact/tryparseexactexample4.cs | 37 +-
.../TimeSpan/op_Addition/Subtraction1.cs | 32 +-
.../System/TimeSpan/op_Addition/operators1.cs | 32 +-
.../TimeSpan/op_Equality/relationalops.cs | 54 +-
.../DateEnd/DateStart1.cs | 121 ++--
.../System.TimeZone2.AdjustmentRule.Class.cs | 424 ++++++-----
.../CreateFixedDateRule/Program.cs | 2 +
.../CreateFixedDateRule/Project.csproj | 6 +
.../System.TimeZone2.TransitionTime.Class.cs | 544 +++++++--------
.../CreateFixedDateRule/example1.cs | 192 +++--
.../TimeZoneInfo/BaseUtcOffset/Program.cs | 3 +
.../TimeZoneInfo/BaseUtcOffset/Project.csproj | 8 +
.../BaseUtcOffset/ShowTimeZoneNames1.cs | 18 +-
.../BaseUtcOffset/TimeZone2_Examples.cs | 272 ++++----
.../BaseUtcOffset/getsystemtimezones1.cs | 108 ++-
.../System.TimeZone2.BestPractices.cs | 44 +-
.../TimeZoneInfo/ConvertTime/Program.cs | 3 +
.../TimeZoneInfo/ConvertTime/Project.csproj | 8 +
.../ConvertTime/TimeZone2Concepts.cs | 658 +++++++++---------
.../TimeZoneInfo/ConvertTime/converttime1.cs | 70 +-
.../TimeZoneInfo/ConvertTime/converttime2.cs | 69 +-
.../System.TimeZone2.Conversions.cs | 190 +++--
.../convertdt2.cs | 28 +-
.../System.TimeZone2.CreateTimeZone.cs | 476 ++++++-------
.../DaylightName/IsDaylightSavingTime.cs | 84 +--
.../System/TimeZoneInfo/Equals/equals1.cs | 22 +-
...ystem.TimeZone2.GetAmbiguousTimeOffsets.cs | 183 +++--
.../System.TimeZone2.GetUtcOffset.cs | 165 +++--
.../TimeZoneInfo/HasSameRules/HasSameRules.cs | 52 +-
.../TimeoutException/Overview/Project.csproj | 9 +
.../System/TimeoutException/Overview/to.cs | 44 +-
.../csharp/System/Tuple/Overview/Program.cs | 5 +
.../System/Tuple/Overview/Project.csproj | 6 +
.../csharp/System/Tuple/Overview/create1.cs | 84 +--
.../System/Tuple/Overview/createntuple.cs | 30 +-
.../csharp/System/Tuple/Overview/ctor8.cs | 20 +-
.../csharp/System/Tuple/Overview/example.cs | 23 +-
.../csharp/System/Tuple/Overview/example1.cs | 62 +-
.../Equals/equals1.cs | 48 +-
.../Item1/item1.cs | 21 +-
.../Overview/octuple1.cs | 16 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 46 +-
.../compareto2.cs | 137 ++--
.../ToString/tostring1.cs | 17 +-
.../Equals/Program.cs | 2 +
.../Equals/Project.csproj | 6 +
.../Equals/equals1.cs | 41 +-
.../Equals/equals2.cs | 87 ++-
.../TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs | 38 +-
.../Overview/example1.cs | 64 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 50 +-
.../compareto2.cs | 130 ++--
.../ToString/tostring1.cs | 14 +-
.../TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs | 2 +
.../Equals/Project.csproj | 6 +
.../TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs | 41 +-
.../TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs | 89 ++-
.../TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs | 40 +-
.../Overview/example1.cs | 58 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 50 +-
.../compareto2.cs | 127 ++--
.../ToString/tostring1.cs | 14 +-
.../TupleT1,T2,T3,T4,T5/Equals/equals1.cs | 41 +-
.../TupleT1,T2,T3,T4,T5/Equals/equals2.cs | 100 ++-
.../System/TupleT1,T2,T3,T4,T5/Item1/item1.cs | 32 +-
.../TupleT1,T2,T3,T4,T5/Overview/example1.cs | 109 ++-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 64 +-
.../compareto2.cs | 88 +--
.../TupleT1,T2,T3,T4,T5/ToString/tostring1.cs | 24 +-
.../System/TupleT1,T2,T3,T4/Equals/equals1.cs | 41 +-
.../System/TupleT1,T2,T3,T4/Equals/equals2.cs | 92 ++-
.../System/TupleT1,T2,T3,T4/Item1/item1.cs | 32 +-
.../TupleT1,T2,T3,T4/Overview/example1.cs | 69 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 50 +-
.../compareto2.cs | 62 +-
.../TupleT1,T2,T3,T4/ToString/tostring1.cs | 22 +-
.../System/TupleT1,T2,T3/Equals/Program.cs | 2 +
.../TupleT1,T2,T3/Equals/Project.csproj | 6 +
.../System/TupleT1,T2,T3/Equals/equals1.cs | 49 +-
.../System/TupleT1,T2,T3/Equals/equals2.cs | 84 ++-
.../System/TupleT1,T2,T3/Overview/example1.cs | 75 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 36 +-
.../compareto2.cs | 62 +-
.../TupleT1,T2,T3/ToString/tostring1.cs | 22 +-
.../System/TupleT1,T2/Equals/Program.cs | 2 +
.../System/TupleT1,T2/Equals/Project.csproj | 6 +
.../System/TupleT1,T2/Equals/equals1.cs | 46 +-
.../System/TupleT1,T2/Equals/equals2.cs | 82 ++-
.../System/TupleT1,T2/Overview/example1.cs | 58 +-
.../System/TupleT1,T2/Overview/item1.cs | 66 +-
.../Program.cs | 2 +
.../Project.csproj | 6 +
.../compareto1.cs | 36 +-
.../compareto2.cs | 62 +-
.../System/TupleT1,T2/ToString/tostring1.cs | 20 +-
.../csharp/System/TupleT1/Equals/Program.cs | 2 +
.../System/TupleT1/Equals/Project.csproj | 6 +
.../csharp/System/TupleT1/Equals/equals1.cs | 45 +-
.../csharp/System/TupleT1/Equals/equals2.cs | 76 +-
snippets/csharp/System/TupleT1/Item1/item1.cs | 50 +-
.../compareto1.cs | 46 +-
.../compareto2.cs | 49 +-
.../System/TupleT1/ToString/tostring1.cs | 35 +-
164 files changed, 5128 insertions(+), 5271 deletions(-)
create mode 100644 snippets/csharp/System/TimeSpan/ParseExact/Program.cs
create mode 100644 snippets/csharp/System/TimeSpan/ParseExact/Project.csproj
create mode 100644 snippets/csharp/System/TimeSpan/ToString/Program.cs
create mode 100644 snippets/csharp/System/TimeSpan/ToString/Project.csproj
create mode 100644 snippets/csharp/System/TimeSpan/TryParseExact/Program.cs
create mode 100644 snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj
create mode 100644 snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs
create mode 100644 snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj
create mode 100644 snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs
create mode 100644 snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj
create mode 100644 snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs
create mode 100644 snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj
create mode 100644 snippets/csharp/System/TimeoutException/Overview/Project.csproj
create mode 100644 snippets/csharp/System/Tuple/Overview/Program.cs
create mode 100644 snippets/csharp/System/Tuple/Overview/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2/Equals/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2/Equals/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs
create mode 100644 snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj
create mode 100644 snippets/csharp/System/TupleT1/Equals/Program.cs
create mode 100644 snippets/csharp/System/TupleT1/Equals/Project.csproj
diff --git a/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs b/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs
index 5f7e07d328a..0fa5de8cd47 100644
--- a/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs
+++ b/snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs
@@ -31,14 +31,8 @@ static void ProcessRequest(object? requestId)
PerformLogging();
}
- static void PerformDatabaseOperation()
- {
- Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}");
- }
+ static void PerformDatabaseOperation() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}");
- static void PerformLogging()
- {
- Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}");
- }
+ static void PerformLogging() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}");
}
//
diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs
index ce9c21fbf34..d52d30cdff5 100644
--- a/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs
+++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriii.cs
@@ -5,37 +5,35 @@
class TimeSpanCtorIIIDemo
{
// Create a TimeSpan object and display its value.
- static void CreateTimeSpan( int hours, int minutes,
- int seconds )
+ static void CreateTimeSpan(int hours, int minutes,
+ int seconds)
{
- TimeSpan elapsedTime =
- new TimeSpan( hours, minutes, seconds );
+ TimeSpan elapsedTime =
+ new(hours, minutes, seconds);
// Format the constructor for display.
- string ctor = String.Format( "TimeSpan( {0}, {1}, {2} )",
- hours, minutes, seconds);
+ string ctor = $"TimeSpan( {hours}, {minutes}, {seconds} )";
// Display the constructor and its value.
- Console.WriteLine( "{0,-37}{1,16}",
- ctor, elapsedTime.ToString( ) );
+ Console.WriteLine($"{ctor,-37}{elapsedTime,16}");
}
-
- static void Main( )
+
+ static void Main()
{
Console.WriteLine(
"This example of the TimeSpan( int, int, int ) " +
- "\nconstructor generates the following output.\n" );
- Console.WriteLine( "{0,-37}{1,16}", "Constructor", "Value" );
- Console.WriteLine( "{0,-37}{1,16}", "-----------", "-----" );
+ "\nconstructor generates the following output.\n");
+ Console.WriteLine($"{"Constructor",-37}{"Value",16}");
+ Console.WriteLine($"{"-----------",-37}{"-----",16}");
- CreateTimeSpan( 10, 20, 30 );
- CreateTimeSpan( -10, 20, 30 );
- CreateTimeSpan( 0, 0, 37230 );
- CreateTimeSpan( 1000, 2000, 3000 );
- CreateTimeSpan( 1000, -2000, -3000 );
- CreateTimeSpan( 999999, 999999, 999999 );
- }
-}
+ CreateTimeSpan(10, 20, 30);
+ CreateTimeSpan(-10, 20, 30);
+ CreateTimeSpan(0, 0, 37230);
+ CreateTimeSpan(1000, 2000, 3000);
+ CreateTimeSpan(1000, -2000, -3000);
+ CreateTimeSpan(999999, 999999, 999999);
+ }
+}
/*
This example of the TimeSpan( int, int, int )
diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs
index f3f6773488f..414722046f1 100644
--- a/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs
+++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriiii.cs
@@ -4,35 +4,33 @@
class Example
{
// Create a TimeSpan object and display its value.
- static void CreateTimeSpan( int days, int hours,
- int minutes, int seconds )
+ static void CreateTimeSpan(int days, int hours,
+ int minutes, int seconds)
{
- TimeSpan elapsedTime =
- new TimeSpan( days, hours, minutes, seconds );
+ TimeSpan elapsedTime =
+ new(days, hours, minutes, seconds);
// Format the constructor for display.
- string ctor =
- String.Format( "TimeSpan( {0}, {1}, {2}, {3} )",
- days, hours, minutes, seconds);
+ string ctor =
+ $"TimeSpan( {days}, {hours}, {minutes}, {seconds} )";
// Display the constructor and its value.
- Console.WriteLine( "{0,-44}{1,16}",
- ctor, elapsedTime.ToString( ) );
+ Console.WriteLine($"{ctor,-44}{elapsedTime,16}");
}
-
- static void Main( )
+
+ static void Main()
{
- Console.WriteLine( "{0,-44}{1,16}", "Constructor", "Value" );
- Console.WriteLine( "{0,-44}{1,16}", "-----------", "-----" );
+ Console.WriteLine($"{"Constructor",-44}{"Value",16}");
+ Console.WriteLine($"{"-----------",-44}{"-----",16}");
- CreateTimeSpan( 10, 20, 30, 40 );
- CreateTimeSpan( -10, 20, 30, 40 );
- CreateTimeSpan( 0, 0, 0, 937840 );
- CreateTimeSpan( 1000, 2000, 3000, 4000 );
- CreateTimeSpan( 1000, -2000, -3000, -4000 );
- CreateTimeSpan( 999999, 999999, 999999, 999999 );
- }
-}
+ CreateTimeSpan(10, 20, 30, 40);
+ CreateTimeSpan(-10, 20, 30, 40);
+ CreateTimeSpan(0, 0, 0, 937840);
+ CreateTimeSpan(1000, 2000, 3000, 4000);
+ CreateTimeSpan(1000, -2000, -3000, -4000);
+ CreateTimeSpan(999999, 999999, 999999, 999999);
+ }
+}
// The example displays the following output:
// Constructor Value
// ----------- -----
diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs b/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs
index 6b9b823404c..f02ea710383 100644
--- a/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs
+++ b/snippets/csharp/System/TimeSpan/.ctor/ctoriiiii.cs
@@ -1,43 +1,41 @@
//
-// Example of the TimeSpan( int, int, int, int, int ) constructor.
+// Example of the TimeSpan( int, int, int, int, int ) constructor.
using System;
class TimeSpanCtorIIIIIDemo
{
// Create a TimeSpan object and display its value.
- static void CreateTimeSpan( int days, int hours,
- int minutes, int seconds, int millisec )
+ static void CreateTimeSpan(int days, int hours,
+ int minutes, int seconds, int millisec)
{
- TimeSpan elapsedTime = new TimeSpan(
- days, hours, minutes, seconds, millisec );
+ TimeSpan elapsedTime = new(
+ days, hours, minutes, seconds, millisec);
// Format the constructor for display.
- string ctor =
- String.Format( "TimeSpan( {0}, {1}, {2}, {3}, {4} )",
- days, hours, minutes, seconds, millisec);
+ string ctor =
+ $"TimeSpan( {days}, {hours}, {minutes}, {seconds}, {millisec} )";
// Display the constructor and its value.
- Console.WriteLine( "{0,-48}{1,24}",
- ctor, elapsedTime.ToString( ) );
+ Console.WriteLine($"{ctor,-48}{elapsedTime,24}");
}
- static void Main( )
+ static void Main()
{
- Console.WriteLine(
+ Console.WriteLine(
"This example of the " +
"TimeSpan( int, int, int, int, int ) " +
- "\nconstructor generates the following output.\n" );
- Console.WriteLine( "{0,-48}{1,16}", "Constructor", "Value" );
- Console.WriteLine( "{0,-48}{1,16}", "-----------", "-----" );
+ "\nconstructor generates the following output.\n");
+ Console.WriteLine($"{"Constructor",-48}{"Value",16}");
+ Console.WriteLine($"{"-----------",-48}{"-----",16}");
- CreateTimeSpan( 10, 20, 30, 40, 50 );
- CreateTimeSpan( -10, 20, 30, 40, 50 );
- CreateTimeSpan( 0, 0, 0, 0, 937840050 );
- CreateTimeSpan( 1111, 2222, 3333, 4444, 5555 );
- CreateTimeSpan( 1111, -2222, -3333, -4444, -5555 );
- CreateTimeSpan( 99999, 99999, 99999, 99999, 99999 );
- }
-}
+ CreateTimeSpan(10, 20, 30, 40, 50);
+ CreateTimeSpan(-10, 20, 30, 40, 50);
+ CreateTimeSpan(0, 0, 0, 0, 937840050);
+ CreateTimeSpan(1111, 2222, 3333, 4444, 5555);
+ CreateTimeSpan(1111, -2222, -3333, -4444, -5555);
+ CreateTimeSpan(99999, 99999, 99999, 99999, 99999);
+ }
+}
/*
This example of the TimeSpan( int, int, int, int, int )
diff --git a/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs b/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs
index acea73f41cf..cae8d36226d 100644
--- a/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs
+++ b/snippets/csharp/System/TimeSpan/.ctor/ctorl.cs
@@ -5,41 +5,41 @@
class TimeSpanCtorLDemo
{
// Create a TimeSpan object and display its value.
- static void CreateTimeSpan( long ticks )
+ static void CreateTimeSpan(long ticks)
{
- TimeSpan elapsedTime = new TimeSpan( ticks );
+ TimeSpan elapsedTime = new(ticks);
// Format the constructor for display.
- string ctor = String.Format( "TimeSpan( {0} )", ticks );
+ string ctor = $"TimeSpan( {ticks} )";
// Pad the end of a TimeSpan string with spaces if
// it does not contain milliseconds.
- string elapsedStr = elapsedTime.ToString( );
- int pointIndex = elapsedStr.IndexOf( ':' );
+ string elapsedStr = elapsedTime.ToString();
+ int pointIndex = elapsedStr.IndexOf(':');
- pointIndex = elapsedStr.IndexOf( '.', pointIndex );
- if( pointIndex < 0 ) elapsedStr += " ";
+ pointIndex = elapsedStr.IndexOf('.', pointIndex);
+ if (pointIndex < 0) elapsedStr += " ";
// Display the constructor and its value.
- Console.WriteLine( "{0,-33}{1,24}", ctor, elapsedStr );
+ Console.WriteLine($"{ctor,-33}{elapsedStr,24}");
}
-
- static void Main( )
+
+ static void Main()
{
- Console.WriteLine(
+ Console.WriteLine(
"This example of the TimeSpan( long ) constructor " +
- "\ngenerates the following output.\n" );
- Console.WriteLine( "{0,-33}{1,16}", "Constructor", "Value" );
- Console.WriteLine( "{0,-33}{1,16}", "-----------", "-----" );
-
- CreateTimeSpan( 1 );
- CreateTimeSpan( 999999 );
- CreateTimeSpan( -1000000000000 );
- CreateTimeSpan( 18012202000000 );
- CreateTimeSpan( 999999999999999999 );
- CreateTimeSpan( 1000000000000000000 );
- }
-}
+ "\ngenerates the following output.\n");
+ Console.WriteLine($"{"Constructor",-33}{"Value",16}");
+ Console.WriteLine($"{"-----------",-33}{"-----",16}");
+
+ CreateTimeSpan(1);
+ CreateTimeSpan(999999);
+ CreateTimeSpan(-1000000000000);
+ CreateTimeSpan(18012202000000);
+ CreateTimeSpan(999999999999999999);
+ CreateTimeSpan(1000000000000000000);
+ }
+}
/*
This example of the TimeSpan( long ) constructor
diff --git a/snippets/csharp/System/TimeSpan/Add/add1.cs b/snippets/csharp/System/TimeSpan/Add/add1.cs
index 4d8254b602f..6a30030219b 100644
--- a/snippets/csharp/System/TimeSpan/Add/add1.cs
+++ b/snippets/csharp/System/TimeSpan/Add/add1.cs
@@ -2,34 +2,34 @@
public class Example
{
- public static void Main()
- {
- //
- TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16);
+ public static void Main()
+ {
+ //
+ TimeSpan baseTimeSpan = new(1, 12, 15, 16);
- // Create an array of timespan intervals.
- TimeSpan[] intervals = {
- TimeSpan.FromDays(1.5),
- TimeSpan.FromHours(1.5),
- TimeSpan.FromMinutes(45),
+ // Create an array of timespan intervals.
+ TimeSpan[] intervals = [
+ TimeSpan.FromDays(1.5),
+ TimeSpan.FromHours(1.5),
+ TimeSpan.FromMinutes(45),
TimeSpan.FromMilliseconds(505),
- new TimeSpan(1, 17, 32, 20),
- new TimeSpan(-8, 30, 0)
- };
+ new TimeSpan(1, 17, 32, 20),
+ new TimeSpan(-8, 30, 0)
+ ];
- // Calculate a new time interval by adding each element to the base interval.
- foreach (var interval in intervals)
- Console.WriteLine(@"{0,-10:g} {3} {1,15:%d\:hh\:mm\:ss\.ffff} = {2:%d\:hh\:mm\:ss\.ffff}",
- baseTimeSpan, interval, baseTimeSpan.Add(interval),
- interval < TimeSpan.Zero ? "-" : "+");
+ // Calculate a new time interval by adding each element to the base interval.
+ foreach (var interval in intervals)
+ Console.WriteLine(@"{0,-10:g} {3} {1,15:%d\:hh\:mm\:ss\.ffff} = {2:%d\:hh\:mm\:ss\.ffff}",
+ baseTimeSpan, interval, baseTimeSpan.Add(interval),
+ interval < TimeSpan.Zero ? "-" : "+");
- // The example displays the following output:
- // 1:12:15:16 + 1:12:00:00.0000 = 3:00:15:16.0000
- // 1:12:15:16 + 0:01:30:00.0000 = 1:13:45:16.0000
- // 1:12:15:16 + 0:00:45:00.0000 = 1:13:00:16.0000
- // 1:12:15:16 + 0:00:00:00.5050 = 1:12:15:16.5050
- // 1:12:15:16 + 1:17:32:20.0000 = 3:05:47:36.0000
- // 1:12:15:16 - 0:07:30:00.0000 = 1:04:45:16.0000
- //
- }
+ // The example displays the following output:
+ // 1:12:15:16 + 1:12:00:00.0000 = 3:00:15:16.0000
+ // 1:12:15:16 + 0:01:30:00.0000 = 1:13:45:16.0000
+ // 1:12:15:16 + 0:00:45:00.0000 = 1:13:00:16.0000
+ // 1:12:15:16 + 0:00:00:00.5050 = 1:12:15:16.5050
+ // 1:12:15:16 + 1:17:32:20.0000 = 3:05:47:36.0000
+ // 1:12:15:16 - 0:07:30:00.0000 = 1:04:45:16.0000
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/Compare/compare1.cs b/snippets/csharp/System/TimeSpan/Compare/compare1.cs
index 14e10e51a83..0a25d8d21c9 100644
--- a/snippets/csharp/System/TimeSpan/Compare/compare1.cs
+++ b/snippets/csharp/System/TimeSpan/Compare/compare1.cs
@@ -6,27 +6,25 @@ static void Main()
{
//
// Define a time interval equal to two hours.
- TimeSpan baseInterval = new TimeSpan( 2, 0, 0);
+ TimeSpan baseInterval = new(2, 0, 0);
// Define an array of time intervals to compare with
// the base interval.
- TimeSpan[] spans = {
+ TimeSpan[] spans = [
TimeSpan.FromSeconds(-2.5),
TimeSpan.FromMinutes(20),
- TimeSpan.FromHours(1),
+ TimeSpan.FromHours(1),
TimeSpan.FromMinutes(90),
- baseInterval,
- TimeSpan.FromDays(.5),
- TimeSpan.FromDays(1)
- };
+ baseInterval,
+ TimeSpan.FromDays(.5),
+ TimeSpan.FromDays(1)
+ ];
// Compare the time intervals.
- foreach (var span in spans) {
- int result = TimeSpan.Compare(baseInterval, span);
- Console.WriteLine("{0} {1} {2} (Compare returns {3})",
- baseInterval,
- result == 1 ? ">" : result == 0 ? "=" : "<",
- span, result);
+ foreach (var span in spans)
+ {
+ int result = TimeSpan.Compare(baseInterval, span);
+ Console.WriteLine($"{baseInterval} {(result == 1 ? ">" : result == 0 ? "=" : "<")} {span} (Compare returns {result})");
}
// The example displays the following output:
@@ -38,5 +36,5 @@ static void Main()
// 02:00:00 < 12:00:00 (Compare returns -1)
// 02:00:00 < 1.00:00:00 (Compare returns -1)
//
- }
-}
+ }
+}
diff --git a/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs b/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs
index 608e000cca8..3bea5a23db7 100644
--- a/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs
+++ b/snippets/csharp/System/TimeSpan/CompareTo/comp_equal.cs
@@ -1,51 +1,51 @@
//
-// Example of the TimeSpan.Compare( TimeSpan, TimeSpan ) and
+// Example of the TimeSpan.Compare( TimeSpan, TimeSpan ) and
// TimeSpan.Equals( TimeSpan, TimeSpan ) methods.
using System;
class TSCompareEqualsDemo
{
- const string dataFmt = "{0,-38}{1}" ;
+ const string dataFmt = "{0,-38}{1}";
// Compare TimeSpan parameters, and display them with the results.
- static void CompareTimeSpans( TimeSpan Left, TimeSpan Right,
- string RightText )
+ static void CompareTimeSpans(TimeSpan Left, TimeSpan Right,
+ string RightText)
{
- Console.WriteLine( );
- Console.WriteLine( dataFmt, "Right: " + RightText, Right );
- Console.WriteLine( dataFmt, "TimeSpan.Equals( Left, Right )",
- TimeSpan.Equals( Left, Right ) );
- Console.WriteLine( dataFmt,
- "TimeSpan.Compare( Left, Right )",
- TimeSpan.Compare( Left, Right ) );
+ Console.WriteLine();
+ Console.WriteLine(dataFmt, "Right: " + RightText, Right);
+ Console.WriteLine(dataFmt, "TimeSpan.Equals( Left, Right )",
+ TimeSpan.Equals(Left, Right));
+ Console.WriteLine(dataFmt,
+ "TimeSpan.Compare( Left, Right )",
+ TimeSpan.Compare(Left, Right));
}
- static void Main( )
+ static void Main()
{
- TimeSpan Left = new TimeSpan( 2, 0, 0 );
+ TimeSpan Left = new(2, 0, 0);
Console.WriteLine(
"This example of the TimeSpan.Equals( TimeSpan, Time" +
"Span ) and \nTimeSpan.Compare( TimeSpan, TimeSpan ) " +
"methods generates the \nfollowing output by creating " +
"several different TimeSpan \nobjects and comparing " +
- "them with a 2-hour TimeSpan.\n" );
- Console.WriteLine( dataFmt, "Left: TimeSpan( 2, 0, 0 )",
- Left );
+ "them with a 2-hour TimeSpan.\n");
+ Console.WriteLine(dataFmt, "Left: TimeSpan( 2, 0, 0 )",
+ Left);
// Create objects to compare with a 2-hour TimeSpan.
- CompareTimeSpans( Left, new TimeSpan( 0, 120, 0 ),
- "TimeSpan( 0, 120, 0 )" );
- CompareTimeSpans( Left, new TimeSpan( 2, 0, 1 ),
- "TimeSpan( 2, 0, 1 )" );
- CompareTimeSpans( Left, new TimeSpan( 2, 0, -1 ),
+ CompareTimeSpans(Left, new TimeSpan(0, 120, 0),
+ "TimeSpan( 0, 120, 0 )");
+ CompareTimeSpans(Left, new TimeSpan(2, 0, 1),
+ "TimeSpan( 2, 0, 1 )");
+ CompareTimeSpans(Left, new TimeSpan(2, 0, -1),
"TimeSpan( 2, 0, -1 )");
- CompareTimeSpans( Left, new TimeSpan( 72000000000 ),
- "TimeSpan( 72000000000 )" );
- CompareTimeSpans( Left, TimeSpan.FromDays( 1.0 / 12D ),
- "TimeSpan.FromDays( 1 / 12 )" );
- }
-}
+ CompareTimeSpans(Left, new TimeSpan(72000000000),
+ "TimeSpan( 72000000000 )");
+ CompareTimeSpans(Left, TimeSpan.FromDays(1.0 / 12D),
+ "TimeSpan.FromDays( 1 / 12 )");
+ }
+}
/*
This example of the TimeSpan.Equals( TimeSpan, TimeSpan ) and
@@ -74,5 +74,5 @@ objects and comparing them with a 2-hour TimeSpan.
Right: TimeSpan.FromDays( 1 / 12 ) 02:00:00
TimeSpan.Equals( Left, Right ) True
TimeSpan.Compare( Left, Right ) 0
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs b/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs
index 81a4f8acf57..0bbf8e67e6e 100644
--- a/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs
+++ b/snippets/csharp/System/TimeSpan/CompareTo/cto_eq_obj.cs
@@ -1,60 +1,57 @@
//
-// Example of the TimeSpan.CompareTo( Object ) and
+// Example of the TimeSpan.CompareTo( Object ) and
// TimeSpan.Equals( Object ) methods.
using System;
class TSCompToEqualsObjDemo
{
- // Compare the TimeSpan to the Object parameters,
+ // Compare the TimeSpan to the Object parameters,
// and display the Object parameters with the results.
- static void CompTimeSpanToObject( TimeSpan Left, object Right,
- string RightText )
+ static void CompTimeSpanToObject(TimeSpan Left, object Right,
+ string RightText)
{
- Console.WriteLine( "{0,-33}{1}", "Object: " + RightText,
- Right );
- Console.WriteLine( "{0,-33}{1}", "Left.Equals( Object )",
- Left.Equals( Right ) );
- Console.Write( "{0,-33}", "Left.CompareTo( Object )" );
+ Console.WriteLine($"{"Object: " + RightText,-33}{Right}");
+ Console.WriteLine($"{"Left.Equals( Object )",-33}{Left.Equals(Right)}");
+ Console.Write($"{"Left.CompareTo( Object )",-33}");
// Catch the exception if CompareTo( ) throws one.
try
{
- Console.WriteLine( "{0}\n", Left.CompareTo( Right ) );
+ Console.WriteLine($"{Left.CompareTo(Right)}\n");
}
- catch( Exception ex )
+ catch (Exception ex)
{
- Console.WriteLine( "Error: {0}\n", ex.Message );
+ Console.WriteLine($"Error: {ex.Message}\n");
}
}
- static void Main( )
+ static void Main()
{
- TimeSpan Left = new TimeSpan( 0, 5, 0 );
+ TimeSpan Left = new(0, 5, 0);
Console.WriteLine(
"This example of the TimeSpan.Equals( Object ) " +
"and \nTimeSpan.CompareTo( Object ) methods generates " +
"the \nfollowing output by creating several different " +
"TimeSpan \nobjects and comparing them with a " +
- "5-minute TimeSpan.\n" );
- Console.WriteLine( "{0,-33}{1}\n",
- "Left: TimeSpan( 0, 5, 0 )", Left );
+ "5-minute TimeSpan.\n");
+ Console.WriteLine($"{"Left: TimeSpan( 0, 5, 0 )",-33}{Left}\n");
// Create objects to compare with a 5-minute TimeSpan.
- CompTimeSpanToObject( Left, new TimeSpan( 0, 0, 300 ),
- "TimeSpan( 0, 0, 300 )" );
- CompTimeSpanToObject( Left, new TimeSpan( 0, 5, 1 ),
- "TimeSpan( 0, 5, 1 )" );
- CompTimeSpanToObject( Left, new TimeSpan( 0, 5, -1 ),
- "TimeSpan( 0, 5, -1 )" );
- CompTimeSpanToObject( Left, new TimeSpan( 3000000000 ),
- "TimeSpan( 3000000000 )" );
- CompTimeSpanToObject( Left, 3000000000L,
- "long 3000000000L" );
- CompTimeSpanToObject( Left, "00:05:00",
- "string \"00:05:00\"" );
- }
-}
+ CompTimeSpanToObject(Left, new TimeSpan(0, 0, 300),
+ "TimeSpan( 0, 0, 300 )");
+ CompTimeSpanToObject(Left, new TimeSpan(0, 5, 1),
+ "TimeSpan( 0, 5, 1 )");
+ CompTimeSpanToObject(Left, new TimeSpan(0, 5, -1),
+ "TimeSpan( 0, 5, -1 )");
+ CompTimeSpanToObject(Left, new TimeSpan(3000000000),
+ "TimeSpan( 3000000000 )");
+ CompTimeSpanToObject(Left, 3000000000L,
+ "long 3000000000L");
+ CompTimeSpanToObject(Left, "00:05:00",
+ "string \"00:05:00\"");
+ }
+}
/*
This example of the TimeSpan.Equals( Object ) and
diff --git a/snippets/csharp/System/TimeSpan/Days/properties.cs b/snippets/csharp/System/TimeSpan/Days/properties.cs
index 15bf2ff4daa..350b7e65123 100644
--- a/snippets/csharp/System/TimeSpan/Days/properties.cs
+++ b/snippets/csharp/System/TimeSpan/Days/properties.cs
@@ -6,45 +6,37 @@ class Example
static void Main()
{
// Create and display a TimeSpan value of 1 tick.
- Console.Write("\n{0,-45}", "TimeSpan( 1 )");
+ Console.Write($"\n{"TimeSpan( 1 )",-45}");
ShowTimeSpanProperties(new TimeSpan(1));
// Create a TimeSpan value with a large number of ticks.
- Console.Write("\n{0,-45}", "TimeSpan( 111222333444555 )");
+ Console.Write($"\n{"TimeSpan( 111222333444555 )",-45}");
ShowTimeSpanProperties(new TimeSpan(111222333444555));
// This TimeSpan has all fields specified.
- Console.Write("\n{0,-45}", "TimeSpan( 10, 20, 30, 40, 50 )");
+ Console.Write($"\n{"TimeSpan( 10, 20, 30, 40, 50 )",-45}");
ShowTimeSpanProperties(new TimeSpan(10, 20, 30, 40, 50));
// This TimeSpan has all fields overflowing.
- Console.Write("\n{0,-45}",
- "TimeSpan( 1111, 2222, 3333, 4444, 5555 )");
+ Console.Write($"\n{"TimeSpan( 1111, 2222, 3333, 4444, 5555 )",-45}");
ShowTimeSpanProperties(
new TimeSpan(1111, 2222, 3333, 4444, 5555));
// This TimeSpan is based on a number of days.
- Console.Write("\n{0,-45}", "FromDays( 20.84745602 )");
- ShowTimeSpanProperties(TimeSpan.FromDays( 20.84745602));
+ Console.Write($"\n{"FromDays( 20.84745602 )",-45}");
+ ShowTimeSpanProperties(TimeSpan.FromDays(20.84745602));
}
- static void ShowTimeSpanProperties( TimeSpan interval )
+ static void ShowTimeSpanProperties(TimeSpan interval)
{
- Console.WriteLine("{0,21}", interval);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Days",
- interval.Days, "TotalDays", interval.TotalDays);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Hours",
- interval.Hours, "TotalHours", interval.TotalHours);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Minutes",
- interval.Minutes, "TotalMinutes", interval.TotalMinutes);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Seconds",
- interval.Seconds, "TotalSeconds", interval.TotalSeconds);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N3}", "Milliseconds",
- interval.Milliseconds, "TotalMilliseconds",
- interval.TotalMilliseconds);
- Console.WriteLine("{0,-12}{1,8} {2,-18}{3,21:N0}", null, null,
- "Ticks", interval.Ticks);
- }
+ Console.WriteLine($"{interval,21}");
+ Console.WriteLine($"{"Days",-12}{interval.Days,8} {"TotalDays",-18}{interval.TotalDays,21:N3}");
+ Console.WriteLine($"{"Hours",-12}{interval.Hours,8} {"TotalHours",-18}{interval.TotalHours,21:N3}");
+ Console.WriteLine($"{"Minutes",-12}{interval.Minutes,8} {"TotalMinutes",-18}{interval.TotalMinutes,21:N3}");
+ Console.WriteLine($"{"Seconds",-12}{interval.Seconds,8} {"TotalSeconds",-18}{interval.TotalSeconds,21:N3}");
+ Console.WriteLine($"{"Milliseconds",-12}{interval.Milliseconds,8} {"TotalMilliseconds",-18}{interval.TotalMilliseconds,21:N3}");
+ Console.WriteLine($"{null,-12}{null,8} {"Ticks",-18}{interval.Ticks,21:N0}");
+ }
}
// The example displays the following output if the current culture is en-US:
// TimeSpan( 1 ) 00:00:00.0000001
diff --git a/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs b/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs
index 4e15130925d..2cb69588d73 100644
--- a/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs
+++ b/snippets/csharp/System/TimeSpan/Duration/dura_nega_una.cs
@@ -5,14 +5,14 @@
class DuraNegaUnaryDemo
{
- const string dataFmt = "{0,22}{1,22}{2,22}" ;
+ const string dataFmt = "{0,22}{1,22}{2,22}";
- static void ShowDurationNegate( TimeSpan interval )
+ static void ShowDurationNegate(TimeSpan interval)
{
- // Display the TimeSpan value and the results of the
+ // Display the TimeSpan value and the results of the
// Duration and Negate methods.
- Console.WriteLine( dataFmt,
- interval, interval.Duration( ), interval.Negate( ) );
+ Console.WriteLine(dataFmt,
+ interval, interval.Duration(), interval.Negate());
}
static void Main()
@@ -21,26 +21,26 @@ static void Main()
"This example of TimeSpan.Duration( ), " +
"TimeSpan.Negate( ), \nand the TimeSpan Unary " +
"Negation and Unary Plus operators \n" +
- "generates the following output.\n" );
- Console.WriteLine( dataFmt,
- "TimeSpan", "Duration( )", "Negate( )" );
- Console.WriteLine( dataFmt,
- "--------", "-----------", "---------" );
+ "generates the following output.\n");
+ Console.WriteLine(dataFmt,
+ "TimeSpan", "Duration( )", "Negate( )");
+ Console.WriteLine(dataFmt,
+ "--------", "-----------", "---------");
// Create TimeSpan objects and apply the Unary Negation
// and Unary Plus operators to them.
- ShowDurationNegate( new TimeSpan( 1 ) );
- ShowDurationNegate( new TimeSpan( -1234567 ) );
- ShowDurationNegate(
- + new TimeSpan( 0, 0, 10, -20, -30 ) );
- ShowDurationNegate(
- + new TimeSpan( 0, -10, 20, -30, 40 ) );
- ShowDurationNegate(
- - new TimeSpan( 1, 10, 20, 40, 160 ) );
- ShowDurationNegate(
- - new TimeSpan( -10, -20, -30, -40, -50 ) );
- }
-}
+ ShowDurationNegate(new TimeSpan(1));
+ ShowDurationNegate(new TimeSpan(-1234567));
+ ShowDurationNegate(
+ +new TimeSpan(0, 0, 10, -20, -30));
+ ShowDurationNegate(
+ +new TimeSpan(0, -10, 20, -30, 40));
+ ShowDurationNegate(
+ -new TimeSpan(1, 10, 20, 40, 160));
+ ShowDurationNegate(
+ -new TimeSpan(-10, -20, -30, -40, -50));
+ }
+}
/*
This example of TimeSpan.Duration( ), TimeSpan.Negate( ),
@@ -55,5 +55,5 @@ TimeSpan Duration( ) Negate( )
-09:40:29.9600000 09:40:29.9600000 09:40:29.9600000
-1.10:20:40.1600000 1.10:20:40.1600000 1.10:20:40.1600000
10.20:30:40.0500000 10.20:30:40.0500000 -10.20:30:40.0500000
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs b/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs
index 977271ac7f6..d20af5e45e3 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/System.TimeSpan.FromMinutes.cs
@@ -2,53 +2,53 @@
public class Class1
{
- public static void Main()
- {
- Class1 cl1 = new Class1();
- cl1.InstantiateMinutes();
- cl1.InstantiateDays();
- cl1.InstantiateHours();
- cl1.InstantiateMilliseconds();
- cl1.InstantiateSeconds();
- }
+ public static void Main()
+ {
+ Class1 cl1 = new();
+ cl1.InstantiateMinutes();
+ cl1.InstantiateDays();
+ cl1.InstantiateHours();
+ cl1.InstantiateMilliseconds();
+ cl1.InstantiateSeconds();
+ }
- private void InstantiateMinutes()
- {
- //
- // The following throws an OverflowException at runtime
- TimeSpan maxSpan = TimeSpan.FromMinutes(TimeSpan.MaxValue.TotalMinutes);
- //
- }
+ private void InstantiateMinutes()
+ {
+ //
+ // The following throws an OverflowException at runtime
+ TimeSpan maxSpan = TimeSpan.FromMinutes(TimeSpan.MaxValue.TotalMinutes);
+ //
+ }
- private void InstantiateDays()
- {
- //
- // The following throws an OverflowException at runtime
- TimeSpan maxSpan = TimeSpan.FromDays(TimeSpan.MaxValue.TotalDays);
- //
- }
-
- private void InstantiateHours()
- {
- //
- // The following throws an OverflowException at runtime
- TimeSpan maxSpan = TimeSpan.FromHours(TimeSpan.MaxValue.TotalHours);
- //
- }
+ private void InstantiateDays()
+ {
+ //
+ // The following throws an OverflowException at runtime
+ TimeSpan maxSpan = TimeSpan.FromDays(TimeSpan.MaxValue.TotalDays);
+ //
+ }
- private void InstantiateMilliseconds()
- {
- //
- // The following throws an OverflowException at runtime
- TimeSpan maxSpan = TimeSpan.FromMilliseconds(TimeSpan.MaxValue.TotalMilliseconds);
- //
- }
+ private void InstantiateHours()
+ {
+ //
+ // The following throws an OverflowException at runtime
+ TimeSpan maxSpan = TimeSpan.FromHours(TimeSpan.MaxValue.TotalHours);
+ //
+ }
- private void InstantiateSeconds()
- {
- //
- // The following throws an OverflowException at runtime
- TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds);
- //
- }
+ private void InstantiateMilliseconds()
+ {
+ //
+ // The following throws an OverflowException at runtime
+ TimeSpan maxSpan = TimeSpan.FromMilliseconds(TimeSpan.MaxValue.TotalMilliseconds);
+ //
+ }
+
+ private void InstantiateSeconds()
+ {
+ //
+ // The following throws an OverflowException at runtime
+ TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds);
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs b/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs
index 11c3697cb30..f275ead79cb 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/fromdays.cs
@@ -4,44 +4,42 @@
class FromDaysDemo
{
- static void GenTimeSpanFromDays( double days )
+ static void GenTimeSpanFromDays(double days)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of days.
- TimeSpan interval = TimeSpan.FromDays( days );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromDays(days);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", days, timeInterval );
- }
+ Console.WriteLine($"{days,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromDays( double )\n" +
- "generates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromDays", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "--------", "--------" );
+ "generates the following output.\n");
+ Console.WriteLine($"{"FromDays",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"--------",21}{"--------",18}");
- GenTimeSpanFromDays( 0.000000006 );
- GenTimeSpanFromDays( 0.000000017 );
- GenTimeSpanFromDays( 0.000123456 );
- GenTimeSpanFromDays( 1.234567898 );
- GenTimeSpanFromDays( 12345.678987654 );
- GenTimeSpanFromDays( 0.000011574 );
- GenTimeSpanFromDays( 0.000694444 );
- GenTimeSpanFromDays( 0.041666666 );
- GenTimeSpanFromDays( 1 );
- GenTimeSpanFromDays( 20.84745602 );
- }
-}
+ GenTimeSpanFromDays(0.000000006);
+ GenTimeSpanFromDays(0.000000017);
+ GenTimeSpanFromDays(0.000123456);
+ GenTimeSpanFromDays(1.234567898);
+ GenTimeSpanFromDays(12345.678987654);
+ GenTimeSpanFromDays(0.000011574);
+ GenTimeSpanFromDays(0.000694444);
+ GenTimeSpanFromDays(0.041666666);
+ GenTimeSpanFromDays(1);
+ GenTimeSpanFromDays(20.84745602);
+ }
+}
/*
This example of TimeSpan.FromDays( double )
@@ -59,5 +57,5 @@ FromDays TimeSpan
0.041666666 01:00:00
1 1.00:00:00
20.84745602 20.20:20:20.2000000
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs b/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs
index ab7476e372f..9b49c4355d2 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/fromhours.cs
@@ -4,44 +4,42 @@
class FromHoursDemo
{
- static void GenTimeSpanFromHours( double hours )
+ static void GenTimeSpanFromHours(double hours)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of hours.
- TimeSpan interval = TimeSpan.FromHours( hours );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromHours(hours);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", hours, timeInterval );
- }
+ Console.WriteLine($"{hours,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromHours( double )\n" +
- "generates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromHours", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "---------", "--------" );
+ "generates the following output.\n");
+ Console.WriteLine($"{"FromHours",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"---------",21}{"--------",18}");
- GenTimeSpanFromHours( 0.0000002 );
- GenTimeSpanFromHours( 0.0000003 );
- GenTimeSpanFromHours( 0.0012345 );
- GenTimeSpanFromHours( 12.3456789 );
- GenTimeSpanFromHours( 123456.7898765 );
- GenTimeSpanFromHours( 0.0002777 );
- GenTimeSpanFromHours( 0.0166666 );
- GenTimeSpanFromHours( 1 );
- GenTimeSpanFromHours( 24 );
- GenTimeSpanFromHours( 500.3389445 );
- }
-}
+ GenTimeSpanFromHours(0.0000002);
+ GenTimeSpanFromHours(0.0000003);
+ GenTimeSpanFromHours(0.0012345);
+ GenTimeSpanFromHours(12.3456789);
+ GenTimeSpanFromHours(123456.7898765);
+ GenTimeSpanFromHours(0.0002777);
+ GenTimeSpanFromHours(0.0166666);
+ GenTimeSpanFromHours(1);
+ GenTimeSpanFromHours(24);
+ GenTimeSpanFromHours(500.3389445);
+ }
+}
/*
This example of TimeSpan.FromHours( double )
@@ -59,5 +57,5 @@ FromHours TimeSpan
1 01:00:00
24 1.00:00:00
500.3389445 20.20:20:20.2000000
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs b/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs
index 4c41285c1c0..74c2d5fba34 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/frommillisec.cs
@@ -4,44 +4,42 @@
class FromMillisecDemo
{
- static void GenTimeSpanFromMillisec( Double millisec )
+ static void GenTimeSpanFromMillisec(double millisec)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of milliseconds.
- TimeSpan interval = TimeSpan.FromMilliseconds( millisec );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromMilliseconds(millisec);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", millisec, timeInterval );
- }
+ Console.WriteLine($"{millisec,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromMilliseconds( " +
- "double )\ngenerates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromMilliseconds", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "----------------", "--------" );
+ "double )\ngenerates the following output.\n");
+ Console.WriteLine($"{"FromMilliseconds",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"----------------",21}{"--------",18}");
- GenTimeSpanFromMillisec( 1 );
- GenTimeSpanFromMillisec( 1.5 );
- GenTimeSpanFromMillisec( 12345.6 );
- GenTimeSpanFromMillisec( 123456789.8 );
- GenTimeSpanFromMillisec( 1234567898765.4 );
- GenTimeSpanFromMillisec( 1000 );
- GenTimeSpanFromMillisec( 60000 );
- GenTimeSpanFromMillisec( 3600000 );
- GenTimeSpanFromMillisec( 86400000 );
- GenTimeSpanFromMillisec( 1801220200 );
- }
-}
+ GenTimeSpanFromMillisec(1);
+ GenTimeSpanFromMillisec(1.5);
+ GenTimeSpanFromMillisec(12345.6);
+ GenTimeSpanFromMillisec(123456789.8);
+ GenTimeSpanFromMillisec(1234567898765.4);
+ GenTimeSpanFromMillisec(1000);
+ GenTimeSpanFromMillisec(60000);
+ GenTimeSpanFromMillisec(3600000);
+ GenTimeSpanFromMillisec(86400000);
+ GenTimeSpanFromMillisec(1801220200);
+ }
+}
/*
This example of TimeSpan.FromMilliseconds( double )
diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs b/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs
index c60b80fa9e9..091b935590a 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/fromminutes.cs
@@ -4,44 +4,42 @@
class FromMinutesDemo
{
- static void GenTimeSpanFromMinutes( double minutes )
+ static void GenTimeSpanFromMinutes(double minutes)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of minutes.
- TimeSpan interval = TimeSpan.FromMinutes( minutes );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromMinutes(minutes);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", minutes, timeInterval );
- }
+ Console.WriteLine($"{minutes,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromMinutes( double )\n" +
- "generates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromMinutes", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "-----------", "--------" );
+ "generates the following output.\n");
+ Console.WriteLine($"{"FromMinutes",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"-----------",21}{"--------",18}");
- GenTimeSpanFromMinutes( 0.00001 );
- GenTimeSpanFromMinutes( 0.00002 );
- GenTimeSpanFromMinutes( 0.12345 );
- GenTimeSpanFromMinutes( 1234.56789 );
- GenTimeSpanFromMinutes( 12345678.98765 );
- GenTimeSpanFromMinutes( 0.01666 );
- GenTimeSpanFromMinutes( 1 );
- GenTimeSpanFromMinutes( 60 );
- GenTimeSpanFromMinutes( 1440 );
- GenTimeSpanFromMinutes( 30020.33667 );
- }
-}
+ GenTimeSpanFromMinutes(0.00001);
+ GenTimeSpanFromMinutes(0.00002);
+ GenTimeSpanFromMinutes(0.12345);
+ GenTimeSpanFromMinutes(1234.56789);
+ GenTimeSpanFromMinutes(12345678.98765);
+ GenTimeSpanFromMinutes(0.01666);
+ GenTimeSpanFromMinutes(1);
+ GenTimeSpanFromMinutes(60);
+ GenTimeSpanFromMinutes(1440);
+ GenTimeSpanFromMinutes(30020.33667);
+ }
+}
/*
This example of TimeSpan.FromMinutes( double )
@@ -59,5 +57,5 @@ FromMinutes TimeSpan
60 01:00:00
1440 1.00:00:00
30020.33667 20.20:20:20.2000000
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs b/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs
index 9fbd25c99f6..db0b9746b25 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/fromseconds.cs
@@ -4,44 +4,42 @@
class FromSecondsDemo
{
- static void GenTimeSpanFromSeconds( double seconds )
+ static void GenTimeSpanFromSeconds(double seconds)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of seconds.
- TimeSpan interval = TimeSpan.FromSeconds( seconds );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromSeconds(seconds);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", seconds, timeInterval );
- }
+ Console.WriteLine($"{seconds,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromSeconds( double )\n" +
- "generates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromSeconds", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "-----------", "--------" );
+ "generates the following output.\n");
+ Console.WriteLine($"{"FromSeconds",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"-----------",21}{"--------",18}");
- GenTimeSpanFromSeconds( 0.001 );
- GenTimeSpanFromSeconds( 0.0015 );
- GenTimeSpanFromSeconds( 12.3456 );
- GenTimeSpanFromSeconds( 123456.7898 );
- GenTimeSpanFromSeconds( 1234567898.7654 );
- GenTimeSpanFromSeconds( 1 );
- GenTimeSpanFromSeconds( 60 );
- GenTimeSpanFromSeconds( 3600 );
- GenTimeSpanFromSeconds( 86400 );
- GenTimeSpanFromSeconds( 1801220.2 );
- }
-}
+ GenTimeSpanFromSeconds(0.001);
+ GenTimeSpanFromSeconds(0.0015);
+ GenTimeSpanFromSeconds(12.3456);
+ GenTimeSpanFromSeconds(123456.7898);
+ GenTimeSpanFromSeconds(1234567898.7654);
+ GenTimeSpanFromSeconds(1);
+ GenTimeSpanFromSeconds(60);
+ GenTimeSpanFromSeconds(3600);
+ GenTimeSpanFromSeconds(86400);
+ GenTimeSpanFromSeconds(1801220.2);
+ }
+}
/*
This example of TimeSpan.FromSeconds( double )
@@ -59,5 +57,5 @@ FromSeconds TimeSpan
3600 01:00:00
86400 1.00:00:00
1801220.2 20.20:20:20.2000000
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs b/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs
index 51361c5034e..d12342c7df3 100644
--- a/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs
+++ b/snippets/csharp/System/TimeSpan/FromDays/fromticks.cs
@@ -4,44 +4,42 @@
class FromTicksDemo
{
- static void GenTimeSpanFromTicks( long ticks )
+ static void GenTimeSpanFromTicks(long ticks)
{
- // Create a TimeSpan object and TimeSpan string from
+ // Create a TimeSpan object and TimeSpan string from
// a number of ticks.
- TimeSpan interval = TimeSpan.FromTicks( ticks );
- string timeInterval = interval.ToString( );
+ TimeSpan interval = TimeSpan.FromTicks(ticks);
+ string timeInterval = interval.ToString();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,21}{1,26}", ticks, timeInterval );
- }
+ Console.WriteLine($"{ticks,21}{timeInterval,26}");
+ }
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.FromTicks( long )\n" +
- "generates the following output.\n" );
- Console.WriteLine( "{0,21}{1,18}",
- "FromTicks", "TimeSpan" );
- Console.WriteLine( "{0,21}{1,18}",
- "---------", "--------" );
+ "generates the following output.\n");
+ Console.WriteLine($"{"FromTicks",21}{"TimeSpan",18}");
+ Console.WriteLine($"{"---------",21}{"--------",18}");
- GenTimeSpanFromTicks( 1 );
- GenTimeSpanFromTicks( 12345 );
- GenTimeSpanFromTicks( 123456789 );
- GenTimeSpanFromTicks( 1234567898765 );
- GenTimeSpanFromTicks( 12345678987654321 );
- GenTimeSpanFromTicks( 10000000 );
- GenTimeSpanFromTicks( 600000000 );
- GenTimeSpanFromTicks( 36000000000 );
- GenTimeSpanFromTicks( 864000000000 );
- GenTimeSpanFromTicks( 18012202000000 );
- }
-}
+ GenTimeSpanFromTicks(1);
+ GenTimeSpanFromTicks(12345);
+ GenTimeSpanFromTicks(123456789);
+ GenTimeSpanFromTicks(1234567898765);
+ GenTimeSpanFromTicks(12345678987654321);
+ GenTimeSpanFromTicks(10000000);
+ GenTimeSpanFromTicks(600000000);
+ GenTimeSpanFromTicks(36000000000);
+ GenTimeSpanFromTicks(864000000000);
+ GenTimeSpanFromTicks(18012202000000);
+ }
+}
/*
This example of TimeSpan.FromTicks( long )
diff --git a/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs b/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs
index 09bbdfd2983..d801da32c6c 100644
--- a/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs
+++ b/snippets/csharp/System/TimeSpan/GetHashCode/hashcode.cs
@@ -4,53 +4,51 @@
class GetHashCode
{
- static void DisplayHashCode( TimeSpan interval )
+ static void DisplayHashCode(TimeSpan interval)
{
- // Create a hash code and a string representation of
+ // Create a hash code and a string representation of
// the TimeSpan parameter.
- string timeInterval = interval.ToString( );
- int hashCode = interval.GetHashCode( );
+ string timeInterval = interval.ToString();
+ int hashCode = interval.GetHashCode();
- // Pad the end of the TimeSpan string with spaces if it
+ // Pad the end of the TimeSpan string with spaces if it
// does not contain milliseconds.
- int pIndex = timeInterval.IndexOf( ':' );
- pIndex = timeInterval.IndexOf( '.', pIndex );
- if( pIndex < 0 ) timeInterval += " ";
+ int pIndex = timeInterval.IndexOf(':');
+ pIndex = timeInterval.IndexOf('.', pIndex);
+ if (pIndex < 0) timeInterval += " ";
- Console.WriteLine( "{0,22} 0x{1:X8}, {1}",
- timeInterval, hashCode );
+ Console.WriteLine("{0,22} 0x{1:X8}, {1}",
+ timeInterval, hashCode);
}
- static void Main( )
+ static void Main()
{
Console.WriteLine(
"This example of TimeSpan.GetHashCode( ) generates " +
"the following \noutput, which displays " +
"the hash codes of representative TimeSpan \n" +
- "objects in hexadecimal and decimal formats.\n" );
- Console.WriteLine( "{0,22} {1,10}",
- "TimeSpan ", "Hash Code" );
- Console.WriteLine( "{0,22} {1,10}",
- "-------- ", "---------" );
+ "objects in hexadecimal and decimal formats.\n");
+ Console.WriteLine($"{"TimeSpan ",22} {"Hash Code",10}");
+ Console.WriteLine($"{"-------- ",22} {"---------",10}");
- DisplayHashCode( new TimeSpan( 0 ) );
- DisplayHashCode( new TimeSpan( 1 ) );
- DisplayHashCode( new TimeSpan( 0, 0, 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 0, 1, 0 ) );
- DisplayHashCode( new TimeSpan( 1, 0, 0 ) );
- DisplayHashCode( new TimeSpan( 36000000001 ) );
- DisplayHashCode( new TimeSpan( 0, 1, 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 1, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 1, 0, 0, 0 ) );
- DisplayHashCode( new TimeSpan( 864000000001 ) );
- DisplayHashCode( new TimeSpan( 1, 0, 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 1, 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 100, 0, 0, 0 ) );
- DisplayHashCode( new TimeSpan( 100, 0, 0, 0, 1 ) );
- DisplayHashCode( new TimeSpan( 100, 0, 0, 1 ) );
- }
-}
+ DisplayHashCode(new TimeSpan(0));
+ DisplayHashCode(new TimeSpan(1));
+ DisplayHashCode(new TimeSpan(0, 0, 0, 0, 1));
+ DisplayHashCode(new TimeSpan(0, 0, 1));
+ DisplayHashCode(new TimeSpan(0, 1, 0));
+ DisplayHashCode(new TimeSpan(1, 0, 0));
+ DisplayHashCode(new TimeSpan(36000000001));
+ DisplayHashCode(new TimeSpan(0, 1, 0, 0, 1));
+ DisplayHashCode(new TimeSpan(1, 0, 1));
+ DisplayHashCode(new TimeSpan(1, 0, 0, 0));
+ DisplayHashCode(new TimeSpan(864000000001));
+ DisplayHashCode(new TimeSpan(1, 0, 0, 0, 1));
+ DisplayHashCode(new TimeSpan(1, 0, 0, 1));
+ DisplayHashCode(new TimeSpan(100, 0, 0, 0));
+ DisplayHashCode(new TimeSpan(100, 0, 0, 0, 1));
+ DisplayHashCode(new TimeSpan(100, 0, 0, 1));
+ }
+}
/*
This example of TimeSpan.GetHashCode( ) generates the following
@@ -75,5 +73,5 @@ TimeSpan Hash Code
100.00:00:00 0x914F4E94, -1857073516
100.00:00:00.0010000 0x914F6984, -1857066620
100.00:00:01 0x91E7D814, -1847076844
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeSpan/MaxValue/fields.cs b/snippets/csharp/System/TimeSpan/MaxValue/fields.cs
index 4005b3ed569..7a1ebfad4a0 100644
--- a/snippets/csharp/System/TimeSpan/MaxValue/fields.cs
+++ b/snippets/csharp/System/TimeSpan/MaxValue/fields.cs
@@ -4,51 +4,51 @@
class TimeSpanFieldsDemo
{
- // Pad the end of a TimeSpan string with spaces if it does not
+ // Pad the end of a TimeSpan string with spaces if it does not
// contain milliseconds.
- static string Align( TimeSpan interval )
+ static string Align(TimeSpan interval)
{
- string intervalStr = interval.ToString( );
- int pointIndex = intervalStr.IndexOf( ':' );
+ string intervalStr = interval.ToString();
+ int pointIndex = intervalStr.IndexOf(':');
- pointIndex = intervalStr.IndexOf( '.', pointIndex );
- if( pointIndex < 0 ) intervalStr += " ";
+ pointIndex = intervalStr.IndexOf('.', pointIndex);
+ if (pointIndex < 0) intervalStr += " ";
return intervalStr;
- }
+ }
- static void Main( )
+ static void Main()
{
- const string numberFmt = "{0,-22}{1,18:N0}" ;
- const string timeFmt = "{0,-22}{1,26}" ;
+ const string numberFmt = "{0,-22}{1,18:N0}";
+ const string timeFmt = "{0,-22}{1,26}";
- Console.WriteLine(
+ Console.WriteLine(
"This example of the fields of the TimeSpan class" +
- "\ngenerates the following output.\n" );
- Console.WriteLine( numberFmt, "Field", "Value" );
- Console.WriteLine( numberFmt, "-----", "-----" );
+ "\ngenerates the following output.\n");
+ Console.WriteLine(numberFmt, "Field", "Value");
+ Console.WriteLine(numberFmt, "-----", "-----");
// Display the maximum, minimum, and zero TimeSpan values.
- Console.WriteLine( timeFmt, "Maximum TimeSpan",
- Align( TimeSpan.MaxValue ) );
- Console.WriteLine( timeFmt, "Minimum TimeSpan",
- Align( TimeSpan.MinValue ) );
- Console.WriteLine( timeFmt, "Zero TimeSpan",
- Align( TimeSpan.Zero ) );
- Console.WriteLine( );
+ Console.WriteLine(timeFmt, "Maximum TimeSpan",
+ Align(TimeSpan.MaxValue));
+ Console.WriteLine(timeFmt, "Minimum TimeSpan",
+ Align(TimeSpan.MinValue));
+ Console.WriteLine(timeFmt, "Zero TimeSpan",
+ Align(TimeSpan.Zero));
+ Console.WriteLine();
// Display the ticks-per-time-unit fields.
- Console.WriteLine( numberFmt, "Ticks per day",
- TimeSpan.TicksPerDay );
- Console.WriteLine( numberFmt, "Ticks per hour",
- TimeSpan.TicksPerHour );
- Console.WriteLine( numberFmt, "Ticks per minute",
- TimeSpan.TicksPerMinute );
- Console.WriteLine( numberFmt, "Ticks per second",
- TimeSpan.TicksPerSecond );
- Console.WriteLine( numberFmt, "Ticks per millisecond",
- TimeSpan.TicksPerMillisecond );
+ Console.WriteLine(numberFmt, "Ticks per day",
+ TimeSpan.TicksPerDay);
+ Console.WriteLine(numberFmt, "Ticks per hour",
+ TimeSpan.TicksPerHour);
+ Console.WriteLine(numberFmt, "Ticks per minute",
+ TimeSpan.TicksPerMinute);
+ Console.WriteLine(numberFmt, "Ticks per second",
+ TimeSpan.TicksPerSecond);
+ Console.WriteLine(numberFmt, "Ticks per millisecond",
+ TimeSpan.TicksPerMillisecond);
}
-}
+}
/*
This example of the fields of the TimeSpan class
diff --git a/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs b/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs
index c93d7f01285..a890a098afa 100644
--- a/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs
+++ b/snippets/csharp/System/TimeSpan/Overview/instantiate1.cs
@@ -1,74 +1,77 @@
-using System;
+using System;
public class Example
{
- public static void Main()
- {
- Implicit();
- Console.WriteLine();
- Explicit();
- Console.WriteLine();
- TimeSpanOperation();
- Console.WriteLine();
- Parse();
- Console.WriteLine();
- }
+ public static void Main()
+ {
+ Implicit();
+ Console.WriteLine();
+ Explicit();
+ Console.WriteLine();
+ TimeSpanOperation();
+ Console.WriteLine();
+ Parse();
+ Console.WriteLine();
+ }
- private static void Implicit()
- {
- //
- TimeSpan interval = new TimeSpan();
- Console.WriteLine(interval.Equals(TimeSpan.Zero)); // Displays "True".
- //
- }
-
- private static void Explicit()
- {
- //
- TimeSpan interval = new TimeSpan(2, 14, 18);
- Console.WriteLine(interval.ToString());
-
- // Displays "02:14:18".
- //
- }
-
- private static void TimeSpanOperation()
- {
- //
- DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
- DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
- TimeSpan travelTime = arrival - departure;
- Console.WriteLine($"{arrival} - {departure} = {travelTime}");
-
- // The example displays the following output:
- // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
- //
- }
-
- private static void Parse()
- {
- //
- string[] values = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"};
- foreach (string value in values)
- {
- try {
- TimeSpan ts = TimeSpan.Parse(value);
- Console.WriteLine($"'{value}' --> {ts}");
- }
- catch (FormatException) {
- Console.WriteLine($"Unable to parse '{value}'");
- }
- catch (OverflowException) {
- Console.WriteLine($"'{value}' is outside the range of a TimeSpan.");
- }
- }
-
- // The example displays the following output:
- // '12' --> 12.00:00:00
- // Unable to parse '31.'
- // '5.8:32:16' --> 5.08:32:16
- // '12:12:15.95' --> 12:12:15.9500000
- // Unable to parse '.12'
- //
- }
+ private static void Implicit()
+ {
+ //
+ TimeSpan interval = new();
+ Console.WriteLine(interval.Equals(TimeSpan.Zero)); // Displays "True".
+ //
+ }
+
+ private static void Explicit()
+ {
+ //
+ TimeSpan interval = new(2, 14, 18);
+ Console.WriteLine(interval);
+
+ // Displays "02:14:18".
+ //
+ }
+
+ private static void TimeSpanOperation()
+ {
+ //
+ DateTime departure = new(2010, 6, 12, 18, 32, 0);
+ DateTime arrival = new(2010, 6, 13, 22, 47, 0);
+ TimeSpan travelTime = arrival - departure;
+ Console.WriteLine($"{arrival} - {departure} = {travelTime}");
+
+ // The example displays the following output:
+ // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
+ //
+ }
+
+ private static void Parse()
+ {
+ //
+ string[] values = [ "12", "31.", "5.8:32:16", "12:12:15.95", ".12" ];
+ foreach (string value in values)
+ {
+ try
+ {
+ TimeSpan ts = TimeSpan.Parse(value);
+ Console.WriteLine($"'{value}' --> {ts}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"Unable to parse '{value}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{value}' is outside the range of a TimeSpan.");
+ }
+ }
+
+ // The example displays the following output:
+ // '12' --> 12.00:00:00
+ // Unable to parse '31.'
+ // '5.8:32:16' --> 5.08:32:16
+ // '12:12:15.95' --> 12:12:15.9500000
+ // Unable to parse '.12'
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/Overview/structure1.cs b/snippets/csharp/System/TimeSpan/Overview/structure1.cs
index f034ea01cd4..fa7e112f27c 100644
--- a/snippets/csharp/System/TimeSpan/Overview/structure1.cs
+++ b/snippets/csharp/System/TimeSpan/Overview/structure1.cs
@@ -2,43 +2,43 @@
public class StructureExample1
{
- public static void Main()
- {
- //
- // Define two dates.
- DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
- DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);
+ public static void Main()
+ {
+ //
+ // Define two dates.
+ DateTime date1 = new(2010, 1, 1, 8, 0, 15);
+ DateTime date2 = new(2010, 8, 18, 13, 30, 30);
- // Calculate the interval between the two dates.
- TimeSpan interval = date2 - date1;
- Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString());
+ // Calculate the interval between the two dates.
+ TimeSpan interval = date2 - date1;
+ Console.WriteLine($"{date2} - {date1} = {interval}");
- // Display individual properties of the resulting TimeSpan object.
- Console.WriteLine(" {0,-35} {1,20}", "Value of Days Component:", interval.Days);
- Console.WriteLine(" {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays);
- Console.WriteLine(" {0,-35} {1,20}", "Value of Hours Component:", interval.Hours);
- Console.WriteLine(" {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours);
- Console.WriteLine(" {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes);
- Console.WriteLine(" {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes);
- Console.WriteLine(" {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds);
- Console.WriteLine(" {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds);
- Console.WriteLine(" {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds);
- Console.WriteLine(" {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds);
- Console.WriteLine(" {0,-35} {1,20:N0}", "Ticks:", interval.Ticks);
-
- // This example displays the following output:
- // 8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
- // Value of Days Component: 229
- // Total Number of Days: 229.229340277778
- // Value of Hours Component: 5
- // Total Number of Hours: 5501.50416666667
- // Value of Minutes Component: 30
- // Total Number of Minutes: 330090.25
- // Value of Seconds Component: 15
- // Total Number of Seconds: 19,805,415
- // Value of Milliseconds Component: 0
- // Total Number of Milliseconds: 19,805,415,000
- // Ticks: 198,054,150,000,000
- //
- }
+ // Display individual properties of the resulting TimeSpan object.
+ Console.WriteLine($" {"Value of Days Component:",-35} {interval.Days,20}");
+ Console.WriteLine($" {"Total Number of Days:",-35} {interval.TotalDays,20}");
+ Console.WriteLine($" {"Value of Hours Component:",-35} {interval.Hours,20}");
+ Console.WriteLine($" {"Total Number of Hours:",-35} {interval.TotalHours,20}");
+ Console.WriteLine($" {"Value of Minutes Component:",-35} {interval.Minutes,20}");
+ Console.WriteLine($" {"Total Number of Minutes:",-35} {interval.TotalMinutes,20}");
+ Console.WriteLine($" {"Value of Seconds Component:",-35} {interval.Seconds,20:N0}");
+ Console.WriteLine($" {"Total Number of Seconds:",-35} {interval.TotalSeconds,20:N0}");
+ Console.WriteLine($" {"Value of Milliseconds Component:",-35} {interval.Milliseconds,20:N0}");
+ Console.WriteLine($" {"Total Number of Milliseconds:",-35} {interval.TotalMilliseconds,20:N0}");
+ Console.WriteLine($" {"Ticks:",-35} {interval.Ticks,20:N0}");
+
+ // This example displays the following output:
+ // 8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
+ // Value of Days Component: 229
+ // Total Number of Days: 229.229340277778
+ // Value of Hours Component: 5
+ // Total Number of Hours: 5501.50416666667
+ // Value of Minutes Component: 30
+ // Total Number of Minutes: 330090.25
+ // Value of Seconds Component: 15
+ // Total Number of Seconds: 19,805,415
+ // Value of Milliseconds Component: 0
+ // Total Number of Milliseconds: 19,805,415,000
+ // Ticks: 198,054,150,000,000
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/Overview/zero1.cs b/snippets/csharp/System/TimeSpan/Overview/zero1.cs
index 3ac36200ed2..89a1a293615 100644
--- a/snippets/csharp/System/TimeSpan/Overview/zero1.cs
+++ b/snippets/csharp/System/TimeSpan/Overview/zero1.cs
@@ -5,7 +5,7 @@ public class Example4
public static void Run()
{
//
- Random rnd = new Random();
+ Random rnd = new();
TimeSpan timeSpent = TimeSpan.Zero;
@@ -14,15 +14,9 @@ public static void Run()
Console.WriteLine($"Total time: {timeSpent}");
- TimeSpan GetTimeBeforeLunch()
- {
- return new TimeSpan(rnd.Next(3, 6), 0, 0);
- }
+ TimeSpan GetTimeBeforeLunch() => new TimeSpan(rnd.Next(3, 6), 0, 0);
- TimeSpan GetTimeAfterLunch()
- {
- return new TimeSpan(rnd.Next(3, 6), 0, 0);
- }
+ TimeSpan GetTimeAfterLunch() => new TimeSpan(rnd.Next(3, 6), 0, 0);
// The example displays output like the following:
// Total time: 08:00:00
diff --git a/snippets/csharp/System/TimeSpan/Parse/parse1.cs b/snippets/csharp/System/TimeSpan/Parse/parse1.cs
index 0604062b069..15b17ed39e4 100644
--- a/snippets/csharp/System/TimeSpan/Parse/parse1.cs
+++ b/snippets/csharp/System/TimeSpan/Parse/parse1.cs
@@ -1,39 +1,41 @@
//
using System;
-using System.Globalization;
+
using System.Threading;
public class Example1
{
- public static void Main()
- {
- string[] values = { "6", "6:12", "6:12:14", "6:12:14:45",
+ public static void Main()
+ {
+ string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45",
"6.12:14:45", "6:12:14:45.3448",
- "6:12:14:45,3448", "6:34:14:45" };
- string[] cultureNames = { "hr-HR", "en-US"};
+ "6:12:14:45,3448", "6:34:14:45" ];
+ string[] cultureNames = [ "hr-HR", "en-US" ];
- // Change the current culture.
- foreach (string cultureName in cultureNames)
- {
- Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
- Console.WriteLine("Current Culture: {0}",
- Thread.CurrentThread.CurrentCulture.Name);
- foreach (string value in values)
- {
- try {
- TimeSpan ts = TimeSpan.Parse(value);
- Console.WriteLine("{0} --> {1}", value, ts.ToString("c"));
- }
- catch (FormatException) {
- Console.WriteLine("{0}: Bad Format", value);
- }
- catch (OverflowException) {
- Console.WriteLine("{0}: Overflow", value);
+ // Change the current culture.
+ foreach (string cultureName in cultureNames)
+ {
+ Thread.CurrentThread.CurrentCulture = new(cultureName);
+ Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.Name}");
+ foreach (string value in values)
+ {
+ try
+ {
+ TimeSpan ts = TimeSpan.Parse(value);
+ Console.WriteLine($"{value} --> {ts.ToString("c")}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"{value}: Bad Format");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"{value}: Overflow");
+ }
}
- }
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Current Culture: hr-HR
diff --git a/snippets/csharp/System/TimeSpan/Parse/parse2.cs b/snippets/csharp/System/TimeSpan/Parse/parse2.cs
index fe7eb0fef9a..f73c82f9cab 100644
--- a/snippets/csharp/System/TimeSpan/Parse/parse2.cs
+++ b/snippets/csharp/System/TimeSpan/Parse/parse2.cs
@@ -1,46 +1,49 @@
//
using System;
using System.Globalization;
-using System.Text.RegularExpressions;
+
public class Example2
{
- public static void Main()
- {
- string[] values = { "6", "6:12", "6:12:14", "6:12:14:45",
+ public static void Main()
+ {
+ string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45",
"6.12:14:45", "6:12:14:45.3448",
- "6:12:14:45,3448", "6:34:14:45" };
- CultureInfo[] cultures = { new CultureInfo("en-US"),
+ "6:12:14:45,3448", "6:34:14:45" ];
+ CultureInfo[] cultures = [ new CultureInfo("en-US"),
new CultureInfo("ru-RU"),
- CultureInfo.InvariantCulture };
+ CultureInfo.InvariantCulture ];
- string header = String.Format("{0,-17}", "String");
- foreach (CultureInfo culture in cultures)
- header += culture.Equals(CultureInfo.InvariantCulture) ?
- String.Format("{0,20}", "Invariant") :
- String.Format("{0,20}", culture.Name);
- Console.WriteLine(header);
- Console.WriteLine();
+ string header = $"{"String",-17}";
+ foreach (CultureInfo culture in cultures)
+ header += culture.Equals(CultureInfo.InvariantCulture) ?
+ $"{"Invariant",20}" :
+ $"{culture.Name,20}";
+ Console.WriteLine(header);
+ Console.WriteLine();
- foreach (string value in values)
- {
- Console.Write("{0,-17}", value);
- foreach (CultureInfo culture in cultures)
- {
- try {
- TimeSpan ts = TimeSpan.Parse(value, culture);
- Console.Write("{0,20}", ts.ToString("c"));
- }
- catch (FormatException) {
- Console.Write("{0,20}", "Bad Format");
- }
- catch (OverflowException) {
- Console.Write("{0,20}", "Overflow");
+ foreach (string value in values)
+ {
+ Console.Write($"{value,-17}");
+ foreach (CultureInfo culture in cultures)
+ {
+ try
+ {
+ TimeSpan ts = TimeSpan.Parse(value, culture);
+ Console.Write($"{ts.ToString("c"),20}");
+ }
+ catch (FormatException)
+ {
+ Console.Write($"{"Bad Format",20}");
+ }
+ catch (OverflowException)
+ {
+ Console.Write($"{"Overflow",20}");
+ }
}
- }
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// String en-US ru-RU Invariant
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/Program.cs b/snippets/csharp/System/TimeSpan/ParseExact/Program.cs
new file mode 100644
index 00000000000..fa847f92faa
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/ParseExact/Program.cs
@@ -0,0 +1,4 @@
+ParseExactExample1.Run();
+ParseExactExample2.Run();
+ParseExactExample3.Run();
+ParseExactExample4.Run();
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj b/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/ParseExact/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs
index 58e5bae7e8f..5fa76cf250c 100644
--- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs
+++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample1.cs
@@ -2,148 +2,174 @@
using System;
using System.Globalization;
-public class Example
+public class ParseExactExample1
{
- public static void Main()
- {
- string intervalString, format;
- TimeSpan interval;
- CultureInfo culture;
-
- // Parse hour:minute value with "g" specifier current culture.
- intervalString = "17:14";
- format = "g";
- culture = CultureInfo.CurrentCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'",
- intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse hour:minute:second value with "G" specifier.
- intervalString = "17:14:48";
- format = "G";
- culture = CultureInfo.InvariantCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
+ public static void Run()
+ {
+ string intervalString, format;
+ TimeSpan interval;
+ CultureInfo culture;
- // Parse days:hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = new CultureInfo("fr-FR");
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48,153";
- format = "G";
- try {
- interval = TimeSpan.ParseExact(intervalString, format, culture);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
+ // Parse hour:minute value with "g" specifier current culture.
+ intervalString = "17:14";
+ format = "g";
+ culture = CultureInfo.CurrentCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
- // Parse a single number using the "c" standard format string.
- intervalString = "12";
- format = "c";
- try {
- interval = TimeSpan.ParseExact(intervalString, format, null);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse a single number using the "%h" custom format string.
- format = "%h";
- try {
- interval = TimeSpan.ParseExact(intervalString, format, null);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse a single number using the "%s" custom format string.
- format = "%s";
- try {
- interval = TimeSpan.ParseExact(intervalString, format, null);
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
- }
+ // Parse hour:minute:second value with "G" specifier.
+ intervalString = "17:14:48";
+ format = "G";
+ culture = CultureInfo.InvariantCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = new("fr-FR");
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48,153";
+ format = "G";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, culture);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "c" standard format string.
+ intervalString = "12";
+ format = "c";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, null);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "%h" custom format string.
+ format = "%h";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, null);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "%s" custom format string.
+ format = "%s";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format, null);
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+ }
}
// The example displays the following output:
// '17:14' --> 17:14:00
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs
index 23e8499b04e..ca705832f63 100644
--- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs
+++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample2.cs
@@ -2,155 +2,182 @@
using System;
using System.Globalization;
-public class Example
+public class ParseExactExample2
{
- public static void Main()
- {
- string intervalString, format;
- TimeSpan interval;
- CultureInfo culture = null;
-
- // Parse hour:minute value with custom format specifier.
- intervalString = "17:14";
- format = "h\\:mm";
- culture = CultureInfo.CurrentCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse hour:minute:second value with "g" specifier.
- intervalString = "17:14:48";
- format = "g";
- culture = CultureInfo.InvariantCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse hours:minute.second value with custom format specifier.
- intervalString = "17:14:48.153";
- format = @"h\:mm\:ss\.fff";
- culture = null;
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
+ public static void Run()
+ {
+ string intervalString, format;
+ TimeSpan interval;
+ CultureInfo culture = null;
- // Parse days:hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse days:hours:minute.second value with a custom format specifier.
- intervalString = "3:17:14:48.153";
- format = @"d\:hh\:mm\:ss\.fff";
- culture = null;
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48,153";
- format = "G";
- culture = new CultureInfo("fr-FR");
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
+ // Parse hour:minute value with custom format specifier.
+ intervalString = "17:14";
+ format = "h\\:mm";
+ culture = CultureInfo.CurrentCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
- // Parse a single number using the "c" standard format string.
- intervalString = "12";
- format = "c";
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse a single number using the "%h" custom format string.
- format = "%h";
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
-
- // Parse a single number using the "%s" custom format string.
- format = "%s";
- try {
- interval = TimeSpan.ParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative);
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- }
- catch (FormatException) {
- Console.WriteLine("'{0}': Bad Format for '{1}'", intervalString, format);
- }
- catch (OverflowException) {
- Console.WriteLine("'{0}': Overflow", intervalString);
- }
- }
+ // Parse hour:minute:second value with "g" specifier.
+ intervalString = "17:14:48";
+ format = "g";
+ culture = CultureInfo.InvariantCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse hours:minute.second value with custom format specifier.
+ intervalString = "17:14:48.153";
+ format = @"h\:mm\:ss\.fff";
+ culture = null;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with a custom format specifier.
+ intervalString = "3:17:14:48.153";
+ format = @"d\:hh\:mm\:ss\.fff";
+ culture = null;
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48,153";
+ format = "G";
+ culture = new("fr-FR");
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "c" standard format string.
+ intervalString = "12";
+ format = "c";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "%h" custom format string.
+ format = "%h";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+
+ // Parse a single number using the "%s" custom format string.
+ format = "%s";
+ try
+ {
+ interval = TimeSpan.ParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"'{intervalString}': Bad Format for '{format}'");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"'{intervalString}': Overflow");
+ }
+ }
}
// The example displays the following output:
// '17:14' (h\:mm) --> -17:14:00
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs
index 1aabe8a2dc4..a24d6a68a67 100644
--- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs
+++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample3.cs
@@ -2,30 +2,34 @@
using System;
using System.Globalization;
-public class Example
+public class ParseExactExample3
{
- public static void Main()
- {
- string[] inputs = { "3", "16:42", "1:6:52:35.0625",
- "1:6:52:35,0625" };
- string[] formats = { "g", "G", "%h"};
- TimeSpan interval;
- CultureInfo culture = new CultureInfo("fr-FR");
-
- // Parse each string in inputs using formats and the fr-FR culture.
- foreach (string input in inputs) {
- try {
- interval = TimeSpan.ParseExact(input, formats, culture);
- Console.WriteLine("{0} --> {1:c}", input, interval);
- }
- catch (FormatException) {
- Console.WriteLine("{0} --> Bad Format", input);
- }
- catch (OverflowException) {
- Console.WriteLine("{0} --> Overflow", input);
- }
- }
- }
+ public static void Run()
+ {
+ string[] inputs = [ "3", "16:42", "1:6:52:35.0625",
+ "1:6:52:35,0625" ];
+ string[] formats = [ "g", "G", "%h" ];
+ TimeSpan interval;
+ CultureInfo culture = new("fr-FR");
+
+ // Parse each string in inputs using formats and the fr-FR culture.
+ foreach (string input in inputs)
+ {
+ try
+ {
+ interval = TimeSpan.ParseExact(input, formats, culture);
+ Console.WriteLine($"{input} --> {interval:c}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"{input} --> Bad Format");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"{input} --> Overflow");
+ }
+ }
+ }
}
// The example displays the following output:
// 3 --> 03:00:00
diff --git a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs
index 95adf76f4e6..4b77efe4d6b 100644
--- a/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs
+++ b/snippets/csharp/System/TimeSpan/ParseExact/parseexactexample4.cs
@@ -2,31 +2,35 @@
using System;
using System.Globalization;
-public class Example
+public class ParseExactExample4
{
- public static void Main()
- {
- string[] inputs = { "3", "16:42", "1:6:52:35.0625",
- "1:6:52:35,0625" };
- string[] formats = { "%h", "g", "G" };
- TimeSpan interval;
- CultureInfo culture = new CultureInfo("de-DE");
-
- // Parse each string in inputs using formats and the de-DE culture.
- foreach (string input in inputs) {
- try {
- interval = TimeSpan.ParseExact(input, formats, culture,
- TimeSpanStyles.AssumeNegative);
- Console.WriteLine("{0} --> {1:c}", input, interval);
- }
- catch (FormatException) {
- Console.WriteLine("{0} --> Bad Format", input);
- }
- catch (OverflowException) {
- Console.WriteLine("{0} --> Overflow", input);
- }
- }
- }
+ public static void Run()
+ {
+ string[] inputs = [ "3", "16:42", "1:6:52:35.0625",
+ "1:6:52:35,0625" ];
+ string[] formats = [ "%h", "g", "G" ];
+ TimeSpan interval;
+ CultureInfo culture = new("de-DE");
+
+ // Parse each string in inputs using formats and the de-DE culture.
+ foreach (string input in inputs)
+ {
+ try
+ {
+ interval = TimeSpan.ParseExact(input, formats, culture,
+ TimeSpanStyles.AssumeNegative);
+ Console.WriteLine($"{input} --> {interval:c}");
+ }
+ catch (FormatException)
+ {
+ Console.WriteLine($"{input} --> Bad Format");
+ }
+ catch (OverflowException)
+ {
+ Console.WriteLine($"{input} --> Overflow");
+ }
+ }
+ }
}
// The example displays the following output:
// 3 --> -03:00:00
diff --git a/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs b/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs
index ee6fac4a079..772922fe295 100644
--- a/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs
+++ b/snippets/csharp/System/TimeSpan/Subtract/subtract1.cs
@@ -2,35 +2,35 @@
public class Example
{
- public static void Main()
- {
- //
- TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16);
+ public static void Main()
+ {
+ //
+ TimeSpan baseTimeSpan = new(1, 12, 15, 16);
- // Create an array of timespan intervals.
- TimeSpan[] intervals = {
- TimeSpan.FromDays(1.5),
- TimeSpan.FromHours(1.5),
- TimeSpan.FromMinutes(45),
+ // Create an array of timespan intervals.
+ TimeSpan[] intervals = [
+ TimeSpan.FromDays(1.5),
+ TimeSpan.FromHours(1.5),
+ TimeSpan.FromMinutes(45),
TimeSpan.FromMilliseconds(505),
- new TimeSpan(1, 17, 32, 20),
- new TimeSpan(-8, 30, 0)
- };
+ new TimeSpan(1, 17, 32, 20),
+ new TimeSpan(-8, 30, 0)
+ ];
- // Calculate a new time interval by adding each element to the base interval.
- foreach (var interval in intervals)
- Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}",
- baseTimeSpan, interval, baseTimeSpan.Subtract(interval),
- interval < TimeSpan.Zero ? "-" : "",
- baseTimeSpan < interval.Duration() ? "-" : "");
+ // Calculate a new time interval by adding each element to the base interval.
+ foreach (var interval in intervals)
+ Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}",
+ baseTimeSpan, interval, baseTimeSpan.Subtract(interval),
+ interval < TimeSpan.Zero ? "-" : "",
+ baseTimeSpan < interval.Duration() ? "-" : "");
- // The example displays the following output:
- // 1:12:15:16 - 1:12:00:00.0000 = 0:00:15:16.0000
- // 1:12:15:16 - 0:01:30:00.0000 = 1:10:45:16.0000
- // 1:12:15:16 - 0:00:45:00.0000 = 1:11:30:16.0000
- // 1:12:15:16 - 0:00:00:00.5050 = 1:12:15:15.4950
- // 1:12:15:16 - 1:17:32:20.0000 = -0:05:17:04.0000
- // 1:12:15:16 - -0:07:30:00.0000 = 1:19:45:16.0000
- //
- }
+ // The example displays the following output:
+ // 1:12:15:16 - 1:12:00:00.0000 = 0:00:15:16.0000
+ // 1:12:15:16 - 0:01:30:00.0000 = 1:10:45:16.0000
+ // 1:12:15:16 - 0:00:45:00.0000 = 1:11:30:16.0000
+ // 1:12:15:16 - 0:00:00:00.5050 = 1:12:15:15.4950
+ // 1:12:15:16 - 1:17:32:20.0000 = -0:05:17:04.0000
+ // 1:12:15:16 - -0:07:30:00.0000 = 1:19:45:16.0000
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/ToString/Program.cs b/snippets/csharp/System/TimeSpan/ToString/Program.cs
new file mode 100644
index 00000000000..177d5246b61
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/ToString/Program.cs
@@ -0,0 +1,3 @@
+TimeSpanToStringExample.Run();
+Class1.Run();
+Example.Run();
diff --git a/snippets/csharp/System/TimeSpan/ToString/Project.csproj b/snippets/csharp/System/TimeSpan/ToString/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/ToString/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TimeSpan/ToString/ToString1.cs b/snippets/csharp/System/TimeSpan/ToString/ToString1.cs
index 173f1550dab..2c4fdfd08f1 100644
--- a/snippets/csharp/System/TimeSpan/ToString/ToString1.cs
+++ b/snippets/csharp/System/TimeSpan/ToString/ToString1.cs
@@ -1,48 +1,48 @@
using System;
-public class ToString
+public class TimeSpanToStringExample
{
- public static void Main()
- {
- //
- TimeSpan span;
-
- // Initialize a time span to zero.
- span = TimeSpan.Zero;
- Console.WriteLine(span);
-
- // Initialize a time span to 14 days.
- span = new TimeSpan(-14, 0, 0, 0, 0);
- Console.WriteLine(span);
-
- // Initialize a time span to 1:02:03.
- span = new TimeSpan(1, 2, 3);
- Console.WriteLine(span);
-
- // Initialize a time span to 250 milliseconds.
- span = new TimeSpan(0, 0, 0, 0, 250);
- Console.WriteLine(span);
-
- // Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds.
- span = new TimeSpan(99, 23, 59, 59, 999);
- Console.WriteLine(span);
-
- // Initialize a time span to 3 hours.
- span = new TimeSpan(3, 0, 0);
- Console.WriteLine(span);
-
- // Initialize a timespan to 25 milliseconds.
- span = new TimeSpan(0, 0, 0, 0, 25);
- Console.WriteLine(span);
-
- // The example displays the following output:
- // 00:00:00
- // -14.00:00:00
- // 01:02:03
- // 00:00:00.2500000
- // 99.23:59:59.9990000
- // 03:00:00
- // 00:00:00.0250000
- //
- }
+ public static void Run()
+ {
+ //
+ TimeSpan span;
+
+ // Initialize a time span to zero.
+ span = TimeSpan.Zero;
+ Console.WriteLine(span);
+
+ // Initialize a time span to 14 days.
+ span = new(-14, 0, 0, 0, 0);
+ Console.WriteLine(span);
+
+ // Initialize a time span to 1:02:03.
+ span = new(1, 2, 3);
+ Console.WriteLine(span);
+
+ // Initialize a time span to 250 milliseconds.
+ span = new(0, 0, 0, 0, 250);
+ Console.WriteLine(span);
+
+ // Initialize a time span to 99 days, 23 hours, 59 minutes, and 59.999 seconds.
+ span = new(99, 23, 59, 59, 999);
+ Console.WriteLine(span);
+
+ // Initialize a time span to 3 hours.
+ span = new(3, 0, 0);
+ Console.WriteLine(span);
+
+ // Initialize a timespan to 25 milliseconds.
+ span = new(0, 0, 0, 0, 25);
+ Console.WriteLine(span);
+
+ // The example displays the following output:
+ // 00:00:00
+ // -14.00:00:00
+ // 01:02:03
+ // 00:00:00.2500000
+ // 99.23:59:59.9990000
+ // 03:00:00
+ // 00:00:00.0250000
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/ToString/tostring3.cs b/snippets/csharp/System/TimeSpan/ToString/tostring3.cs
index 13e72927122..227ae2cf0f3 100644
--- a/snippets/csharp/System/TimeSpan/ToString/tostring3.cs
+++ b/snippets/csharp/System/TimeSpan/ToString/tostring3.cs
@@ -2,69 +2,69 @@
public class Class1
{
- public static void Main()
- {
- //
- TimeSpan[] spans = {
- TimeSpan.Zero,
- new TimeSpan(-14, 0, 0, 0, 0),
- new TimeSpan(1, 2, 3),
- new TimeSpan(0, 0, 0, 0, 250),
+ public static void Run()
+ {
+ //
+ TimeSpan[] spans = [
+ TimeSpan.Zero,
+ new TimeSpan(-14, 0, 0, 0, 0),
+ new TimeSpan(1, 2, 3),
+ new TimeSpan(0, 0, 0, 0, 250),
new TimeSpan(99, 23, 59, 59, 999),
- new TimeSpan(3, 0, 0),
- new TimeSpan(0, 0, 0, 0, 25)
- };
+ new TimeSpan(3, 0, 0),
+ new TimeSpan(0, 0, 0, 0, 25)
+ ];
- string[] fmts = { "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" };
- foreach (TimeSpan span in spans)
- {
- foreach (string fmt in fmts)
- Console.WriteLine("{0}: {1}", fmt, span.ToString(fmt));
+ string[] fmts = [ "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" ];
+ foreach (TimeSpan span in spans)
+ {
+ foreach (string fmt in fmts)
+ Console.WriteLine($"{fmt}: {span.ToString(fmt)}");
- Console.WriteLine();
- }
- // The example displays the following output:
- // c: 00:00:00
- // g: 0:00:00
- // G: 0:00:00:00.0000000
- // hh\:mm\:ss: 00:00:00
- // %m' min.': 0 min.
- //
- // c: -14.00:00:00
- // g: -14:0:00:00
- // G: -14:00:00:00.0000000
- // hh\:mm\:ss: 00:00:00
- // %m' min.': 0 min.
- //
- // c: 01:02:03
- // g: 1:02:03
- // G: 0:01:02:03.0000000
- // hh\:mm\:ss: 01:02:03
- // %m' min.': 2 min.
- //
- // c: 00:00:00.2500000
- // g: 0:00:00.25
- // G: 0:00:00:00.2500000
- // hh\:mm\:ss: 00:00:00
- // %m' min.': 0 min.
- //
- // c: 99.23:59:59.9990000
- // g: 99:23:59:59.999
- // G: 99:23:59:59.9990000
- // hh\:mm\:ss: 23:59:59
- // %m' min.': 59 min.
- //
- // c: 03:00:00
- // g: 3:00:00
- // G: 0:03:00:00.0000000
- // hh\:mm\:ss: 03:00:00
- // %m' min.': 0 min.
- //
- // c: 00:00:00.0250000
- // g: 0:00:00.025
- // G: 0:00:00:00.0250000
- // hh\:mm\:ss: 00:00:00
- // %m' min.': 0 min.
- //
- }
+ Console.WriteLine();
+ }
+ // The example displays the following output:
+ // c: 00:00:00
+ // g: 0:00:00
+ // G: 0:00:00:00.0000000
+ // hh\:mm\:ss: 00:00:00
+ // %m' min.': 0 min.
+ //
+ // c: -14.00:00:00
+ // g: -14:0:00:00
+ // G: -14:00:00:00.0000000
+ // hh\:mm\:ss: 00:00:00
+ // %m' min.': 0 min.
+ //
+ // c: 01:02:03
+ // g: 1:02:03
+ // G: 0:01:02:03.0000000
+ // hh\:mm\:ss: 01:02:03
+ // %m' min.': 2 min.
+ //
+ // c: 00:00:00.2500000
+ // g: 0:00:00.25
+ // G: 0:00:00:00.2500000
+ // hh\:mm\:ss: 00:00:00
+ // %m' min.': 0 min.
+ //
+ // c: 99.23:59:59.9990000
+ // g: 99:23:59:59.999
+ // G: 99:23:59:59.9990000
+ // hh\:mm\:ss: 23:59:59
+ // %m' min.': 59 min.
+ //
+ // c: 03:00:00
+ // g: 3:00:00
+ // G: 0:03:00:00.0000000
+ // hh\:mm\:ss: 03:00:00
+ // %m' min.': 0 min.
+ //
+ // c: 00:00:00.0250000
+ // g: 0:00:00.025
+ // G: 0:00:00:00.0250000
+ // hh\:mm\:ss: 00:00:00
+ // %m' min.': 0 min.
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/ToString/tostring4.cs b/snippets/csharp/System/TimeSpan/ToString/tostring4.cs
index abfc9d0e3cb..341876b4264 100644
--- a/snippets/csharp/System/TimeSpan/ToString/tostring4.cs
+++ b/snippets/csharp/System/TimeSpan/ToString/tostring4.cs
@@ -4,36 +4,33 @@
public class Example
{
- public static void Main()
- {
- TimeSpan[] intervals = { new TimeSpan(38, 30, 15),
- new TimeSpan(16, 14, 30) };
- CultureInfo[] cultures = { new CultureInfo("en-US"),
- new CultureInfo("fr-FR") };
- string[] formats = {"c", "g", "G", @"hh\:mm\:ss" };
- Console.WriteLine("{0,12} Format {1,22} {2,22}\n",
- "Interval", cultures[0].Name, cultures[1].Name);
+ public static void Run()
+ {
+ TimeSpan[] intervals = [ new TimeSpan(38, 30, 15),
+ new TimeSpan(16, 14, 30) ];
+ CultureInfo[] cultures = [ new CultureInfo("en-US"),
+ new CultureInfo("fr-FR") ];
+ string[] formats = [ "c", "g", "G", @"hh\:mm\:ss" ];
+ Console.WriteLine($"{"Interval",12} Format {cultures[0].Name,22} {cultures[1].Name,22}\n");
- foreach (var interval in intervals) {
- foreach (var fmt in formats)
- Console.WriteLine("{0,12} {1,10} {2,22} {3,22}",
- interval, fmt,
- interval.ToString(fmt, cultures[0]),
- interval.ToString(fmt, cultures[1]));
- Console.WriteLine();
- }
- }
+ foreach (var interval in intervals)
+ {
+ foreach (string fmt in formats)
+ Console.WriteLine($"{interval,12} {fmt,10} {interval.ToString(fmt, cultures[0]),22} {interval.ToString(fmt, cultures[1]),22}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Interval Format en-US fr-FR
-//
+//
// 1.14:30:15 c 1.14:30:15 1.14:30:15
// 1.14:30:15 g 1:14:30:15 1:14:30:15
// 1.14:30:15 G 1:14:30:15.0000000 1:14:30:15,0000000
// 1.14:30:15 hh\:mm\:ss 14:30:15 14:30:15
-//
+//
// 16:14:30 c 16:14:30 16:14:30
// 16:14:30 g 16:14:30 16:14:30
// 16:14:30 G 0:16:14:30.0000000 0:16:14:30,0000000
// 16:14:30 hh\:mm\:ss 16:14:30 16:14:30
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs b/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs
index 14b4f8aa574..6f02c72adaa 100644
--- a/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs
+++ b/snippets/csharp/System/TimeSpan/TotalDays/totaldays.cs
@@ -2,28 +2,28 @@
public class Example
{
- public static void Main()
- {
- //
- // Define an interval of 3 days, 16+ hours.
- TimeSpan interval = new TimeSpan(3, 16, 42, 45, 750);
- Console.WriteLine("Value of TimeSpan: {0}", interval);
-
- Console.WriteLine("{0:N5} days, as follows:", interval.TotalDays);
- Console.WriteLine(" Days: {0,3}", interval.Days);
- Console.WriteLine(" Hours: {0,3}", interval.Hours);
- Console.WriteLine(" Minutes: {0,3}", interval.Minutes);
- Console.WriteLine(" Seconds: {0,3}", interval.Seconds);
- Console.WriteLine(" Milliseconds: {0,3}", interval.Milliseconds);
+ public static void Main()
+ {
+ //
+ // Define an interval of 3 days, 16+ hours.
+ TimeSpan interval = new(3, 16, 42, 45, 750);
+ Console.WriteLine($"Value of TimeSpan: {interval}");
- // The example displays the following output:
- // Value of TimeSpan: 3.16:42:45.7500000
- // 3.69636 days, as follows:
- // Days: 3
- // Hours: 16
- // Minutes: 42
- // Seconds: 45
- // Milliseconds: 750
- //
- }
+ Console.WriteLine($"{interval.TotalDays:N5} days, as follows:");
+ Console.WriteLine($" Days: {interval.Days,3}");
+ Console.WriteLine($" Hours: {interval.Hours,3}");
+ Console.WriteLine($" Minutes: {interval.Minutes,3}");
+ Console.WriteLine($" Seconds: {interval.Seconds,3}");
+ Console.WriteLine($" Milliseconds: {interval.Milliseconds,3}");
+
+ // The example displays the following output:
+ // Value of TimeSpan: 3.16:42:45.7500000
+ // 3.69636 days, as follows:
+ // Days: 3
+ // Hours: 16
+ // Minutes: 42
+ // Seconds: 45
+ // Milliseconds: 750
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs b/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs
index c667cc0911d..efc9ea06c12 100644
--- a/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs
+++ b/snippets/csharp/System/TimeSpan/TotalHours/totalhours.cs
@@ -2,27 +2,26 @@
public class Example
{
- public static void Main()
- {
- //
- // Define an interval of 1 day, 15+ hours.
- TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
- Console.WriteLine("Value of TimeSpan: {0}", interval);
-
- Console.WriteLine("{0:N5} hours, as follows:", interval.TotalHours);
- Console.WriteLine(" Hours: {0,3}",
- interval.Days * 24 + interval.Hours);
- Console.WriteLine(" Minutes: {0,3}", interval.Minutes);
- Console.WriteLine(" Seconds: {0,3}", interval.Seconds);
- Console.WriteLine(" Milliseconds: {0,3}", interval.Milliseconds);
+ public static void Main()
+ {
+ //
+ // Define an interval of 1 day, 15+ hours.
+ TimeSpan interval = new(1, 15, 42, 45, 750);
+ Console.WriteLine($"Value of TimeSpan: {interval}");
- // The example displays the following output:
- // Value of TimeSpan: 1.15:42:45.7500000
- // 39.71271 hours, as follows:
- // Hours: 39
- // Minutes: 42
- // Seconds: 45
- // Milliseconds: 750
- //
- }
+ Console.WriteLine($"{interval.TotalHours:N5} hours, as follows:");
+ Console.WriteLine($" Hours: {interval.Days * 24 + interval.Hours,3}");
+ Console.WriteLine($" Minutes: {interval.Minutes,3}");
+ Console.WriteLine($" Seconds: {interval.Seconds,3}");
+ Console.WriteLine($" Milliseconds: {interval.Milliseconds,3}");
+
+ // The example displays the following output:
+ // Value of TimeSpan: 1.15:42:45.7500000
+ // 39.71271 hours, as follows:
+ // Hours: 39
+ // Minutes: 42
+ // Seconds: 45
+ // Milliseconds: 750
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs b/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs
index d79e8f3206c..53e4c8b9508 100644
--- a/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs
+++ b/snippets/csharp/System/TimeSpan/TotalMilliseconds/totalmilliseconds.cs
@@ -2,28 +2,27 @@
public class Example
{
- public static void Main()
- {
- //
- // Define an interval of 1 day, 15+ hours.
- TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
- Console.WriteLine("Value of TimeSpan: {0}", interval);
-
- Console.WriteLine("There are {0:N5} milliseconds, as follows:", interval.TotalMilliseconds);
- long nMilliseconds = interval.Days * 24 * 60 * 60 * 1000 +
- interval.Hours *60 * 60 * 1000 +
- interval.Minutes * 60 * 1000 +
- interval.Seconds * 1000 +
- interval.Milliseconds;
- Console.WriteLine(" Milliseconds: {0,18:N0}", nMilliseconds);
- Console.WriteLine(" Ticks: {0,18:N0}",
- nMilliseconds * 10000 - interval.Ticks);
+ public static void Main()
+ {
+ //
+ // Define an interval of 1 day, 15+ hours.
+ TimeSpan interval = new(1, 15, 42, 45, 750);
+ Console.WriteLine($"Value of TimeSpan: {interval}");
- // The example displays the following output:
- // Value of TimeSpan: 1.15:42:45.7500000
- // There are 142,965,750.00000 milliseconds, as follows:
- // Milliseconds: 142,965,750
- // Ticks: 0
- //
- }
+ Console.WriteLine($"There are {interval.TotalMilliseconds:N5} milliseconds, as follows:");
+ long nMilliseconds = interval.Days * 24 * 60 * 60 * 1000 +
+ interval.Hours * 60 * 60 * 1000 +
+ interval.Minutes * 60 * 1000 +
+ interval.Seconds * 1000 +
+ interval.Milliseconds;
+ Console.WriteLine($" Milliseconds: {nMilliseconds,18:N0}");
+ Console.WriteLine($" Ticks: {nMilliseconds * 10000 - interval.Ticks,18:N0}");
+
+ // The example displays the following output:
+ // Value of TimeSpan: 1.15:42:45.7500000
+ // There are 142,965,750.00000 milliseconds, as follows:
+ // Milliseconds: 142,965,750
+ // Ticks: 0
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs b/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs
index b3aa641a06d..534257ccf03 100644
--- a/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs
+++ b/snippets/csharp/System/TimeSpan/TotalMinutes/totalminutes.cs
@@ -2,26 +2,26 @@
public class Example
{
- public static void Main()
- {
- //
- // Define an interval of 1 day, 15+ hours.
- TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
- Console.WriteLine("Value of TimeSpan: {0}", interval);
-
- Console.WriteLine("{0:N5} minutes, as follows:", interval.TotalMinutes);
- Console.WriteLine(" Minutes: {0,5}", interval.Days * 24 * 60 +
- interval.Hours * 60 +
- interval.Minutes);
- Console.WriteLine(" Seconds: {0,5}", interval.Seconds);
- Console.WriteLine(" Milliseconds: {0,5}", interval.Milliseconds);
+ public static void Main()
+ {
+ //
+ // Define an interval of 1 day, 15+ hours.
+ TimeSpan interval = new(1, 15, 42, 45, 750);
+ Console.WriteLine($"Value of TimeSpan: {interval}");
- // The example displays the following output:
- // Value of TimeSpan: 1.15:42:45.7500000
- // 2,382.76250 minutes, as follows:
- // Minutes: 2382
- // Seconds: 45
- // Milliseconds: 750
- //
- }
+ Console.WriteLine($"{interval.TotalMinutes:N5} minutes, as follows:");
+ Console.WriteLine($" Minutes: {interval.Days * 24 * 60 +
+ interval.Hours * 60 +
+ interval.Minutes,5}");
+ Console.WriteLine($" Seconds: {interval.Seconds,5}");
+ Console.WriteLine($" Milliseconds: {interval.Milliseconds,5}");
+
+ // The example displays the following output:
+ // Value of TimeSpan: 1.15:42:45.7500000
+ // 2,382.76250 minutes, as follows:
+ // Minutes: 2382
+ // Seconds: 45
+ // Milliseconds: 750
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs b/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs
index db041c79fd1..784ca177241 100644
--- a/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs
+++ b/snippets/csharp/System/TimeSpan/TotalSeconds/totalseconds.cs
@@ -2,25 +2,25 @@
public class Example
{
- public static void Main()
- {
- //
- // Define an interval of 1 day, 15+ hours.
- TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
- Console.WriteLine("Value of TimeSpan: {0}", interval);
-
- Console.WriteLine("{0:N5} seconds, as follows:", interval.TotalSeconds);
- Console.WriteLine(" Seconds: {0,8:N0}", interval.Days * 24 * 60 * 60 +
- interval.Hours *60 * 60 +
- interval.Minutes * 60 +
- interval.Seconds);
- Console.WriteLine(" Milliseconds: {0,8}", interval.Milliseconds);
+ public static void Main()
+ {
+ //
+ // Define an interval of 1 day, 15+ hours.
+ TimeSpan interval = new(1, 15, 42, 45, 750);
+ Console.WriteLine($"Value of TimeSpan: {interval}");
- // The example displays the following output:
- // Value of TimeSpan: 1.15:42:45.7500000
- // 142,965.75000 seconds, as follows:
- // Seconds: 142,965
- // Milliseconds: 750
- //
- }
+ Console.WriteLine($"{interval.TotalSeconds:N5} seconds, as follows:");
+ Console.WriteLine($" Seconds: {interval.Days * 24 * 60 * 60 +
+ interval.Hours * 60 * 60 +
+ interval.Minutes * 60 +
+ interval.Seconds,8:N0}");
+ Console.WriteLine($" Milliseconds: {interval.Milliseconds,8}");
+
+ // The example displays the following output:
+ // Value of TimeSpan: 1.15:42:45.7500000
+ // 142,965.75000 seconds, as follows:
+ // Seconds: 142,965
+ // Milliseconds: 750
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs b/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs
index 783b776fbfc..22d3336a17a 100644
--- a/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs
+++ b/snippets/csharp/System/TimeSpan/TryParse/TryParse1.cs
@@ -3,39 +3,37 @@
public class TryParse
{
- private static void ParseTimeSpan(string intervalStr)
- {
- // Write the first part of the output line.
- Console.Write( "{0,20} ", intervalStr );
+ private static void ParseTimeSpan(string intervalStr)
+ {
+ // Write the first part of the output line.
+ Console.Write($"{intervalStr,20} ");
- // Parse the parameter, and then convert it back to a string.
- TimeSpan intervalVal;
- if (TimeSpan.TryParse(intervalStr, out intervalVal))
- {
- string intervalToStr = intervalVal.ToString();
-
- // Pad the end of the TimeSpan string with spaces if it
- // does not contain milliseconds.
- int pIndex = intervalToStr.IndexOf(':');
- pIndex = intervalToStr.IndexOf('.', pIndex);
- if (pIndex < 0)
- intervalToStr += " ";
-
- Console.WriteLine("{0,21}", intervalToStr);
- // Handle failure of TryParse method.
- }
- else
- {
- Console.WriteLine("Parse operation failed.");
- }
- }
-
- public static void Main()
- {
- Console.WriteLine( "{0,20} {1,21}",
- "String to Parse", "TimeSpan" );
- Console.WriteLine( "{0,20} {1,21}",
- "---------------", "---------------------" );
+ // Parse the parameter, and then convert it back to a string.
+ TimeSpan intervalVal;
+ if (TimeSpan.TryParse(intervalStr, out intervalVal))
+ {
+ string intervalToStr = intervalVal.ToString();
+
+ // Pad the end of the TimeSpan string with spaces if it
+ // does not contain milliseconds.
+ int pIndex = intervalToStr.IndexOf(':');
+ pIndex = intervalToStr.IndexOf('.', pIndex);
+ if (pIndex < 0)
+ intervalToStr += " ";
+
+ Console.WriteLine($"{intervalToStr,21}");
+ // Handle failure of TryParse method.
+ }
+ else
+ {
+ Console.WriteLine("Parse operation failed.");
+ }
+ }
+
+ public static void Main()
+ {
+ Console.WriteLine($"{"String to Parse",20} {"TimeSpan",21}");
+ Console.WriteLine($"{"---------------",20} {"---------------------",21}");
ParseTimeSpan("0");
ParseTimeSpan("14");
@@ -61,7 +59,7 @@ public static void Main()
ParseTimeSpan("10.");
ParseTimeSpan("10.12");
ParseTimeSpan("10.12:00");
- }
+ }
}
// String to Parse TimeSpan
// --------------- ---------------------
diff --git a/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs b/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs
index 3824d3786a7..b8218ec673d 100644
--- a/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs
+++ b/snippets/csharp/System/TimeSpan/TryParse/tryparse2.cs
@@ -4,42 +4,42 @@
public class Example
{
- public static void Main()
- {
- string[] values = { "6", "6:12", "6:12:14", "6:12:14:45",
- "6.12:14:45", "6:12:14:45.3448",
- "6:12:14:45,3448", "6:34:14:45" };
- CultureInfo[] cultures = { new CultureInfo("en-US"),
+ public static void Main()
+ {
+ string[] values = [ "6", "6:12", "6:12:14", "6:12:14:45",
+ "6.12:14:45", "6:12:14:45.3448",
+ "6:12:14:45,3448", "6:34:14:45" ];
+ CultureInfo[] cultures = [ new CultureInfo("en-US"),
new CultureInfo("ru-RU"),
- CultureInfo.InvariantCulture };
-
- string header = String.Format("{0,-17}", "String");
- foreach (CultureInfo culture in cultures)
- header += culture.Equals(CultureInfo.InvariantCulture) ?
- String.Format("{0,20}", "Invariant") :
- String.Format("{0,20}", culture.Name);
+ CultureInfo.InvariantCulture ];
- Console.WriteLine(header);
- Console.WriteLine();
-
- foreach (string value in values)
- {
- Console.Write("{0,-17}", value);
- foreach (CultureInfo culture in cultures)
- {
- TimeSpan interval = new TimeSpan();
- if (TimeSpan.TryParse(value, culture, out interval))
- Console.Write("{0,20}", interval.ToString("c"));
- else
- Console.Write("{0,20}", "Unable to Parse");
- }
- Console.WriteLine();
- }
- }
+ string header = $"{"String",-17}";
+ foreach (CultureInfo culture in cultures)
+ header += culture.Equals(CultureInfo.InvariantCulture) ?
+ $"{"Invariant",20}" :
+ $"{culture.Name,20}";
+
+ Console.WriteLine(header);
+ Console.WriteLine();
+
+ foreach (string value in values)
+ {
+ Console.Write($"{value,-17}");
+ foreach (CultureInfo culture in cultures)
+ {
+ TimeSpan interval = new();
+ if (TimeSpan.TryParse(value, culture, out interval))
+ Console.Write($"{interval.ToString("c"),20}");
+ else
+ Console.Write($"{"Unable to Parse",20}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// String en-US ru-RU Invariant
-//
+//
// 6 6.00:00:00 6.00:00:00 6.00:00:00
// 6:12 06:12:00 06:12:00 06:12:00
// 6:12:14 06:12:14 06:12:14 06:12:14
@@ -48,4 +48,4 @@ public static void Main()
// 6:12:14:45.3448 6.12:14:45.3448000 Unable to Parse 6.12:14:45.3448000
// 6:12:14:45,3448 Unable to Parse 6.12:14:45.3448000 Unable to Parse
// 6:34:14:45 Unable to Parse Unable to Parse Unable to Parse
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs b/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs
new file mode 100644
index 00000000000..9f145ec0812
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/Program.cs
@@ -0,0 +1,4 @@
+TryParseExactExample1.Run();
+TryParseExactExample2.Run();
+TryParseExactExample3.Run();
+TryParseExactExample4.Run();
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj b/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs
index 08d4d54eb50..cbe17d7617a 100644
--- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample1.cs
@@ -2,93 +2,93 @@
using System;
using System.Globalization;
-public class Example
+public class TryParseExactExample1
{
- public static void Main()
- {
- string intervalString, format;
- TimeSpan interval;
- CultureInfo culture;
-
- // Parse hour:minute value with "g" specifier current culture.
- intervalString = "17:14";
- format = "g";
- culture = CultureInfo.CurrentCulture;
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse hour:minute:second value with "G" specifier.
- intervalString = "17:14:48";
- format = "G";
- culture = CultureInfo.InvariantCulture;
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
+ public static void Run()
+ {
+ string intervalString, format;
+ TimeSpan interval;
+ CultureInfo culture;
- // Parse days:hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = new CultureInfo("fr-FR");
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48,153";
- format = "G";
- if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
+ // Parse hour:minute value with "g" specifier current culture.
+ intervalString = "17:14";
+ format = "g";
+ culture = CultureInfo.CurrentCulture;
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
- // Parse a single number using the "c" standard format string.
- intervalString = "12";
- format = "c";
- if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse a single number using the "%h" custom format string.
- format = "%h";
- if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
-
- // Parse a single number using the "%s" custom format string.
- format = "%s";
- if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
- Console.WriteLine("'{0}' --> {1}", intervalString, interval);
- else
- Console.WriteLine("Unable to parse {0}", intervalString);
- }
+ // Parse hour:minute:second value with "G" specifier.
+ intervalString = "17:14:48";
+ format = "G";
+ culture = CultureInfo.InvariantCulture;
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = new("fr-FR");
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48,153";
+ format = "G";
+ if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse a single number using the "c" standard format string.
+ intervalString = "12";
+ format = "c";
+ if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse a single number using the "%h" custom format string.
+ format = "%h";
+ if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+
+ // Parse a single number using the "%s" custom format string.
+ format = "%s";
+ if (TimeSpan.TryParseExact(intervalString, format, null, out interval))
+ Console.WriteLine($"'{intervalString}' --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse {intervalString}");
+ }
}
// The example displays the following output:
// '17:14' --> 17:14:00
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs
index d496905410c..8901e941aea 100644
--- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample2.cs
@@ -2,110 +2,101 @@
using System;
using System.Globalization;
-public class Example
+public class TryParseExactExample2
{
- public static void Main()
- {
- string intervalString, format;
- TimeSpan interval;
- CultureInfo culture = null;
-
- // Parse hour:minute value with custom format specifier.
- intervalString = "17:14";
- format = "h\\:mm";
- culture = CultureInfo.CurrentCulture;
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse hour:minute:second value with "g" specifier.
- intervalString = "17:14:48";
- format = "g";
- culture = CultureInfo.InvariantCulture;
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse hours:minute.second value with custom format specifier.
- intervalString = "17:14:48.153";
- format = @"h\:mm\:ss\.fff";
- culture = null;
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
+ public static void Run()
+ {
+ string intervalString, format;
+ TimeSpan interval;
+ CultureInfo culture = null;
- // Parse days:hours:minute.second value with "G" specifier
- // and current (en-US) culture.
- intervalString = "3:17:14:48.153";
- format = "G";
- culture = CultureInfo.CurrentCulture;
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse days:hours:minute.second value with a custom format specifier.
- intervalString = "3:17:14:48.153";
- format = @"d\:hh\:mm\:ss\.fff";
- culture = null;
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse days:hours:minute.second value with "G" specifier
- // and fr-FR culture.
- intervalString = "3:17:14:48,153";
- format = "G";
- culture = new CultureInfo("fr-FR");
- if (TimeSpan.TryParseExact(intervalString, format,
- culture, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
+ // Parse hour:minute value with custom format specifier.
+ intervalString = "17:14";
+ format = "h\\:mm";
+ culture = CultureInfo.CurrentCulture;
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
- // Parse a single number using the "c" standard format string.
- intervalString = "12";
- format = "c";
- if (TimeSpan.TryParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse a single number using the "%h" custom format string.
- format = "%h";
- if (TimeSpan.TryParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
-
- // Parse a single number using the "%s" custom format string.
- format = "%s";
- if (TimeSpan.TryParseExact(intervalString, format,
- null, TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
- else
- Console.WriteLine("Unable to parse '{0}' using format {1}",
- intervalString, format);
- }
+ // Parse hour:minute:second value with "g" specifier.
+ intervalString = "17:14:48";
+ format = "g";
+ culture = CultureInfo.InvariantCulture;
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse hours:minute.second value with custom format specifier.
+ intervalString = "17:14:48.153";
+ format = @"h\:mm\:ss\.fff";
+ culture = null;
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and current (en-US) culture.
+ intervalString = "3:17:14:48.153";
+ format = "G";
+ culture = CultureInfo.CurrentCulture;
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse days:hours:minute.second value with a custom format specifier.
+ intervalString = "3:17:14:48.153";
+ format = @"d\:hh\:mm\:ss\.fff";
+ culture = null;
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse days:hours:minute.second value with "G" specifier
+ // and fr-FR culture.
+ intervalString = "3:17:14:48,153";
+ format = "G";
+ culture = new("fr-FR");
+ if (TimeSpan.TryParseExact(intervalString, format,
+ culture, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse a single number using the "c" standard format string.
+ intervalString = "12";
+ format = "c";
+ if (TimeSpan.TryParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse a single number using the "%h" custom format string.
+ format = "%h";
+ if (TimeSpan.TryParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+
+ // Parse a single number using the "%s" custom format string.
+ format = "%s";
+ if (TimeSpan.TryParseExact(intervalString, format,
+ null, TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"'{intervalString}' ({format}) --> {interval}");
+ else
+ Console.WriteLine($"Unable to parse '{intervalString}' using format {format}");
+ }
}
// The example displays the following output:
// '17:14' (h\:mm) --> -17:14:00
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs
index 8a1398b4bed..4caee9407ce 100644
--- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample3.cs
@@ -2,24 +2,25 @@
using System;
using System.Globalization;
-public class Example
+public class TryParseExactExample3
{
- public static void Main()
- {
- string[] inputs = { "3", "16:42", "1:6:52:35.0625",
- "1:6:52:35,0625" };
- string[] formats = { "g", "G", "%h"};
- TimeSpan interval;
- CultureInfo culture = new CultureInfo("fr-FR");
-
- // Parse each string in inputs using formats and the fr-FR culture.
- foreach (string input in inputs) {
- if(TimeSpan.TryParseExact(input, formats, culture, out interval))
- Console.WriteLine("{0} --> {1:c}", input, interval);
- else
- Console.WriteLine("Unable to parse {0}", input);
- }
- }
+ public static void Run()
+ {
+ string[] inputs = [ "3", "16:42", "1:6:52:35.0625",
+ "1:6:52:35,0625" ];
+ string[] formats = [ "g", "G", "%h" ];
+ TimeSpan interval;
+ CultureInfo culture = new("fr-FR");
+
+ // Parse each string in inputs using formats and the fr-FR culture.
+ foreach (string input in inputs)
+ {
+ if (TimeSpan.TryParseExact(input, formats, culture, out interval))
+ Console.WriteLine($"{input} --> {interval:c}");
+ else
+ Console.WriteLine($"Unable to parse {input}");
+ }
+ }
}
// The example displays the following output:
// 3 --> 03:00:00
diff --git a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs
index 1e53dd05895..1a0ac2931b9 100644
--- a/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs
+++ b/snippets/csharp/System/TimeSpan/TryParseExact/tryparseexactexample4.cs
@@ -2,25 +2,26 @@
using System;
using System.Globalization;
-public class Example
+public class TryParseExactExample4
{
- public static void Main()
- {
- string[] inputs = { "3", "16:42", "1:6:52:35.0625",
- "1:6:52:35,0625" };
- string[] formats = { "%h", "g", "G" };
- TimeSpan interval;
- CultureInfo culture = new CultureInfo("fr-FR");
-
- // Parse each string in inputs using formats and the fr-FR culture.
- foreach (string input in inputs) {
- if(TimeSpan.TryParseExact(input, formats, culture,
- TimeSpanStyles.AssumeNegative, out interval))
- Console.WriteLine("{0} --> {1:c}", input, interval);
- else
- Console.WriteLine("Unable to parse {0}", input);
- }
- }
+ public static void Run()
+ {
+ string[] inputs = [ "3", "16:42", "1:6:52:35.0625",
+ "1:6:52:35,0625" ];
+ string[] formats = [ "%h", "g", "G" ];
+ TimeSpan interval;
+ CultureInfo culture = new("fr-FR");
+
+ // Parse each string in inputs using formats and the fr-FR culture.
+ foreach (string input in inputs)
+ {
+ if (TimeSpan.TryParseExact(input, formats, culture,
+ TimeSpanStyles.AssumeNegative, out interval))
+ Console.WriteLine($"{input} --> {interval:c}");
+ else
+ Console.WriteLine($"Unable to parse {input}");
+ }
+ }
}
// The example displays the following output:
// 3 --> -03:00:00
diff --git a/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs b/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs
index 80fa199e085..9fec60265f2 100644
--- a/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs
+++ b/snippets/csharp/System/TimeSpan/op_Addition/Subtraction1.cs
@@ -2,22 +2,20 @@
public class Example
{
- public static void Main()
- {
- //
- var startWork = new TimeSpan(08,00,00);
- var endWork = new TimeSpan(18,30,00);
- var lunchBreak = new TimeSpan(1, 0, 0);
- var breaks = new TimeSpan(0, 30, 0);
-
- Console.WriteLine("Length of work day: {0}",
- endWork - startWork);
- Console.WriteLine("Actual time worked: {0}",
- endWork - startWork - (lunchBreak + breaks));
+ public static void Main()
+ {
+ //
+ var startWork = new TimeSpan(08, 00, 00);
+ var endWork = new TimeSpan(18, 30, 00);
+ var lunchBreak = new TimeSpan(1, 0, 0);
+ var breaks = new TimeSpan(0, 30, 0);
- // The example displays the following output:
- // Length of work day: 10:30:00
- // Actual time worked: 09:00:00
- //
- }
+ Console.WriteLine($"Length of work day: {endWork - startWork}");
+ Console.WriteLine($"Actual time worked: {endWork - startWork - (lunchBreak + breaks)}");
+
+ // The example displays the following output:
+ // Length of work day: 10:30:00
+ // Actual time worked: 09:00:00
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs b/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs
index bde80fdaa9b..155b5f3ca17 100644
--- a/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs
+++ b/snippets/csharp/System/TimeSpan/op_Addition/operators1.cs
@@ -2,21 +2,21 @@
public class Class1
{
- public static void Main()
- {
- //
- TimeSpan time1 = new TimeSpan(1, 0, 0, 0); // TimeSpan equivalent to 1 day.
- TimeSpan time2 = new TimeSpan(12, 0, 0); // TimeSpan equivalent to 1/2 day.
- TimeSpan time3 = time1 + time2; // Add the two time spans.
-
- Console.WriteLine(" {0,12}\n + {1,10}\n {3}\n {2,10}",
- time1, time2, time3, new String('_', 10));
+ public static void Main()
+ {
+ //
+ TimeSpan time1 = new(1, 0, 0, 0); // TimeSpan equivalent to 1 day.
+ TimeSpan time2 = new(12, 0, 0); // TimeSpan equivalent to 1/2 day.
+ TimeSpan time3 = time1 + time2; // Add the two time spans.
- // The example displays the following output:
- // 1.00:00:00
- // + 12:00:00
- // __________
- // 1.12:00:00
- //
- }
+ Console.WriteLine(" {0,12}\n + {1,10}\n {3}\n {2,10}",
+ time1, time2, time3, new string('_', 10));
+
+ // The example displays the following output:
+ // 1.00:00:00
+ // + 12:00:00
+ // __________
+ // 1.12:00:00
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs b/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs
index fdeeea2e211..b3d2ed170ca 100644
--- a/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs
+++ b/snippets/csharp/System/TimeSpan/op_Equality/relationalops.cs
@@ -4,45 +4,45 @@
class TSRelationalOpsDemo
{
- const string dataFmt = "{0,34} {1}" ;
+ const string dataFmt = "{0,34} {1}";
// Compare TimeSpan parameters, and display them with the results.
- static void CompareTimeSpans( TimeSpan Left, TimeSpan Right,
- string RightText )
+ static void CompareTimeSpans(TimeSpan Left, TimeSpan Right,
+ string RightText)
{
- Console.WriteLine( );
- Console.WriteLine( dataFmt, "Right: " + RightText, Right );
- Console.WriteLine( dataFmt, "Left == Right", Left == Right );
- Console.WriteLine( dataFmt, "Left > Right", Left > Right );
- Console.WriteLine( dataFmt, "Left >= Right", Left >= Right );
- Console.WriteLine( dataFmt, "Left != Right", Left != Right );
- Console.WriteLine( dataFmt, "Left < Right", Left < Right );
- Console.WriteLine( dataFmt, "Left <= Right", Left <= Right );
+ Console.WriteLine();
+ Console.WriteLine(dataFmt, "Right: " + RightText, Right);
+ Console.WriteLine(dataFmt, "Left == Right", Left == Right);
+ Console.WriteLine(dataFmt, "Left > Right", Left > Right);
+ Console.WriteLine(dataFmt, "Left >= Right", Left >= Right);
+ Console.WriteLine(dataFmt, "Left != Right", Left != Right);
+ Console.WriteLine(dataFmt, "Left < Right", Left < Right);
+ Console.WriteLine(dataFmt, "Left <= Right", Left <= Right);
}
- static void Main( )
+ static void Main()
{
- TimeSpan Left = new TimeSpan( 2, 0, 0 );
+ TimeSpan Left = new(2, 0, 0);
Console.WriteLine(
"This example of the TimeSpan relational operators " +
"generates \nthe following output. It creates several " +
"different TimeSpan \nobjects and compares them with " +
- "a 2-hour TimeSpan.\n" );
- Console.WriteLine( dataFmt,
- "Left: TimeSpan( 2, 0, 0 )", Left );
+ "a 2-hour TimeSpan.\n");
+ Console.WriteLine(dataFmt,
+ "Left: TimeSpan( 2, 0, 0 )", Left);
// Create objects to compare with a 2-hour TimeSpan.
- CompareTimeSpans( Left, new TimeSpan( 0, 120, 0 ),
- "TimeSpan( 0, 120, 0 )" );
- CompareTimeSpans( Left, new TimeSpan( 2, 0, 1 ),
- "TimeSpan( 2, 0, 1 )" );
- CompareTimeSpans( Left, new TimeSpan( 2, 0, -1 ),
- "TimeSpan( 2, 0, -1 )" );
- CompareTimeSpans( Left, TimeSpan.FromDays( 1.0 / 12D ),
- "TimeSpan.FromDays( 1 / 12 )" );
- }
-}
+ CompareTimeSpans(Left, new TimeSpan(0, 120, 0),
+ "TimeSpan( 0, 120, 0 )");
+ CompareTimeSpans(Left, new TimeSpan(2, 0, 1),
+ "TimeSpan( 2, 0, 1 )");
+ CompareTimeSpans(Left, new TimeSpan(2, 0, -1),
+ "TimeSpan( 2, 0, -1 )");
+ CompareTimeSpans(Left, TimeSpan.FromDays(1.0 / 12D),
+ "TimeSpan.FromDays( 1 / 12 )");
+ }
+}
/*
This example of the TimeSpan relational operators generates
@@ -82,5 +82,5 @@ objects and compares them with a 2-hour TimeSpan.
Left != Right False
Left < Right False
Left <= Right True
-*/
+*/
//
diff --git a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs
index 1e312e5fb10..7f3234b3836 100644
--- a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs
+++ b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/DateEnd/DateStart1.cs
@@ -5,76 +5,63 @@
public class Example
{
- public static void Main()
- {
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
-
- foreach (var zone in timeZones)
- {
- Console.WriteLine("{0} transition time information:", zone.StandardName);
- Console.WriteLine(" Time zone information: ");
- Console.WriteLine(" Base UTC Offset: {0}", zone.BaseUtcOffset);
- Console.WriteLine(" Supports DST: {0}", zone.SupportsDaylightSavingTime);
+ public static void Main()
+ {
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
- TimeZoneInfo.AdjustmentRule[] adjustmentRules= zone.GetAdjustmentRules();
-
- // Indicate that time zone has no adjustment rules
- if (adjustmentRules.Length == 0) {
- Console.WriteLine(" No adjustment rules defined.");
- }
- else {
- Console.WriteLine(" Adjustment Rules: {0}", adjustmentRules.Length);
- // Iterate adjustment rules
- foreach (var adjustmentRule in adjustmentRules) {
- Console.WriteLine(" Adjustment rule from {0:d} to {1:d}:",
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd);
- Console.WriteLine(" Delta: {0}", adjustmentRule.DaylightDelta);
- // Get start of transition
- TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
- // Display information on floating date rule
- if (!daylightStart.IsFixedDateRule)
- Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}",
- daylightStart.TimeOfDay,
- (WeekOfMonth) daylightStart.Week,
- daylightStart.DayOfWeek,
- dateInfo.GetMonthName(daylightStart.Month));
- // Display information on fixed date rule
- else
- Console.WriteLine(" Begins at {0:t} on {1} {2}",
- daylightStart.TimeOfDay,
- dateInfo.GetMonthName(daylightStart.Month),
- daylightStart.Day);
-
- // Get end of transition.
- TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
- // Display information on floating date rule.
- if (!daylightEnd.IsFixedDateRule)
- Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}",
- daylightEnd.TimeOfDay,
- (WeekOfMonth) daylightEnd.Week,
- daylightEnd.DayOfWeek,
- dateInfo.GetMonthName(daylightEnd.Month));
- // Display information on fixed date rule.
- else
- Console.WriteLine(" Ends at {0:t} on {1} {2}",
- daylightEnd.TimeOfDay,
- dateInfo.GetMonthName(daylightEnd.Month),
- daylightEnd.Day);
+ foreach (var zone in timeZones)
+ {
+ Console.WriteLine($"{zone.StandardName} transition time information:");
+ Console.WriteLine(" Time zone information: ");
+ Console.WriteLine($" Base UTC Offset: {zone.BaseUtcOffset}");
+ Console.WriteLine($" Supports DST: {zone.SupportsDaylightSavingTime}");
+
+ TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
+
+ // Indicate that time zone has no adjustment rules
+ if (adjustmentRules.Length == 0)
+ {
+ Console.WriteLine(" No adjustment rules defined.");
+ }
+ else
+ {
+ Console.WriteLine($" Adjustment Rules: {adjustmentRules.Length}");
+ // Iterate adjustment rules
+ foreach (var adjustmentRule in adjustmentRules)
+ {
+ Console.WriteLine($" Adjustment rule from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}:");
+ Console.WriteLine($" Delta: {adjustmentRule.DaylightDelta}");
+ // Get start of transition
+ TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
+ // Display information on floating date rule
+ if (!daylightStart.IsFixedDateRule)
+ Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {(WeekOfMonth)daylightStart.Week} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}");
+ // Display information on fixed date rule
+ else
+ Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on {dateInfo.GetMonthName(daylightStart.Month)} {daylightStart.Day}");
+
+ // Get end of transition.
+ TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
+ // Display information on floating date rule.
+ if (!daylightEnd.IsFixedDateRule)
+ Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on the {(WeekOfMonth)daylightEnd.Week} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}");
+ // Display information on fixed date rule.
+ else
+ Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on {dateInfo.GetMonthName(daylightEnd.Month)} {daylightEnd.Day}");
+ }
}
- }
- }
- }
+ }
+ }
- private enum WeekOfMonth
- {
- First = 1,
- Second = 2,
- Third = 3,
- Fourth = 4,
- Last = 5,
- }
+ private enum WeekOfMonth
+ {
+ First = 1,
+ Second = 2,
+ Third = 3,
+ Fourth = 4,
+ Last = 5,
+ }
}
// A portion of the output from the example might appear as follows:
// Tonga Standard Time transition time information:
diff --git a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs
index 2c6a43727c5..af88a729795 100644
--- a/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs
+++ b/snippets/csharp/System/TimeZoneInfo+AdjustmentRule/Overview/System.TimeZone2.AdjustmentRule.Class.cs
@@ -3,240 +3,214 @@
using System.Collections.ObjectModel;
using System.Globalization;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
namespace TimeZoneInfoCode
{
-public class AdjustmentRuleTest
-{
- private static void Main()
- {
- CreateCustomTimeZone();
- CompareRulesForEquality();
- ShowStartAndEndDates();
- }
+ public class AdjustmentRuleTest
+ {
+ private static void Main()
+ {
+ CreateCustomTimeZone();
+ CompareRulesForEquality();
+ ShowStartAndEndDates();
+ }
+
+ private static void CreateCustomTimeZone()
+ {
+ //
+ // Create alternate Central Standard Time to include historical time zone information
+ //
+ // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment;
+ List adjustmentList = [];
+ // Declare transition time variables to hold transition time information
+ TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
- private static void CreateCustomTimeZone()
- {
- //
- // Create alternate Central Standard Time to include historical time zone information
- //
- // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment;
- List adjustmentList = new List();
- // Declare transition time variables to hold transition time information
- TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
+ // Define end rule (for 1976-2006)
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday);
+ // Define rule (1976-1986)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule (1987-2006)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule (2007- )
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 01, 01), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
- // Define end rule (for 1976-2006)
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday);
- // Define rule (1976-1986)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31), delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule (1987-2006)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31), delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule (2007- )
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 01, 01), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
-
- // Create custom U.S. Central Standard Time zone
- TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0),
- "(GMT-06:00) Central Time (US Only)", "Central Standard Time",
- "Central Daylight Time", adjustmentList.ToArray());
- //
- }
+ // Create custom U.S. Central Standard Time zone
+ TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0),
+ "(GMT-06:00) Central Time (US Only)", "Central Standard Time",
+ "Central Daylight Time", adjustmentList.ToArray());
+ //
+ }
- private static void CompareRulesForEquality()
- {
- //
- string timeZoneName = "";
- // Get CST, Canadian CST, and Mexican CST adjustment rules
- TimeZoneInfo.AdjustmentRule[] usCstAdjustments = null;
- TimeZoneInfo.AdjustmentRule[] canCstAdjustments = null;
- TimeZoneInfo.AdjustmentRule[] mexCstAdjustments = null;
- try
- {
- timeZoneName = "Central Standard Time";
- usCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The {0} time zone is not defined in the registry.",
- timeZoneName);
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Data for the {0} time zone is invalid.",
- timeZoneName);
- }
- try
- {
- timeZoneName = "Canada Central Standard Time";
- canCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The {0} time zone is not defined in the registry.",
- timeZoneName);
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Data for the {0} time zone is invalid.",
- timeZoneName);
- }
- try
- {
- timeZoneName = "Central Standard Time (Mexico)";
- mexCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The {0} time zone is not defined in the registry.",
- timeZoneName);
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Data for the {0} time zone is invalid.",
- timeZoneName);
- }
- // Determine if CST and other time zones have the same rules
- foreach(TimeZoneInfo.AdjustmentRule rule in usCstAdjustments)
- {
- Console.WriteLine("Comparing Central Standard Time rule for {0:d} to {1:d} with:",
- rule.DateStart, rule.DateEnd);
- // Compare with Canada Central Standard Time
- if (canCstAdjustments.Length == 0)
- {
- Console.WriteLine(" Canada Central Standard Time has no adjustment rules.");
- }
- else
- {
- foreach (TimeZoneInfo.AdjustmentRule canRule in canCstAdjustments)
+ private static void CompareRulesForEquality()
+ {
+ //
+ string timeZoneName = "";
+ // Get CST, Canadian CST, and Mexican CST adjustment rules
+ TimeZoneInfo.AdjustmentRule[] usCstAdjustments = null;
+ TimeZoneInfo.AdjustmentRule[] canCstAdjustments = null;
+ TimeZoneInfo.AdjustmentRule[] mexCstAdjustments = null;
+ try
+ {
+ timeZoneName = "Central Standard Time";
+ usCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry.");
+ }
+ catch (InvalidTimeZoneException)
{
- Console.WriteLine(" Canadian CST for {0:d} to {1:d}: {2}",
- canRule.DateStart, canRule.DateEnd,
- rule.Equals(canRule) ? "Equal" : "Not Equal");
- }
- }
-
- // Compare with Mexico Central Standard Time
- if (mexCstAdjustments.Length == 0)
- {
- Console.WriteLine(" Mexican Central Standard Time has no adjustment rules.");
- }
- else
- {
- foreach (TimeZoneInfo.AdjustmentRule mexRule in mexCstAdjustments)
+ Console.WriteLine($"Data for the {timeZoneName} time zone is invalid.");
+ }
+ try
+ {
+ timeZoneName = "Canada Central Standard Time";
+ canCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
+ }
+ catch (TimeZoneNotFoundException)
{
- Console.WriteLine(" Mexican CST for {0:d} to {1:d}: {2}",
- mexRule.DateStart, mexRule.DateEnd,
- rule.Equals(mexRule) ? "Equal" : "Not Equal");
- }
- }
- }
- // This code displays the following output to the console:
- //
- // Comparing Central Standard Time rule for 1/1/0001 to 12/31/9999 with:
- // Canada Central Standard Time has no adjustment rules.
- // Mexican CST for 1/1/0001 to 12/31/9999: Equal
- //
- }
+ Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine($"Data for the {timeZoneName} time zone is invalid.");
+ }
+ try
+ {
+ timeZoneName = "Central Standard Time (Mexico)";
+ mexCstAdjustments = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName).GetAdjustmentRules();
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine($"The {timeZoneName} time zone is not defined in the registry.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine($"Data for the {timeZoneName} time zone is invalid.");
+ }
+ // Determine if CST and other time zones have the same rules
+ foreach (TimeZoneInfo.AdjustmentRule rule in usCstAdjustments)
+ {
+ Console.WriteLine($"Comparing Central Standard Time rule for {rule.DateStart:d} to {rule.DateEnd:d} with:");
+ // Compare with Canada Central Standard Time
+ if (canCstAdjustments.Length == 0)
+ {
+ Console.WriteLine(" Canada Central Standard Time has no adjustment rules.");
+ }
+ else
+ {
+ foreach (TimeZoneInfo.AdjustmentRule canRule in canCstAdjustments)
+ {
+ Console.WriteLine($" Canadian CST for {canRule.DateStart:d} to {canRule.DateEnd:d}: {(rule.Equals(canRule) ? "Equal" : "Not Equal")}");
+ }
+ }
- //
- private enum WeekOfMonth
- {
- First = 1,
- Second = 2,
- Third = 3,
- Fourth = 4,
- Last = 5,
- }
+ // Compare with Mexico Central Standard Time
+ if (mexCstAdjustments.Length == 0)
+ {
+ Console.WriteLine(" Mexican Central Standard Time has no adjustment rules.");
+ }
+ else
+ {
+ foreach (TimeZoneInfo.AdjustmentRule mexRule in mexCstAdjustments)
+ {
+ Console.WriteLine($" Mexican CST for {mexRule.DateStart:d} to {mexRule.DateEnd:d}: {(rule.Equals(mexRule) ? "Equal" : "Not Equal")}");
+ }
+ }
+ }
+ // This code displays the following output to the console:
+ //
+ // Comparing Central Standard Time rule for 1/1/0001 to 12/31/9999 with:
+ // Canada Central Standard Time has no adjustment rules.
+ // Mexican CST for 1/1/0001 to 12/31/9999: Equal
+ //
+ }
- private static void ShowStartAndEndDates()
- {
- // Get all time zones from system
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- string[] monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
- // Get each time zone
- foreach (TimeZoneInfo timeZone in timeZones)
- {
- TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
- // Display message for time zones with no adjustments
- if (adjustments.Length == 0)
- {
- Console.WriteLine("{0} has no adjustment rules", timeZone.StandardName);
- }
- else
- {
- // Handle time zones with 1 or 2+ adjustments differently
- bool showCount = false;
- int ctr = 0;
- string spacer = "";
-
- Console.WriteLine("{0} Adjustment rules", timeZone.StandardName);
- if (adjustments.Length > 1)
- {
- showCount = true;
- spacer = " ";
- }
- // Iterate adjustment rules
- foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
+ //
+ private enum WeekOfMonth
+ {
+ First = 1,
+ Second = 2,
+ Third = 3,
+ Fourth = 4,
+ Last = 5,
+ }
+
+ private static void ShowStartAndEndDates()
+ {
+ // Get all time zones from system
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ string[] monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
+ // Get each time zone
+ foreach (TimeZoneInfo timeZone in timeZones)
{
- if (showCount)
- {
- Console.WriteLine(" Adjustment rule #{0}", ctr+1);
- ctr++;
- }
- // Display general adjustment information
- Console.WriteLine("{0} Start Date: {1:D}", spacer, adjustment.DateStart);
- Console.WriteLine("{0} End Date: {1:D}", spacer, adjustment.DateEnd);
- Console.WriteLine("{0} Time Change: {1}:{2:00} hours", spacer,
- adjustment.DaylightDelta.Hours, adjustment.DaylightDelta.Minutes);
- // Get transition start information
- TimeZoneInfo.TransitionTime transitionStart = adjustment.DaylightTransitionStart;
- Console.Write("{0} Annual Start: ", spacer);
- if (transitionStart.IsFixedDateRule)
- {
- Console.WriteLine("On {0} {1} at {2:t}",
- monthNames[transitionStart.Month - 1],
- transitionStart.Day,
- transitionStart.TimeOfDay);
- }
- else
- {
- Console.WriteLine("The {0} {1} of {2} at {3:t}",
- ((WeekOfMonth)transitionStart.Week).ToString(),
- transitionStart.DayOfWeek.ToString(),
- monthNames[transitionStart.Month - 1],
- transitionStart.TimeOfDay);
- }
- // Get transition end information
- TimeZoneInfo.TransitionTime transitionEnd = adjustment.DaylightTransitionEnd;
- Console.Write("{0} Annual End: ", spacer);
- if (transitionEnd.IsFixedDateRule)
- {
- Console.WriteLine("On {0} {1} at {2:t}",
- monthNames[transitionEnd.Month - 1],
- transitionEnd.Day,
- transitionEnd.TimeOfDay);
- }
- else
- {
- Console.WriteLine("The {0} {1} of {2} at {3:t}",
- ((WeekOfMonth)transitionEnd.Week).ToString(),
- transitionEnd.DayOfWeek.ToString(),
- monthNames[transitionEnd.Month - 1],
- transitionEnd.TimeOfDay);
- }
+ TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
+ // Display message for time zones with no adjustments
+ if (adjustments.Length == 0)
+ {
+ Console.WriteLine($"{timeZone.StandardName} has no adjustment rules");
+ }
+ else
+ {
+ // Handle time zones with 1 or 2+ adjustments differently
+ bool showCount = false;
+ int ctr = 0;
+ string spacer = "";
+
+ Console.WriteLine($"{timeZone.StandardName} Adjustment rules");
+ if (adjustments.Length > 1)
+ {
+ showCount = true;
+ spacer = " ";
+ }
+ // Iterate adjustment rules
+ foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
+ {
+ if (showCount)
+ {
+ Console.WriteLine($" Adjustment rule #{ctr + 1}");
+ ctr++;
+ }
+ // Display general adjustment information
+ Console.WriteLine($"{spacer} Start Date: {adjustment.DateStart:D}");
+ Console.WriteLine($"{spacer} End Date: {adjustment.DateEnd:D}");
+ Console.WriteLine($"{spacer} Time Change: {adjustment.DaylightDelta.Hours}:{adjustment.DaylightDelta.Minutes:00} hours");
+ // Get transition start information
+ TimeZoneInfo.TransitionTime transitionStart = adjustment.DaylightTransitionStart;
+ Console.Write($"{spacer} Annual Start: ");
+ if (transitionStart.IsFixedDateRule)
+ {
+ Console.WriteLine($"On {monthNames[transitionStart.Month - 1]} {transitionStart.Day} at {transitionStart.TimeOfDay:t}");
+ }
+ else
+ {
+ Console.WriteLine($"The {((WeekOfMonth)transitionStart.Week)} {transitionStart.DayOfWeek} of {monthNames[transitionStart.Month - 1]} at {transitionStart.TimeOfDay:t}");
+ }
+ // Get transition end information
+ TimeZoneInfo.TransitionTime transitionEnd = adjustment.DaylightTransitionEnd;
+ Console.Write($"{spacer} Annual End: ");
+ if (transitionEnd.IsFixedDateRule)
+ {
+ Console.WriteLine($"On {monthNames[transitionEnd.Month - 1]} {transitionEnd.Day} at {transitionEnd.TimeOfDay:t}");
+ }
+ else
+ {
+ Console.WriteLine($"The {((WeekOfMonth)transitionEnd.Week)} {transitionEnd.DayOfWeek} of {monthNames[transitionEnd.Month - 1]} at {transitionEnd.TimeOfDay:t}");
+ }
+ }
+ }
+ Console.WriteLine();
}
- }
- Console.WriteLine();
- }
- }
- //
-}
+ }
+ //
+ }
} // end namespace
diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs
new file mode 100644
index 00000000000..9e1d688f17e
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Program.cs
@@ -0,0 +1,2 @@
+TransitionTimeExamplesFull.Run();
+TransitionTimeExamplesYear.Run();
diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs
index 49b940fa108..3109acd1f6b 100644
--- a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs
+++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/System.TimeZone2.TransitionTime.Class.cs
@@ -3,325 +3,271 @@
using System.Collections.ObjectModel;
using System.Globalization;
-[assembly:CLSCompliant(true)]
-public class TransitionTimeExamples
+[assembly: CLSCompliant(true)]
+public class TransitionTimeExamplesFull
{
- public static void Main()
- {
- TransitionTimeExamples tte = new TransitionTimeExamples();
-
- Console.WriteLine("***CompareForEquality()");
- tte.CompareForEquality();
- Console.WriteLine();
- Console.WriteLine("***CompareTransitionTimesForEquality()");
- tte.CompareTransitionTimesForEquality();
- Console.WriteLine();
- Console.WriteLine("***CreateTransitionRules()");
- tte.CreateTransitionRules();
- Console.WriteLine();
- Console.WriteLine("***GetFixedTransitionTimes()");
- tte.GetFixedTransitionTimes();
- Console.WriteLine();
- Console.WriteLine("***GetFloatingTransitionTimes()");
- tte.GetFloatingTransitionTimes();
- Console.WriteLine();
- Console.WriteLine("***GetTransitionTimes(2006)");
- tte.GetTransitionTimes(2006);
- AdditionalExamples ae = new AdditionalExamples();
- Console.WriteLine();
- Console.WriteLine("***GetAllTransitionTimes()");
- ae.GetAllTransitionTimes();
- }
+ public static void Run()
+ {
+ TransitionTimeExamplesFull tte = new();
- private void CompareForEquality()
- {
- //
- TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
- TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
- TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday);
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Console.WriteLine(tt1.Equals(tz)); // Returns False (overload with argument of type Object)
- Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself)
- Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values)
- Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values)
- //
- }
+ Console.WriteLine("***CompareForEquality()");
+ tte.CompareForEquality();
+ Console.WriteLine();
+ Console.WriteLine("***CompareTransitionTimesForEquality()");
+ tte.CompareTransitionTimesForEquality();
+ Console.WriteLine();
+ Console.WriteLine("***CreateTransitionRules()");
+ tte.CreateTransitionRules();
+ Console.WriteLine();
+ Console.WriteLine("***GetFixedTransitionTimes()");
+ tte.GetFixedTransitionTimes();
+ Console.WriteLine();
+ Console.WriteLine("***GetFloatingTransitionTimes()");
+ tte.GetFloatingTransitionTimes();
+ Console.WriteLine();
+ Console.WriteLine("***GetTransitionTimes(2006)");
+ tte.GetTransitionTimes(2006);
+ AdditionalExamples ae = new();
+ Console.WriteLine();
+ Console.WriteLine("***GetAllTransitionTimes()");
+ ae.GetAllTransitionTimes();
+ }
- private void CompareTransitionTimesForEquality()
- {
- //
- TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
- TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
- TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday);
- Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself)
- Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values)
- Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values)
- //
- }
+ private void CompareForEquality()
+ {
+ //
+ TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
+ TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
+ TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday);
+ TimeZoneInfo tz = TimeZoneInfo.Local;
+ Console.WriteLine(tt1.Equals(tz)); // Returns False (overload with argument of type Object)
+ Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself)
+ Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values)
+ Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values)
+ //
+ }
- private void CreateTransitionRules()
- {
- //
- // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
- TimeZoneInfo imaginaryTZ;
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment;
- List adjustmentList = new List();
- // Declare transition time variables to hold transition time information
- TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
-
- // Define a fictitious new time zone consisting of fixed and floating adjustment rules
- // Define fixed rule (for 1900-1955)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 15);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 3, 0, 0), 11, 15);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1900, 1, 1), new DateTime(1955, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define floating rule (for 1956- )
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 4, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1956, 1, 1), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
+ private void CompareTransitionTimesForEquality()
+ {
+ //
+ TimeZoneInfo.TransitionTime tt1 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
+ TimeZoneInfo.TransitionTime tt2 = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 02, 00, 00), 11, 03);
+ TimeZoneInfo.TransitionTime tt3 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 02, 00, 00), 10, 05, DayOfWeek.Sunday);
+ Console.WriteLine(tt1.Equals(tt1)); // Returns True (an object always equals itself)
+ Console.WriteLine(tt1.Equals(tt2)); // Returns True (identical property values)
+ Console.WriteLine(tt1.Equals(tt3)); // Returns False (different property values)
+ //
+ }
- // Create fictitious time zone
- imaginaryTZ = TimeZoneInfo.CreateCustomTimeZone("Fictitious Standard Time", new TimeSpan(-9, 0, 0),
- "(GMT-09:00) Fictitious Time", "Fictitious Standard Time",
- "Fictitious Daylight Time", adjustmentList.ToArray());
- //
- }
+ private void CreateTransitionRules()
+ {
+ //
+ // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
+ TimeZoneInfo imaginaryTZ;
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment;
+ List adjustmentList = [];
+ // Declare transition time variables to hold transition time information
+ TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
- //
- private void GetFixedTransitionTimes()
- {
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
- foreach (TimeZoneInfo zone in timeZones)
- {
- TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
- foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
- {
- TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
- if (daylightStart.IsFixedDateRule)
- Console.WriteLine("For {0}, daylight savings time begins at {1:t} on {2} {3} from {4:d} to {5:d}.",
- zone.StandardName,
- daylightStart.TimeOfDay,
- dateInfo.GetMonthName(daylightStart.Month),
- daylightStart.Day,
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd);
- TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
- if (daylightEnd.IsFixedDateRule)
- Console.WriteLine("For {0}, daylight savings time ends at {1:t} on {2} {3} from {4:d} to {5:d}.",
- zone.StandardName,
- daylightEnd.TimeOfDay,
- dateInfo.GetMonthName(daylightEnd.Month),
- daylightEnd.Day,
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd);
- }
- }
- }
- //
-
- //
- private enum WeekOfMonth
- {
- First = 1,
- Second = 2,
- Third = 3,
- Fourth = 4,
- Last = 5
- }
-
- private void GetFloatingTransitionTimes()
- {
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- foreach (TimeZoneInfo zone in timeZones)
- {
- TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
- DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
- foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
- {
- TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
- if (!daylightStart.IsFixedDateRule)
- Console.WriteLine("{0}, {1:d}-{2:d}: Begins at {3:t} on the {4} {5} of {6}.",
- zone.StandardName,
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd,
- daylightStart.TimeOfDay,
- ((WeekOfMonth)daylightStart.Week).ToString(),
- daylightStart.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightStart.Month));
+ // Define a fictitious new time zone consisting of fixed and floating adjustment rules
+ // Define fixed rule (for 1900-1955)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 15);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 3, 0, 0), 11, 15);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1900, 1, 1), new DateTime(1955, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define floating rule (for 1956- )
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 4, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1956, 1, 1), DateTime.MaxValue.Date, delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
- TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
- if (!daylightEnd.IsFixedDateRule)
- Console.WriteLine("{0}, {1:d}-{2:d}: Ends at {3:t} on the {4} {5} of {6}.",
- zone.StandardName,
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd,
- daylightEnd.TimeOfDay,
- ((WeekOfMonth)daylightEnd.Week).ToString(),
- daylightEnd.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightEnd.Month));
- }
- }
- }
- //
+ // Create fictitious time zone
+ imaginaryTZ = TimeZoneInfo.CreateCustomTimeZone("Fictitious Standard Time", new TimeSpan(-9, 0, 0),
+ "(GMT-09:00) Fictitious Time", "Fictitious Standard Time",
+ "Fictitious Daylight Time", adjustmentList.ToArray());
+ //
+ }
- private void GetTransitionTimes(int year)
- {
- // Instantiate DateTimeFormatInfo object for month names
- DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
+ //
+ private void GetFixedTransitionTimes()
+ {
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
+ foreach (TimeZoneInfo zone in timeZones)
+ {
+ TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
+ foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
+ {
+ TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
+ if (daylightStart.IsFixedDateRule)
+ Console.WriteLine($"For {zone.StandardName}, daylight savings time begins at {daylightStart.TimeOfDay:t} on {dateInfo.GetMonthName(daylightStart.Month)} {daylightStart.Day} from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}.");
+ TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
+ if (daylightEnd.IsFixedDateRule)
+ Console.WriteLine($"For {zone.StandardName}, daylight savings time ends at {daylightEnd.TimeOfDay:t} on {dateInfo.GetMonthName(daylightEnd.Month)} {daylightEnd.Day} from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}.");
+ }
+ }
+ }
+ //
- // Get and iterate time zones on local computer
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- foreach (TimeZoneInfo timeZone in timeZones)
- {
- Console.WriteLine("{0}:", timeZone.StandardName);
- TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
- if (adjustments.Length == 0)
- {
- Console.WriteLine(" No adjustment rules.");
- }
- else
- {
- // Iterate adjustment rules for time zone
- foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
+ //
+ private enum WeekOfMonth
+ {
+ First = 1,
+ Second = 2,
+ Third = 3,
+ Fourth = 4,
+ Last = 5
+ }
+
+ private void GetFloatingTransitionTimes()
+ {
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ foreach (TimeZoneInfo zone in timeZones)
+ {
+ TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
+ DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
+ foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
{
- // Determine if this adjustment rule covers year desired
- if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year)
- {
- TimeZoneInfo.TransitionTime startTransition, endTransition;
- // Determine if starting transition is fixed
- startTransition = adjustment.DaylightTransitionStart;
- // Determine if starting transition is fixed and display transition info for year
- if (startTransition.IsFixedDateRule)
- Console.WriteLine(" Begins on {0} {1} at {2:t}",
- dateFormat.GetMonthName(startTransition.Month),
- startTransition.Day,
- startTransition.TimeOfDay);
- else
- DisplayTransitionInfo(startTransition, year, "Begins on");
+ TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
+ if (!daylightStart.IsFixedDateRule)
+ Console.WriteLine($"{zone.StandardName}, {adjustmentRule.DateStart:d}-{adjustmentRule.DateEnd:d}: Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}.");
- // Determine if ending transition is fixed and display transition info for year
- endTransition = adjustment.DaylightTransitionEnd;
- if (endTransition.IsFixedDateRule)
- Console.WriteLine(" Ends on {0} {1} at {2:t}",
- dateFormat.GetMonthName(endTransition.Month),
- endTransition.Day,
- endTransition.TimeOfDay);
- else
- DisplayTransitionInfo(endTransition, year, "Ends on");
-
- break;
- }
+ TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
+ if (!daylightEnd.IsFixedDateRule)
+ Console.WriteLine($"{zone.StandardName}, {adjustmentRule.DateStart:d}-{adjustmentRule.DateEnd:d}: Ends at {daylightEnd.TimeOfDay:t} on the {((WeekOfMonth)daylightEnd.Week)} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}.");
}
- }
- }
- }
-
- private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label)
- {
- // For non-fixed date rules, get local calendar
- Calendar cal = CultureInfo.CurrentCulture.Calendar;
- // Get first day of week for transition
- // For example, the 3rd week starts no earlier than the 15th of the month
- int startOfWeek = transition.Week * 7 - 6;
- // What day of the week does the month start on?
- int firstDayOfWeek = (int) cal.GetDayOfWeek(new DateTime(year, transition.Month, startOfWeek));
- // Determine how much start date has to be adjusted
- int transitionDay;
- int changeDayOfWeek = (int) transition.DayOfWeek;
+ }
+ }
+ //
- if (firstDayOfWeek <= changeDayOfWeek)
- transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
- else
- transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
+ private void GetTransitionTimes(int year)
+ {
+ // Instantiate DateTimeFormatInfo object for month names
+ DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
- // Adjust for months with no fifth week
- if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
- transitionDay -= 7;
+ // Get and iterate time zones on local computer
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ foreach (TimeZoneInfo timeZone in timeZones)
+ {
+ Console.WriteLine($"{timeZone.StandardName}:");
+ TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
+ if (adjustments.Length == 0)
+ {
+ Console.WriteLine(" No adjustment rules.");
+ }
+ else
+ {
+ // Iterate adjustment rules for time zone
+ foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
+ {
+ // Determine if this adjustment rule covers year desired
+ if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year)
+ {
+ TimeZoneInfo.TransitionTime startTransition, endTransition;
+ // Determine if starting transition is fixed
+ startTransition = adjustment.DaylightTransitionStart;
+ // Determine if starting transition is fixed and display transition info for year
+ if (startTransition.IsFixedDateRule)
+ Console.WriteLine($" Begins on {dateFormat.GetMonthName(startTransition.Month)} {startTransition.Day} at {startTransition.TimeOfDay:t}");
+ else
+ DisplayTransitionInfo(startTransition, year, "Begins on");
+
+ // Determine if ending transition is fixed and display transition info for year
+ endTransition = adjustment.DaylightTransitionEnd;
+ if (endTransition.IsFixedDateRule)
+ Console.WriteLine($" Ends on {dateFormat.GetMonthName(endTransition.Month)} {endTransition.Day} at {endTransition.TimeOfDay:t}");
+ else
+ DisplayTransitionInfo(endTransition, year, "Ends on");
+
+ break;
+ }
+ }
+ }
+ }
+ }
- Console.WriteLine(" {0} {1}, {2:d} at {3:t}",
- label,
- transition.DayOfWeek,
- new DateTime(year, transition.Month, transitionDay),
- transition.TimeOfDay);
- }
+ private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label)
+ {
+ // For non-fixed date rules, get local calendar
+ Calendar cal = CultureInfo.CurrentCulture.Calendar;
+ // Get first day of week for transition
+ // For example, the 3rd week starts no earlier than the 15th of the month
+ int startOfWeek = transition.Week * 7 - 6;
+ // What day of the week does the month start on?
+ int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, startOfWeek));
+ // Determine how much start date has to be adjusted
+ int transitionDay;
+ int changeDayOfWeek = (int)transition.DayOfWeek;
+
+ if (firstDayOfWeek <= changeDayOfWeek)
+ transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
+ else
+ transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
+
+ // Adjust for months with no fifth week
+ if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
+ transitionDay -= 7;
+
+ Console.WriteLine($" {label} {transition.DayOfWeek}, {new DateTime(year, transition.Month, transitionDay):d} at {transition.TimeOfDay:t}");
+ }
}
public class AdditionalExamples
{
- //
- private enum WeekOfMonth
- {
- First = 1,
- Second = 2,
- Third = 3,
- Fourth = 4,
- Last = 5,
- }
+ //
+ private enum WeekOfMonth
+ {
+ First = 1,
+ Second = 2,
+ Third = 3,
+ Fourth = 4,
+ Last = 5,
+ }
- public void GetAllTransitionTimes()
- {
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
-
- foreach (TimeZoneInfo zone in timeZones)
- {
- Console.WriteLine("{0} transition time information:", zone.StandardName);
- TimeZoneInfo.AdjustmentRule[] adjustmentRules= zone.GetAdjustmentRules();
-
- // Indicate that time zone has no adjustment rules
- if (adjustmentRules.Length == 0)
- {
- Console.WriteLine(" No adjustment rules defined.");
- }
- else
- {
- // Iterate adjustment rules
- foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
+ public void GetAllTransitionTimes()
+ {
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ DateTimeFormatInfo dateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
+
+ foreach (TimeZoneInfo zone in timeZones)
+ {
+ Console.WriteLine($"{zone.StandardName} transition time information:");
+ TimeZoneInfo.AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules();
+
+ // Indicate that time zone has no adjustment rules
+ if (adjustmentRules.Length == 0)
+ {
+ Console.WriteLine(" No adjustment rules defined.");
+ }
+ else
{
- Console.WriteLine(" Adjustment rule from {0:d} to {1:d}:",
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd);
-
- // Get start of transition
- TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
- // Display information on fixed date rule
- if (!daylightStart.IsFixedDateRule)
- Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}.",
- daylightStart.TimeOfDay,
- ((WeekOfMonth)daylightStart.Week).ToString(),
- daylightStart.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightStart.Month));
- // Display information on floating date rule
- else
- Console.WriteLine(" Begins at {0:t} on the {1} {2} of {3}.",
- daylightStart.TimeOfDay,
- ((WeekOfMonth)daylightStart.Week).ToString(),
- daylightStart.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightStart.Month));
-
- // Get end of transition
- TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
- // Display information on fixed date rule
- if (!daylightEnd.IsFixedDateRule)
- Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}.",
- daylightEnd.TimeOfDay,
- ((WeekOfMonth)daylightEnd.Week).ToString(),
- daylightEnd.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightEnd.Month));
- // Display information on floating date rule
- else
- Console.WriteLine(" Ends at {0:t} on the {1} {2} of {3}.",
- daylightStart.TimeOfDay,
- ((WeekOfMonth)daylightStart.Week).ToString(),
- daylightStart.DayOfWeek.ToString(),
- dateInfo.GetMonthName(daylightStart.Month));
+ // Iterate adjustment rules
+ foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules)
+ {
+ Console.WriteLine($" Adjustment rule from {adjustmentRule.DateStart:d} to {adjustmentRule.DateEnd:d}:");
+
+ // Get start of transition
+ TimeZoneInfo.TransitionTime daylightStart = adjustmentRule.DaylightTransitionStart;
+ // Display information on fixed date rule
+ if (!daylightStart.IsFixedDateRule)
+ Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}.");
+ // Display information on floating date rule
+ else
+ Console.WriteLine($" Begins at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}.");
+
+ // Get end of transition
+ TimeZoneInfo.TransitionTime daylightEnd = adjustmentRule.DaylightTransitionEnd;
+ // Display information on fixed date rule
+ if (!daylightEnd.IsFixedDateRule)
+ Console.WriteLine($" Ends at {daylightEnd.TimeOfDay:t} on the {((WeekOfMonth)daylightEnd.Week)} {daylightEnd.DayOfWeek} of {dateInfo.GetMonthName(daylightEnd.Month)}.");
+ // Display information on floating date rule
+ else
+ Console.WriteLine($" Ends at {daylightStart.TimeOfDay:t} on the {((WeekOfMonth)daylightStart.Week)} {daylightStart.DayOfWeek} of {dateInfo.GetMonthName(daylightStart.Month)}.");
+ }
}
- }
- }
- }
- //
+ }
+ }
+ //
}
diff --git a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs
index c9e6c34b54a..0f59475c641 100644
--- a/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs
+++ b/snippets/csharp/System/TimeZoneInfo+TransitionTime/CreateFixedDateRule/example1.cs
@@ -1,120 +1,108 @@
using System;
-using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
-[assembly:CLSCompliant(true)]
-public class TransitionTimeExamples
+public class TransitionTimeExamplesYear
{
- public static void Main()
- {
- TransitionTimeExamples tte = new TransitionTimeExamples();
- tte.GetTransitionTimes(2007);
- }
+ public static void Run()
+ {
+ TransitionTimeExamplesYear tte = new();
+ tte.GetTransitionTimes(2007);
+ }
- //
- private void GetTransitionTimes(int year)
- {
- // Instantiate DateTimeFormatInfo object for month names
- DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
+ //
+ private void GetTransitionTimes(int year)
+ {
+ // Instantiate DateTimeFormatInfo object for month names
+ DateTimeFormatInfo dateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
- // Get and iterate time zones on local computer
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- foreach (TimeZoneInfo timeZone in timeZones)
- {
- Console.WriteLine("{0}:", timeZone.StandardName);
- TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
- int startYear = year;
- int endYear = startYear;
+ // Get and iterate time zones on local computer
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ foreach (TimeZoneInfo timeZone in timeZones)
+ {
+ Console.WriteLine($"{timeZone.StandardName}:");
+ TimeZoneInfo.AdjustmentRule[] adjustments = timeZone.GetAdjustmentRules();
+ int startYear = year;
+ int endYear = startYear;
- if (adjustments.Length == 0)
- {
- Console.WriteLine(" No adjustment rules.");
- }
- else
- {
- TimeZoneInfo.AdjustmentRule adjustment = GetAdjustment(adjustments, year);
- if (adjustment == null)
+ if (adjustments.Length == 0)
{
- Console.WriteLine(" No adjustment rules available for this year.");
- continue;
+ Console.WriteLine(" No adjustment rules.");
}
- TimeZoneInfo.TransitionTime startTransition, endTransition;
-
- // Determine if starting transition is fixed
- startTransition = adjustment.DaylightTransitionStart;
- // Determine if starting transition is fixed and display transition info for year
- if (startTransition.IsFixedDateRule)
- Console.WriteLine(" Begins on {0} {1} at {2:t}",
- dateFormat.GetMonthName(startTransition.Month),
- startTransition.Day,
- startTransition.TimeOfDay);
else
- DisplayTransitionInfo(startTransition, startYear, "Begins on");
-
- // Determine if ending transition is fixed and display transition info for year
- endTransition = adjustment.DaylightTransitionEnd;
-
- // Does the transition back occur in an earlier month (i.e.,
- // the following year) than the transition to DST? If so, make
- // sure we have the right adjustment rule.
- if (endTransition.Month < startTransition.Month)
{
- endTransition = GetAdjustment(adjustments, year + 1).DaylightTransitionEnd;
- endYear++;
+ TimeZoneInfo.AdjustmentRule adjustment = GetAdjustment(adjustments, year);
+ if (adjustment == null)
+ {
+ Console.WriteLine(" No adjustment rules available for this year.");
+ continue;
+ }
+ TimeZoneInfo.TransitionTime startTransition, endTransition;
+
+ // Determine if starting transition is fixed
+ startTransition = adjustment.DaylightTransitionStart;
+ // Determine if starting transition is fixed and display transition info for year
+ if (startTransition.IsFixedDateRule)
+ Console.WriteLine($" Begins on {dateFormat.GetMonthName(startTransition.Month)} {startTransition.Day} at {startTransition.TimeOfDay:t}");
+ else
+ DisplayTransitionInfo(startTransition, startYear, "Begins on");
+
+ // Determine if ending transition is fixed and display transition info for year
+ endTransition = adjustment.DaylightTransitionEnd;
+
+ // Does the transition back occur in an earlier month (i.e.,
+ // the following year) than the transition to DST? If so, make
+ // sure we have the right adjustment rule.
+ if (endTransition.Month < startTransition.Month)
+ {
+ endTransition = GetAdjustment(adjustments, year + 1).DaylightTransitionEnd;
+ endYear++;
+ }
+
+ if (endTransition.IsFixedDateRule)
+ Console.WriteLine($" Ends on {dateFormat.GetMonthName(endTransition.Month)} {endTransition.Day} at {endTransition.TimeOfDay:t}");
+ else
+ DisplayTransitionInfo(endTransition, endYear, "Ends on");
}
-
- if (endTransition.IsFixedDateRule)
- Console.WriteLine(" Ends on {0} {1} at {2:t}",
- dateFormat.GetMonthName(endTransition.Month),
- endTransition.Day,
- endTransition.TimeOfDay);
- else
- DisplayTransitionInfo(endTransition, endYear, "Ends on");
- }
- }
- }
+ }
+ }
+
+ private static TimeZoneInfo.AdjustmentRule GetAdjustment(TimeZoneInfo.AdjustmentRule[] adjustments,
+ int year)
+ {
+ // Iterate adjustment rules for time zone
+ foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
+ {
+ // Determine if this adjustment rule covers year desired
+ if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year)
+ return adjustment;
+ }
+ return null;
+ }
- private static TimeZoneInfo.AdjustmentRule GetAdjustment(TimeZoneInfo.AdjustmentRule[] adjustments,
- int year)
- {
- // Iterate adjustment rules for time zone
- foreach (TimeZoneInfo.AdjustmentRule adjustment in adjustments)
- {
- // Determine if this adjustment rule covers year desired
- if (adjustment.DateStart.Year <= year && adjustment.DateEnd.Year >= year)
- return adjustment;
- }
- return null;
- }
-
- private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label)
- {
- // For non-fixed date rules, get local calendar
- Calendar cal = CultureInfo.CurrentCulture.Calendar;
- // Get first day of week for transition
- // For example, the 3rd week starts no earlier than the 15th of the month
- int startOfWeek = transition.Week * 7 - 6;
- // What day of the week does the month start on?
- int firstDayOfWeek = (int) cal.GetDayOfWeek(new DateTime(year, transition.Month, 1));
- // Determine how much start date has to be adjusted
- int transitionDay;
- int changeDayOfWeek = (int) transition.DayOfWeek;
+ private void DisplayTransitionInfo(TimeZoneInfo.TransitionTime transition, int year, string label)
+ {
+ // For non-fixed date rules, get local calendar
+ Calendar cal = CultureInfo.CurrentCulture.Calendar;
+ // Get first day of week for transition
+ // For example, the 3rd week starts no earlier than the 15th of the month
+ int startOfWeek = transition.Week * 7 - 6;
+ // What day of the week does the month start on?
+ int firstDayOfWeek = (int)cal.GetDayOfWeek(new DateTime(year, transition.Month, 1));
+ // Determine how much start date has to be adjusted
+ int transitionDay;
+ int changeDayOfWeek = (int)transition.DayOfWeek;
- if (firstDayOfWeek <= changeDayOfWeek)
- transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
- else
- transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
+ if (firstDayOfWeek <= changeDayOfWeek)
+ transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
+ else
+ transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
- // Adjust for months with no fifth week
- if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
- transitionDay -= 7;
+ // Adjust for months with no fifth week
+ if (transitionDay > cal.GetDaysInMonth(year, transition.Month))
+ transitionDay -= 7;
- Console.WriteLine(" {0} {1}, {2:d} at {3:t}",
- label,
- transition.DayOfWeek,
- new DateTime(year, transition.Month, transitionDay),
- transition.TimeOfDay);
- }
- //
+ Console.WriteLine($" {label} {transition.DayOfWeek}, {new DateTime(year, transition.Month, transitionDay):d} at {transition.TimeOfDay:t}");
+ }
+ //
}
diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs
new file mode 100644
index 00000000000..ea77484b8d8
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Program.cs
@@ -0,0 +1,3 @@
+GetSystemTimeZonesExample.Run();
+ShowTimeZoneNamesExample.Run();
+TimeZoneExamples.TZClass.Run();
diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj
new file mode 100644
index 00000000000..c27165eee76
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/Project.csproj
@@ -0,0 +1,8 @@
+
+
+ Exe
+ net10.0-windows
+ true
+ true
+
+
diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs
index 65c5d51c2ac..1f08961d414 100644
--- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs
+++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/ShowTimeZoneNames1.cs
@@ -1,16 +1,16 @@
//
using System;
-public class Example
+public class ShowTimeZoneNamesExample
{
- public static void Main()
- {
- TimeZoneInfo localZone = TimeZoneInfo.Local;
- Console.WriteLine("Local Time Zone ID: {0}", localZone.Id);
- Console.WriteLine(" Display Name is: {0}.", localZone.DisplayName);
- Console.WriteLine(" Standard name is: {0}.", localZone.StandardName);
- Console.WriteLine(" Daylight saving name is: {0}.", localZone.DaylightName);
- }
+ public static void Run()
+ {
+ TimeZoneInfo localZone = TimeZoneInfo.Local;
+ Console.WriteLine($"Local Time Zone ID: {localZone.Id}");
+ Console.WriteLine($" Display Name is: {localZone.DisplayName}.");
+ Console.WriteLine($" Standard name is: {localZone.StandardName}.");
+ Console.WriteLine($" Daylight saving name is: {localZone.DaylightName}.");
+ }
}
// The example displays output like the following:
// Local Time Zone ID: Pacific Standard Time
diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs
index e5fbfa74fd7..109d32ad764 100644
--- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs
+++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/TimeZone2_Examples.cs
@@ -1,147 +1,141 @@
using System;
using System.Collections.ObjectModel;
-using System.Globalization;
-using System.IO;
using System.Windows.Forms;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
namespace TimeZoneExamples
{
- public class TZClass
- {
- public static void Main()
- {
- TZClass tz = new TZClass();
- if(MessageBox.Show("Display time zone offset?", "Offset", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowTimezoneOffset();
-
- if(MessageBox.Show("Display time zone names?", "Names", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowTimeZoneNames();
-
- if(MessageBox.Show("Display universal time zone names?", "Universal Time Zone Names", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowUniversalTimeZoneNames();
-
- if(MessageBox.Show("Show time zones without daylight savings time", "Zones Supporting DST", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowNoDSTZones();
-
- if(MessageBox.Show("List all time zone IDs?", "IDs", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowTimeZoneIDs();
-
- if(MessageBox.Show("Test Time Zones for Equality?", "TimeZoneInfo.Equals", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.TestForEquality();
-
- if(MessageBox.Show("Show ambiguous times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsAmbiguousTime", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowAmbiguousTimes();
-
- if(MessageBox.Show("Show invalid times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsInvalidTime", MessageBoxButtons.YesNo) == DialogResult.Yes)
- tz.ShowInvalidTimes();
- }
-
- private void ShowTimezoneOffset()
- {
- //
- TimeZoneInfo localZone = TimeZoneInfo.Local;
- Console.WriteLine("The {0} time zone is {1}:{2} {3} than Coordinated Universal Time.",
- localZone.DisplayName,
- Math.Abs(localZone.BaseUtcOffset.Hours),
- Math.Abs(localZone.BaseUtcOffset.Minutes),
- (localZone.BaseUtcOffset >= TimeSpan.Zero) ? "later" : "earlier");
- //
- }
-
- private void ShowTimeZoneNames()
- {
- TimeZoneInfo localZone = TimeZoneInfo.Local;
- Console.WriteLine("Local Time Zone ID: {0}", localZone.Id);
- Console.WriteLine(" Display Name is: {0}.", localZone.DisplayName);
- Console.WriteLine(" Standard name is: {0}.", localZone.StandardName);
- Console.WriteLine(" Daylight saving name is: {0}.", localZone.DaylightName);
- }
-
- private void ShowUniversalTimeZoneNames()
- {
- //
- TimeZoneInfo universalZone = TimeZoneInfo.Utc;
- Console.WriteLine("The universal time zone is {0}.", universalZone.DisplayName);
- Console.WriteLine("Its standard name is {0}.", universalZone.StandardName);
- Console.WriteLine("Its daylight savings name is {0}.", universalZone.DaylightName);
- //
- }
-
- private void ShowNoDSTZones()
- {
- //
- ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones();
- foreach(TimeZoneInfo zone in zones)
- {
- if (!zone.SupportsDaylightSavingTime)
- Console.WriteLine(zone.DisplayName);
- }
- //
- }
-
- private void ShowTimeZoneIDs()
- {
- //
- ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones();
- Console.WriteLine("The local system has the following {0} time zones", zones.Count);
- foreach (TimeZoneInfo zone in zones)
- Console.WriteLine(zone.Id);
- //
- }
-
- private void TestForEquality()
- {
- //
- TimeZoneInfo thisTimeZone, zone1, zone2;
-
- thisTimeZone = TimeZoneInfo.Local;
- zone1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
- zone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
- Console.WriteLine(thisTimeZone.Equals(zone1));
- Console.WriteLine(thisTimeZone.Equals(zone2));
- //
- }
-
- private void ShowAmbiguousTimes()
- {
- //
- // Specify DateTimeKind in Date constructor
- DateTime baseTime = new DateTime(2007, 11, 4, 0, 59, 00, DateTimeKind.Unspecified);
- DateTime newTime;
-
- // Get Pacific Standard Time zone
- TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
-
- // List possible ambiguous times for 63-minute interval, from 12:59 AM to 2:01 AM
- for (int ctr = 0; ctr < 63; ctr++)
- {
- // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified
- newTime = baseTime.AddMinutes(ctr);
- Console.WriteLine("{0} is ambiguous: {1}", newTime, pstZone.IsAmbiguousTime(newTime));
- }
- //
- }
-
- private void ShowInvalidTimes()
- {
- //
- // Specify DateTimeKind in Date constructor
- DateTime baseTime = new DateTime(2007, 3, 11, 1, 59, 0, DateTimeKind.Unspecified);
- DateTime newTime;
-
- // Get Pacific Standard Time zone
- TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
-
- // List possible invalid times for a 63-minute interval, from 1:59 AM to 3:01 AM
- for (int ctr = 0; ctr < 63; ctr++)
- {
- // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified
- newTime = baseTime.AddMinutes(ctr);
- Console.WriteLine("{0} is invalid: {1}", newTime, pstZone.IsInvalidTime(newTime));
- }
- //
- }
- }
+ public class TZClass
+ {
+ public static void Run()
+ {
+ TZClass tz = new();
+ if (MessageBox.Show("Display time zone offset?", "Offset", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowTimezoneOffset();
+
+ if (MessageBox.Show("Display time zone names?", "Names", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowTimeZoneNames();
+
+ if (MessageBox.Show("Display universal time zone names?", "Universal Time Zone Names", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowUniversalTimeZoneNames();
+
+ if (MessageBox.Show("Show time zones without daylight savings time", "Zones Supporting DST", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowNoDSTZones();
+
+ if (MessageBox.Show("List all time zone IDs?", "IDs", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowTimeZoneIDs();
+
+ if (MessageBox.Show("Test Time Zones for Equality?", "TimeZoneInfo.Equals", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.TestForEquality();
+
+ if (MessageBox.Show("Show ambiguous times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsAmbiguousTime", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowAmbiguousTimes();
+
+ if (MessageBox.Show("Show invalid times in Pacific Time Zone for 2007?", "TimeZoneInfo.IsInvalidTime", MessageBoxButtons.YesNo) == DialogResult.Yes)
+ tz.ShowInvalidTimes();
+ }
+
+ private void ShowTimezoneOffset()
+ {
+ //
+ TimeZoneInfo localZone = TimeZoneInfo.Local;
+ Console.WriteLine($"The {localZone.DisplayName} time zone is {Math.Abs(localZone.BaseUtcOffset.Hours)}:{Math.Abs(localZone.BaseUtcOffset.Minutes)} {((localZone.BaseUtcOffset >= TimeSpan.Zero) ? "later" : "earlier")} than Coordinated Universal Time.");
+ //
+ }
+
+ private void ShowTimeZoneNames()
+ {
+ TimeZoneInfo localZone = TimeZoneInfo.Local;
+ Console.WriteLine($"Local Time Zone ID: {localZone.Id}");
+ Console.WriteLine($" Display Name is: {localZone.DisplayName}.");
+ Console.WriteLine($" Standard name is: {localZone.StandardName}.");
+ Console.WriteLine($" Daylight saving name is: {localZone.DaylightName}.");
+ }
+
+ private void ShowUniversalTimeZoneNames()
+ {
+ //
+ TimeZoneInfo universalZone = TimeZoneInfo.Utc;
+ Console.WriteLine($"The universal time zone is {universalZone.DisplayName}.");
+ Console.WriteLine($"Its standard name is {universalZone.StandardName}.");
+ Console.WriteLine($"Its daylight savings name is {universalZone.DaylightName}.");
+ //
+ }
+
+ private void ShowNoDSTZones()
+ {
+ //
+ ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones();
+ foreach (TimeZoneInfo zone in zones)
+ {
+ if (!zone.SupportsDaylightSavingTime)
+ Console.WriteLine(zone.DisplayName);
+ }
+ //
+ }
+
+ private void ShowTimeZoneIDs()
+ {
+ //
+ ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones();
+ Console.WriteLine($"The local system has the following {zones.Count} time zones");
+ foreach (TimeZoneInfo zone in zones)
+ Console.WriteLine(zone.Id);
+ //
+ }
+
+ private void TestForEquality()
+ {
+ //
+ TimeZoneInfo thisTimeZone, zone1, zone2;
+
+ thisTimeZone = TimeZoneInfo.Local;
+ zone1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
+ zone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ Console.WriteLine(thisTimeZone.Equals(zone1));
+ Console.WriteLine(thisTimeZone.Equals(zone2));
+ //
+ }
+
+ private void ShowAmbiguousTimes()
+ {
+ //
+ // Specify DateTimeKind in Date constructor
+ DateTime baseTime = new(2007, 11, 4, 0, 59, 00, DateTimeKind.Unspecified);
+ DateTime newTime;
+
+ // Get Pacific Standard Time zone
+ TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
+
+ // List possible ambiguous times for 63-minute interval, from 12:59 AM to 2:01 AM
+ for (int ctr = 0; ctr < 63; ctr++)
+ {
+ // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified
+ newTime = baseTime.AddMinutes(ctr);
+ Console.WriteLine($"{newTime} is ambiguous: {pstZone.IsAmbiguousTime(newTime)}");
+ }
+ //
+ }
+
+ private void ShowInvalidTimes()
+ {
+ //
+ // Specify DateTimeKind in Date constructor
+ DateTime baseTime = new(2007, 3, 11, 1, 59, 0, DateTimeKind.Unspecified);
+ DateTime newTime;
+
+ // Get Pacific Standard Time zone
+ TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
+
+ // List possible invalid times for a 63-minute interval, from 1:59 AM to 3:01 AM
+ for (int ctr = 0; ctr < 63; ctr++)
+ {
+ // Because of assignment, newTime.Kind is also DateTimeKind.Unspecified
+ newTime = baseTime.AddMinutes(ctr);
+ Console.WriteLine($"{newTime} is invalid: {pstZone.IsInvalidTime(newTime)}");
+ }
+ //
+ }
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs
index 5c28ea5f202..4f85f055478 100644
--- a/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs
+++ b/snippets/csharp/System/TimeZoneInfo/BaseUtcOffset/getsystemtimezones1.cs
@@ -4,67 +4,57 @@
using System.IO;
using System.Collections.ObjectModel;
-public class Example
+public class GetSystemTimeZonesExample
{
- public static void Main()
- {
- const string OUTPUTFILENAME = @"C:\Temp\TimeZoneInfo.txt";
-
- DateTimeFormatInfo dateFormats = CultureInfo.CurrentCulture.DateTimeFormat;
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- StreamWriter sw = new StreamWriter(OUTPUTFILENAME, false);
-
- foreach (TimeZoneInfo timeZone in timeZones)
- {
- bool hasDST = timeZone.SupportsDaylightSavingTime;
- TimeSpan offsetFromUtc = timeZone.BaseUtcOffset;
- TimeZoneInfo.AdjustmentRule[] adjustRules;
- string offsetString;
-
- sw.WriteLine("ID: {0}", timeZone.Id);
- sw.WriteLine(" Display Name: {0, 40}", timeZone.DisplayName);
- sw.WriteLine(" Standard Name: {0, 39}", timeZone.StandardName);
- sw.Write(" Daylight Name: {0, 39}", timeZone.DaylightName);
- sw.Write(hasDST ? " ***Has " : " ***Does Not Have ");
- sw.WriteLine("Daylight Saving Time***");
- offsetString = String.Format("{0} hours, {1} minutes", offsetFromUtc.Hours, offsetFromUtc.Minutes);
- sw.WriteLine(" Offset from UTC: {0, 40}", offsetString);
- adjustRules = timeZone.GetAdjustmentRules();
- sw.WriteLine(" Number of adjustment rules: {0, 26}", adjustRules.Length);
- if (adjustRules.Length > 0)
- {
- sw.WriteLine(" Adjustment Rules:");
- foreach (TimeZoneInfo.AdjustmentRule rule in adjustRules)
+ public static void Run()
+ {
+ const string OUTPUTFILENAME = @"C:\Temp\TimeZoneInfo.txt";
+
+ DateTimeFormatInfo dateFormats = CultureInfo.CurrentCulture.DateTimeFormat;
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ StreamWriter sw = new(OUTPUTFILENAME, false);
+
+ foreach (TimeZoneInfo timeZone in timeZones)
+ {
+ bool hasDST = timeZone.SupportsDaylightSavingTime;
+ TimeSpan offsetFromUtc = timeZone.BaseUtcOffset;
+ TimeZoneInfo.AdjustmentRule[] adjustRules;
+ string offsetString;
+
+ sw.WriteLine($"ID: {timeZone.Id}");
+ sw.WriteLine($" Display Name: {timeZone.DisplayName,40}");
+ sw.WriteLine($" Standard Name: {timeZone.StandardName,39}");
+ sw.Write($" Daylight Name: {timeZone.DaylightName,39}");
+ sw.Write(hasDST ? " ***Has " : " ***Does Not Have ");
+ sw.WriteLine("Daylight Saving Time***");
+ offsetString = $"{offsetFromUtc.Hours} hours, {offsetFromUtc.Minutes} minutes";
+ sw.WriteLine($" Offset from UTC: {offsetString,40}");
+ adjustRules = timeZone.GetAdjustmentRules();
+ sw.WriteLine($" Number of adjustment rules: {adjustRules.Length,26}");
+ if (adjustRules.Length > 0)
{
- TimeZoneInfo.TransitionTime transTimeStart = rule.DaylightTransitionStart;
- TimeZoneInfo.TransitionTime transTimeEnd = rule.DaylightTransitionEnd;
-
- sw.WriteLine(" From {0} to {1}", rule.DateStart, rule.DateEnd);
- sw.WriteLine(" Delta: {0}", rule.DaylightDelta);
- if (!transTimeStart.IsFixedDateRule)
- {
- sw.WriteLine(" Begins at {0:t} on {1} of week {2} of {3}", transTimeStart.TimeOfDay,
- transTimeStart.DayOfWeek,
- transTimeStart.Week,
- dateFormats.MonthNames[transTimeStart.Month - 1]);
- sw.WriteLine(" Ends at {0:t} on {1} of week {2} of {3}", transTimeEnd.TimeOfDay,
- transTimeEnd.DayOfWeek,
- transTimeEnd.Week,
- dateFormats.MonthNames[transTimeEnd.Month - 1]);
- }
- else
- {
- sw.WriteLine(" Begins at {0:t} on {1} {2}", transTimeStart.TimeOfDay,
- transTimeStart.Day,
- dateFormats.MonthNames[transTimeStart.Month - 1]);
- sw.WriteLine(" Ends at {0:t} on {1} {2}", transTimeEnd.TimeOfDay,
- transTimeEnd.Day,
- dateFormats.MonthNames[transTimeEnd.Month - 1]);
- }
+ sw.WriteLine(" Adjustment Rules:");
+ foreach (TimeZoneInfo.AdjustmentRule rule in adjustRules)
+ {
+ TimeZoneInfo.TransitionTime transTimeStart = rule.DaylightTransitionStart;
+ TimeZoneInfo.TransitionTime transTimeEnd = rule.DaylightTransitionEnd;
+
+ sw.WriteLine($" From {rule.DateStart} to {rule.DateEnd}");
+ sw.WriteLine($" Delta: {rule.DaylightDelta}");
+ if (!transTimeStart.IsFixedDateRule)
+ {
+ sw.WriteLine($" Begins at {transTimeStart.TimeOfDay:t} on {transTimeStart.DayOfWeek} of week {transTimeStart.Week} of {dateFormats.MonthNames[transTimeStart.Month - 1]}");
+ sw.WriteLine($" Ends at {transTimeEnd.TimeOfDay:t} on {transTimeEnd.DayOfWeek} of week {transTimeEnd.Week} of {dateFormats.MonthNames[transTimeEnd.Month - 1]}");
+ }
+ else
+ {
+ sw.WriteLine($" Begins at {transTimeStart.TimeOfDay:t} on {transTimeStart.Day} {dateFormats.MonthNames[transTimeStart.Month - 1]}");
+ sw.WriteLine($" Ends at {transTimeEnd.TimeOfDay:t} on {transTimeEnd.Day} {dateFormats.MonthNames[transTimeEnd.Month - 1]}");
+ }
+ }
}
- }
- }
- sw.Close();
- }
+ }
+ sw.Close();
+ }
}
//
diff --git a/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs b/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs
index 2d477152dd5..16c248c6beb 100644
--- a/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ClearCachedData/System.TimeZone2.BestPractices.cs
@@ -2,28 +2,28 @@
public class BestTimeZonePractices
{
- public static void Main()
- {
- BestTimeZonePractices best = new BestTimeZonePractices();
- best.NoCachedReferences();
- }
+ public static void Main()
+ {
+ BestTimeZonePractices best = new();
+ best.NoCachedReferences();
+ }
- private void NoCachedReferences()
- {
- //
- TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
- TimeZoneInfo local = TimeZoneInfo.Local;
- Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
+ private void NoCachedReferences()
+ {
+ //
+ TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
+ TimeZoneInfo local = TimeZoneInfo.Local;
+ Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
- TimeZoneInfo.ClearCachedData();
- try
- {
- Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
- }
- catch (ArgumentException e)
- {
- Console.WriteLine(e.GetType().Name + "\n " + e.Message);
- }
- //
- }
+ TimeZoneInfo.ClearCachedData();
+ try
+ {
+ Console.WriteLine(TimeZoneInfo.ConvertTime(DateTime.Now, local, cst));
+ }
+ catch (ArgumentException e)
+ {
+ Console.WriteLine(e.GetType().Name + "\n " + e.Message);
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs
new file mode 100644
index 00000000000..de79dcfbfd2
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Program.cs
@@ -0,0 +1,3 @@
+ConvertTimeExample1.Run();
+ConvertTimeExample2.Run();
+TZExamples.Run();
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj
new file mode 100644
index 00000000000..c27165eee76
--- /dev/null
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/Project.csproj
@@ -0,0 +1,8 @@
+
+
+ Exe
+ net10.0-windows
+ true
+ true
+
+
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs
index 664a65d775e..db89a9a9436 100644
--- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/TimeZone2Concepts.cs
@@ -1,386 +1,354 @@
// Note that this source code file includes a code module (modMain) and
-// a WinForm.
+// a WinForm.
using System;
using System.Collections.ObjectModel;
using System.Security;
using System.Windows.Forms;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
public class TZExamples
{
- public static void Main()
- {
- TZExamples tze = new TZExamples();
-// tze.IterateTimeZones();
-// tze.SelectTimeZone();
+ public static void Run()
+ {
+ TZExamples tze = new();
+ // tze.IterateTimeZones();
+ // tze.SelectTimeZone();
tze.ShowDaylightStatus();
Console.WriteLine("\nShowLocalAndUtcTime:");
tze.ShowLocalAndUtcTime();
tze.ConvertToArbitraryTime();
Console.WriteLine("**ConvertTimeToUtc***");
tze.ConvertToUtc();
- Console.WriteLine("ConvertEasternToUtc:");
+ Console.WriteLine("ConvertEasternToUtc:");
tze.ConvertEasternToUtc();
Console.WriteLine("\nConvertUtcToCentral:");
tze.ConvertUtcToCentral();
- Console.WriteLine("\nConvertHawaiianToLocal:");
- tze.ConvertHawaiianToLocal();
- Console.WriteLine("Resolving ambiguous times:");
- Console.WriteLine(tze.ResolveAmbiguousTime(new DateTime(2006, 10, 29, 02, 03, 15)));
- Console.WriteLine(tze.ResolveAmbiguousTime(DateTime.Now));
- Console.WriteLine();
- tze.GetUserDateInput();
- }
+ Console.WriteLine("\nConvertHawaiianToLocal:");
+ tze.ConvertHawaiianToLocal();
+ Console.WriteLine("Resolving ambiguous times:");
+ Console.WriteLine(tze.ResolveAmbiguousTime(new DateTime(2006, 10, 29, 02, 03, 15)));
+ Console.WriteLine(tze.ResolveAmbiguousTime(DateTime.Now));
+ Console.WriteLine();
+ tze.GetUserDateInput();
+ }
- private void IterateTimeZones()
- {
- //
- ReadOnlyCollection tzCollection;
- tzCollection = TimeZoneInfo.GetSystemTimeZones();
- //
-
- Console.WriteLine("Listing {0} time zones found on the system:", tzCollection.Count);
- //
- foreach (TimeZoneInfo timeZone in tzCollection)
- Console.WriteLine(" {0}: {1}", timeZone.Id, timeZone.DisplayName);
- //
- }
+ private void IterateTimeZones()
+ {
+ //
+ ReadOnlyCollection tzCollection;
+ tzCollection = TimeZoneInfo.GetSystemTimeZones();
+ //
- private void SelectTimeZone()
- {
- TZListForm frm = new TZListForm();
- frm.ShowDialog();
- }
+ Console.WriteLine($"Listing {tzCollection.Count} time zones found on the system:");
+ //
+ foreach (TimeZoneInfo timeZone in tzCollection)
+ Console.WriteLine($" {timeZone.Id}: {timeZone.DisplayName}");
+ //
+ }
- private void ShowDaylightStatus()
- {
- //
- DateTime dateToday = DateTime.Now;
- TimeSpan differenceFromUtc = TimeZoneInfo.Local.GetUtcOffset(dateToday);
- Console.WriteLine("The time is {0:t} in {1} time, {2:##.0} hours {3} universal time.",
- dateToday,
- TimeZoneInfo.Local.IsDaylightSavingTime(dateToday) ? "daylight saving" : "standard",
- Math.Abs(differenceFromUtc.TotalHours),
- differenceFromUtc.Hours > 0 ? "after" : "earlier than");
- //
- }
+ private void SelectTimeZone()
+ {
+ TZListForm frm = new();
+ frm.ShowDialog();
+ }
- private void ShowLocalAndUtcTime()
- {
- //
- DateTime timeNow = DateTime.Now;
- Console.WriteLine("It is now {0:t} {1}, or {2:t} {3}.",
- timeNow,
- TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ?
- TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName,
- TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, TimeZoneInfo.Utc),
- TimeZoneInfo.Utc.StandardName);
- //
- }
+ private void ShowDaylightStatus()
+ {
+ //
+ DateTime dateToday = DateTime.Now;
+ TimeSpan differenceFromUtc = TimeZoneInfo.Local.GetUtcOffset(dateToday);
+ Console.WriteLine($"The time is {dateToday:t} in {(TimeZoneInfo.Local.IsDaylightSavingTime(dateToday) ? "daylight saving" : "standard")} time, {Math.Abs(differenceFromUtc.TotalHours):##.0} hours {(differenceFromUtc.Hours > 0 ? "after" : "earlier than")} universal time.");
+ //
+ }
- private void ConvertToArbitraryTime()
- {
- //
- DateTime timeNow = DateTime.Now;
- try
- {
- TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
- DateTime easternTimeNow = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local,
- easternZone);
- Console.WriteLine("{0} {1} corresponds to {2} {3}.",
- timeNow,
- TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ?
- TimeZoneInfo.Local.DaylightName :
- TimeZoneInfo.Local.StandardName,
- easternTimeNow,
- easternZone.IsDaylightSavingTime(easternTimeNow) ?
- easternZone.DaylightName :
- easternZone.StandardName);
- }
- // Handle exception
- //
- // As an alternative to simply displaying an error message, an alternate Eastern
- // Standard Time TimeZoneInfo object could be instantiated here either by restoring
- // it from a serialized string or by providing the necessary data to the
- // CreateCustomTimeZone method.
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system.");
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data.");
- }
- catch (SecurityException)
- {
- Console.WriteLine("The application lacks permission to read time zone information from the registry.");
- }
- catch (OutOfMemoryException)
- {
- Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone.");
- }
- // If we weren't passing FindSystemTimeZoneById a literal string, we also
- // would handle an ArgumentNullException.
- //
- }
+ private void ShowLocalAndUtcTime()
+ {
+ //
+ DateTime timeNow = DateTime.Now;
+ Console.WriteLine($"It is now {timeNow:t} {(TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ?
+ TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName)}, or {TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local, TimeZoneInfo.Utc):t} {TimeZoneInfo.Utc.StandardName}.");
+ //
+ }
- private void ConvertToUtc()
- {
- //
- DateTime dateNow = DateTime.Now;
- Console.WriteLine("The date and time are {0} UTC.",
- TimeZoneInfo.ConvertTimeToUtc(dateNow));
- //
- }
+ private void ConvertToArbitraryTime()
+ {
+ //
+ DateTime timeNow = DateTime.Now;
+ try
+ {
+ TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ DateTime easternTimeNow = TimeZoneInfo.ConvertTime(timeNow, TimeZoneInfo.Local,
+ easternZone);
+ Console.WriteLine($"{timeNow} {(TimeZoneInfo.Local.IsDaylightSavingTime(timeNow) ?
+ TimeZoneInfo.Local.DaylightName :
+ TimeZoneInfo.Local.StandardName)} corresponds to {easternTimeNow} {(easternZone.IsDaylightSavingTime(easternTimeNow) ?
+ easternZone.DaylightName :
+ easternZone.StandardName)}.");
+ }
+ // Handle exception
+ //
+ // As an alternative to simply displaying an error message, an alternate Eastern
+ // Standard Time TimeZoneInfo object could be instantiated here either by restoring
+ // it from a serialized string or by providing the necessary data to the
+ // CreateCustomTimeZone method.
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine("The Eastern Standard Time Zone cannot be found on the local system.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine("The Eastern Standard Time Zone contains invalid or missing data.");
+ }
+ catch (SecurityException)
+ {
+ Console.WriteLine("The application lacks permission to read time zone information from the registry.");
+ }
+ catch (OutOfMemoryException)
+ {
+ Console.WriteLine("Not enough memory is available to load information on the Eastern Standard Time zone.");
+ }
+ // If we weren't passing FindSystemTimeZoneById a literal string, we also
+ // would handle an ArgumentNullException.
+ //
+ }
- private void ConvertEasternToUtc()
- {
- //
- DateTime easternTime = new DateTime(2007, 01, 02, 12, 16, 00);
- string easternZoneId = "Eastern Standard Time";
- try
- {
- TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
- Console.WriteLine("The date and time are {0} UTC.",
- TimeZoneInfo.ConvertTimeToUtc(easternTime, easternZone));
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("Unable to find the {0} zone in the registry.",
- easternZoneId);
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Registry data on the {0} zone has been corrupted.",
- easternZoneId);
- }
- //
- }
+ private void ConvertToUtc()
+ {
+ //
+ DateTime dateNow = DateTime.Now;
+ Console.WriteLine($"The date and time are {TimeZoneInfo.ConvertTimeToUtc(dateNow)} UTC.");
+ //
+ }
- private void ConvertUtcToCentral()
- {
- //
- DateTime timeUtc = DateTime.UtcNow;
- try
- {
- TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
- DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
- Console.WriteLine("The date and time are {0} {1}.",
- cstTime,
- cstZone.IsDaylightSavingTime(cstTime) ?
- cstZone.DaylightName : cstZone.StandardName);
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The registry does not define the Central Standard Time zone.");
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted.");
- }
- //
- }
+ private void ConvertEasternToUtc()
+ {
+ //
+ DateTime easternTime = new(2007, 01, 02, 12, 16, 00);
+ string easternZoneId = "Eastern Standard Time";
+ try
+ {
+ TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
+ Console.WriteLine($"The date and time are {TimeZoneInfo.ConvertTimeToUtc(easternTime, easternZone)} UTC.");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine($"Unable to find the {easternZoneId} zone in the registry.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine($"Registry data on the {easternZoneId} zone has been corrupted.");
+ }
+ //
+ }
- private void ConvertHawaiianToLocal()
- {
- //
- DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
- try
- {
- TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
- Console.WriteLine("{0} {1} is {2} local time.",
- hwTime,
- hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName,
- TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The registry does not define the Hawaiian Standard Time zone.");
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("Registry data on the Hawaiian Standard Time zone has been corrupted.");
- }
- //
- }
+ private void ConvertUtcToCentral()
+ {
+ //
+ DateTime timeUtc = DateTime.UtcNow;
+ try
+ {
+ TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
+ DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
+ Console.WriteLine($"The date and time are {cstTime} {(cstZone.IsDaylightSavingTime(cstTime) ?
+ cstZone.DaylightName : cstZone.StandardName)}.");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine("The registry does not define the Central Standard Time zone.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted.");
+ }
+ //
+ }
- // Map an ambiguous time to the time zone's standard time
- //
- private DateTime ResolveAmbiguousTime(DateTime ambiguousTime)
- {
- // Time is not ambiguous
- if (!TimeZoneInfo.Local.IsAmbiguousTime(ambiguousTime))
- {
- return ambiguousTime;
- }
- // Time is ambiguous
- else
- {
- DateTime utcTime = DateTime.SpecifyKind(ambiguousTime - TimeZoneInfo.Local.BaseUtcOffset,
- DateTimeKind.Utc);
- Console.WriteLine("{0} local time corresponds to {1} {2}.",
- ambiguousTime, utcTime, utcTime.Kind.ToString());
- return utcTime;
- }
- }
- //
+ private void ConvertHawaiianToLocal()
+ {
+ //
+ DateTime hwTime = new(2007, 02, 01, 08, 00, 00);
+ try
+ {
+ TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
+ Console.WriteLine($"{hwTime} {(hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName)} is {TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local)} local time.");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine("The registry does not define the Hawaiian Standard Time zone.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine("Registry data on the Hawaiian Standard Time zone has been corrupted.");
+ }
+ //
+ }
- // Allow the user to resolve an ambiguous time
- //
- private void GetUserDateInput()
- {
- // Get date and time from user
- DateTime inputDate = GetUserDateTime();
- DateTime utcDate;
-
- // Exit if date has no significant value
- if (inputDate == DateTime.MinValue) return;
-
- if (TimeZoneInfo.Local.IsAmbiguousTime(inputDate))
- {
- Console.WriteLine("The date you've entered is ambiguous.");
- Console.WriteLine("Please select the correct offset from Universal Coordinated Time:");
- TimeSpan[] offsets = TimeZoneInfo.Local.GetAmbiguousTimeOffsets(inputDate);
- for (int ctr = 0; ctr < offsets.Length; ctr++)
- {
- Console.WriteLine("{0}.) {1} hours, {2} minutes", ctr, offsets[ctr].Hours, offsets[ctr].Minutes);
- }
- Console.Write("> ");
- int selection = int.Parse(Console.ReadLine());
-
- // Convert local time to UTC, and set Kind property to DateTimeKind.Utc
- utcDate = DateTime.SpecifyKind(inputDate - offsets[selection], DateTimeKind.Utc);
+ // Map an ambiguous time to the time zone's standard time
+ //
+ private DateTime ResolveAmbiguousTime(DateTime ambiguousTime)
+ {
+ // Time is not ambiguous
+ if (!TimeZoneInfo.Local.IsAmbiguousTime(ambiguousTime))
+ {
+ return ambiguousTime;
+ }
+ // Time is ambiguous
+ else
+ {
+ DateTime utcTime = DateTime.SpecifyKind(ambiguousTime - TimeZoneInfo.Local.BaseUtcOffset,
+ DateTimeKind.Utc);
+ Console.WriteLine($"{ambiguousTime} local time corresponds to {utcTime} {utcTime.Kind}.");
+ return utcTime;
+ }
+ }
+ //
- Console.WriteLine("{0} local time corresponds to {1} {2}.", inputDate, utcDate, utcDate.Kind.ToString());
- }
- else
- {
- utcDate = inputDate.ToUniversalTime();
- Console.WriteLine("{0} local time corresponds to {1} {2}.", inputDate, utcDate, utcDate.Kind.ToString());
- }
- }
+ // Allow the user to resolve an ambiguous time
+ //
+ private void GetUserDateInput()
+ {
+ // Get date and time from user
+ DateTime inputDate = GetUserDateTime();
+ DateTime utcDate;
- private DateTime GetUserDateTime()
- {
- bool exitFlag = false; // flag to exit loop if date is valid
- string dateString;
- DateTime inputDate = DateTime.MinValue;
-
- Console.Write("Enter a local date and time: ");
- while (!exitFlag)
- {
- dateString = Console.ReadLine();
- if (dateString.ToUpper() == "E")
- exitFlag = true;
-
- if (DateTime.TryParse(dateString, out inputDate))
- exitFlag = true;
- else
- Console.Write("Enter a valid date and time, or enter 'e' to exit: ");
- }
+ // Exit if date has no significant value
+ if (inputDate == DateTime.MinValue) return;
- return inputDate;
- }
- //
+ if (TimeZoneInfo.Local.IsAmbiguousTime(inputDate))
+ {
+ Console.WriteLine("The date you've entered is ambiguous.");
+ Console.WriteLine("Please select the correct offset from Universal Coordinated Time:");
+ TimeSpan[] offsets = TimeZoneInfo.Local.GetAmbiguousTimeOffsets(inputDate);
+ for (int ctr = 0; ctr < offsets.Length; ctr++)
+ {
+ Console.WriteLine($"{ctr}.) {offsets[ctr].Hours} hours, {offsets[ctr].Minutes} minutes");
+ }
+ Console.Write("> ");
+ int selection = int.Parse(Console.ReadLine());
+
+ // Convert local time to UTC, and set Kind property to DateTimeKind.Utc
+ utcDate = DateTime.SpecifyKind(inputDate - offsets[selection], DateTimeKind.Utc);
+
+ Console.WriteLine($"{inputDate} local time corresponds to {utcDate} {utcDate.Kind}.");
+ }
+ else
+ {
+ utcDate = inputDate.ToUniversalTime();
+ Console.WriteLine($"{inputDate} local time corresponds to {utcDate} {utcDate.Kind}.");
+ }
+ }
+
+ private DateTime GetUserDateTime()
+ {
+ bool exitFlag = false; // flag to exit loop if date is valid
+ string dateString;
+ DateTime inputDate = DateTime.MinValue;
+
+ Console.Write("Enter a local date and time: ");
+ while (!exitFlag)
+ {
+ dateString = Console.ReadLine();
+ if (dateString.ToUpper() == "E")
+ exitFlag = true;
+
+ if (DateTime.TryParse(dateString, out inputDate))
+ exitFlag = true;
+ else
+ Console.Write("Enter a valid date and time, or enter 'e' to exit: ");
+ }
+
+ return inputDate;
+ }
+ //
}
public class TZListForm : Form
{
- private System.Windows.Forms.ListBox timeZoneList;
- private System.Windows.Forms.Button OkButton;
-
- public TZListForm()
- {
- this.timeZoneList = new System.Windows.Forms.ListBox();
- this.OkButton = new System.Windows.Forms.Button();
- this.SuspendLayout();
- //
- // timeZoneList
- //
- this.timeZoneList.FormattingEnabled = true;
- this.timeZoneList.Location = new System.Drawing.Point(12, 12);
- this.timeZoneList.Name = "timeZoneList";
- this.timeZoneList.Size = new System.Drawing.Size(250, 212);
- this.timeZoneList.TabIndex = 0;
- //
- // OkButton
- //
- this.OkButton.Location = new System.Drawing.Point(186, 231);
- this.OkButton.Name = "OkButton";
- this.OkButton.Size = new System.Drawing.Size(75, 23);
- this.OkButton.TabIndex = 1;
- this.OkButton.Text = "&OK";
- this.OkButton.UseVisualStyleBackColor = true;
- this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(292, 266);
- this.Controls.Add(this.OkButton);
- this.Controls.Add(this.timeZoneList);
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.ResumeLayout(false);
- }
+ private System.Windows.Forms.ListBox timeZoneList;
+ private System.Windows.Forms.Button OkButton;
+
+ public TZListForm()
+ {
+ this.timeZoneList = new();
+ this.OkButton = new();
+ this.SuspendLayout();
+ //
+ // timeZoneList
+ //
+ this.timeZoneList.FormattingEnabled = true;
+ this.timeZoneList.Location = new(12, 12);
+ this.timeZoneList.Name = "timeZoneList";
+ this.timeZoneList.Size = new(250, 212);
+ this.timeZoneList.TabIndex = 0;
+ //
+ // OkButton
+ //
+ this.OkButton.Location = new(186, 231);
+ this.OkButton.Name = "OkButton";
+ this.OkButton.Size = new(75, 23);
+ this.OkButton.TabIndex = 1;
+ this.OkButton.Text = "&OK";
+ this.OkButton.UseVisualStyleBackColor = true;
+ this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
+ //
+ // Form1
+ //
+ this.AutoScaleDimensions = new(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ this.ClientSize = new(292, 266);
+ this.Controls.Add(this.OkButton);
+ this.Controls.Add(this.timeZoneList);
+ this.Name = "Form1";
+ this.Text = "Form1";
+ this.Load += new System.EventHandler(this.Form1_Load);
+ this.ResumeLayout(false);
+ }
+
+ //
+ private void Form1_Load(object sender, EventArgs e)
+ {
+ ReadOnlyCollection tzCollection;
+ tzCollection = TimeZoneInfo.GetSystemTimeZones();
+ this.timeZoneList.DataSource = tzCollection;
+ }
+
+ private void OkButton_Click(object sender, EventArgs e)
+ {
+ TimeZoneInfo selectedTimeZone = (TimeZoneInfo)this.timeZoneList.SelectedItem;
+ MessageBox.Show("You selected the " + selectedTimeZone + " time zone.");
+ }
+ //
- //
- private void Form1_Load(object sender, EventArgs e)
- {
- ReadOnlyCollection tzCollection;
- tzCollection = TimeZoneInfo.GetSystemTimeZones();
- this.timeZoneList.DataSource = tzCollection;
- }
+ private void ShowLocalAndUtc()
+ {
+ //
+ // Create Eastern Standard Time value and TimeZoneInfo object
+ DateTime estTime = new(2007, 1, 1, 00, 00, 00);
+ string timeZoneName = "Eastern Standard Time";
+ try
+ {
+ TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
- private void OkButton_Click(object sender, EventArgs e)
- {
- TimeZoneInfo selectedTimeZone = (TimeZoneInfo) this.timeZoneList.SelectedItem;
- MessageBox.Show("You selected the " + selectedTimeZone.ToString() + " time zone.");
- }
- //
+ // Convert EST to local time
+ DateTime localTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Local);
+ Console.WriteLine($"At {estTime} {est}, the local time is {localTime} {(TimeZoneInfo.Local.IsDaylightSavingTime(localTime) ?
+ TimeZoneInfo.Local.DaylightName :
+ TimeZoneInfo.Local.StandardName)}.");
- private void ShowLocalAndUtc()
- {
- //
- // Create Eastern Standard Time value and TimeZoneInfo object
- DateTime estTime = new DateTime(2007, 1, 1, 00, 00, 00);
- string timeZoneName = "Eastern Standard Time";
- try
- {
- TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
-
- // Convert EST to local time
- DateTime localTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Local);
- Console.WriteLine("At {0} {1}, the local time is {2} {3}.",
- estTime,
- est,
- localTime,
- TimeZoneInfo.Local.IsDaylightSavingTime(localTime) ?
- TimeZoneInfo.Local.DaylightName :
- TimeZoneInfo.Local.StandardName);
-
- // Convert EST to UTC
- DateTime utcTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Utc);
- Console.WriteLine("At {0} {1}, the time is {2} {3}.",
- estTime,
- est,
- utcTime,
- TimeZoneInfo.Utc.StandardName);
- }
- catch (TimeZoneNotFoundException)
- {
- Console.WriteLine("The {0} zone cannot be found in the registry.",
- timeZoneName);
- }
- catch (InvalidTimeZoneException)
- {
- Console.WriteLine("The registry contains invalid data for the {0} zone.",
- timeZoneName);
- }
- //
- }
+ // Convert EST to UTC
+ DateTime utcTime = TimeZoneInfo.ConvertTime(estTime, est, TimeZoneInfo.Utc);
+ Console.WriteLine($"At {estTime} {est}, the time is {utcTime} {TimeZoneInfo.Utc.StandardName}.");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine($"The {timeZoneName} zone cannot be found in the registry.");
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine($"The registry contains invalid data for the {timeZoneName} zone.");
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs
index a060daa1a61..1ff28977fad 100644
--- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime1.cs
@@ -1,46 +1,48 @@
//
using System;
-public class Example
+public class ConvertTimeExample1
{
- public static void Main()
- {
- // Define times to be converted.
- DateTime[] times = { new DateTime(2010, 1, 1, 0, 1, 0),
- new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Utc),
- new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Local),
+ public static void Run()
+ {
+ // Define times to be converted.
+ DateTime[] times = [ new DateTime(2010, 1, 1, 0, 1, 0),
+ new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Utc),
+ new DateTime(2010, 1, 1, 0, 1, 0, DateTimeKind.Local),
new DateTime(2010, 11, 6, 23, 30, 0),
- new DateTime(2010, 11, 7, 2, 30, 0) };
-
- // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
- TimeZoneInfo est;
- try {
- est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
- }
- catch (TimeZoneNotFoundException) {
- Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
- return;
- }
- catch (InvalidTimeZoneException) {
- Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
- return;
- }
+ new DateTime(2010, 11, 7, 2, 30, 0) ];
- // Display the current time zone name.
- Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName);
-
- // Convert each time in the array.
- foreach (DateTime timeToConvert in times)
- {
- DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
- Console.WriteLine("Converted {0} {1} to {2}.", timeToConvert,
- timeToConvert.Kind, targetTime);
- }
- }
+ // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
+ TimeZoneInfo est;
+ try
+ {
+ est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
+ return;
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
+ return;
+ }
+
+ // Display the current time zone name.
+ Console.WriteLine($"Local time zone: {TimeZoneInfo.Local.DisplayName}\n");
+
+ // Convert each time in the array.
+ foreach (DateTime timeToConvert in times)
+ {
+ DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
+ Console.WriteLine($"Converted {timeToConvert} {timeToConvert.Kind} to {targetTime}.");
+ }
+ }
}
// The example displays the following output:
// Local time zone: (GMT-08:00) Pacific Time (US & Canada)
-//
+//
// Converted 1/1/2010 12:01:00 AM Unspecified to 1/1/2010 3:01:00 AM.
// Converted 1/1/2010 12:01:00 AM Utc to 12/31/2009 7:01:00 PM.
// Converted 1/1/2010 12:01:00 AM Local to 1/1/2010 3:01:00 AM.
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs
index 21a4ad4b5db..e518861d1a6 100644
--- a/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTime/converttime2.cs
@@ -1,46 +1,49 @@
//
using System;
-public class Example
+public class ConvertTimeExample2
{
- public static void Main()
- {
- // Define times to be converted.
- DateTime time1 = new DateTime(2010, 1, 1, 12, 1, 0);
- DateTime time2 = new DateTime(2010, 11, 6, 23, 30, 0);
- DateTimeOffset[] times = { new DateTimeOffset(time1, TimeZoneInfo.Local.GetUtcOffset(time1)),
+ public static void Run()
+ {
+ // Define times to be converted.
+ DateTime time1 = new(2010, 1, 1, 12, 1, 0);
+ DateTime time2 = new(2010, 11, 6, 23, 30, 0);
+ DateTimeOffset[] times = [ new DateTimeOffset(time1, TimeZoneInfo.Local.GetUtcOffset(time1)),
new DateTimeOffset(time1, TimeSpan.Zero),
new DateTimeOffset(time2, TimeZoneInfo.Local.GetUtcOffset(time2)),
- new DateTimeOffset(time2.AddHours(3), TimeZoneInfo.Local.GetUtcOffset(time2.AddHours(3))) };
-
- // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
- TimeZoneInfo est;
- try {
- est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
- }
- catch (TimeZoneNotFoundException) {
- Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
- return;
- }
- catch (InvalidTimeZoneException) {
- Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
- return;
- }
+ new DateTimeOffset(time2.AddHours(3), TimeZoneInfo.Local.GetUtcOffset(time2.AddHours(3))) ];
- // Display the current time zone name.
- Console.WriteLine("Local time zone: {0}\n", TimeZoneInfo.Local.DisplayName);
-
- // Convert each time in the array.
- foreach (DateTimeOffset timeToConvert in times)
- {
- DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
- Console.WriteLine("Converted {0} to {1}.", timeToConvert, targetTime);
- }
- }
+ // Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
+ TimeZoneInfo est;
+ try
+ {
+ est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ }
+ catch (TimeZoneNotFoundException)
+ {
+ Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
+ return;
+ }
+ catch (InvalidTimeZoneException)
+ {
+ Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
+ return;
+ }
+
+ // Display the current time zone name.
+ Console.WriteLine($"Local time zone: {TimeZoneInfo.Local.DisplayName}\n");
+
+ // Convert each time in the array.
+ foreach (DateTimeOffset timeToConvert in times)
+ {
+ DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
+ Console.WriteLine($"Converted {timeToConvert} to {targetTime}.");
+ }
+ }
}
// The example displays the following output:
// Local time zone: (GMT-08:00) Pacific Time (US & Canada)
-//
+//
// Converted 1/1/2010 12:01:00 AM -08:00 to 1/1/2010 3:01:00 AM -05:00.
// Converted 1/1/2010 12:01:00 AM +00:00 to 12/31/2009 7:01:00 PM -05:00.
// Converted 11/6/2010 11:30:00 PM -07:00 to 11/7/2010 1:30:00 AM -05:00.
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs
index 9116ab83038..9c734110837 100644
--- a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/System.TimeZone2.Conversions.cs
@@ -1,109 +1,101 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
public class TimeZoneConversion
{
- public static void Main()
- {
- TimeZoneConversion tzc = new TimeZoneConversion();
- Console.WriteLine("\nConvertToUtc:");
- tzc.ConvertToUtc();
- Console.WriteLine("\nConvertZonesToUtc:");
- tzc.ConvertZonesToUtc();
- Console.WriteLine();
- tzc.ConvertZonesById();
- }
+ public static void Main()
+ {
+ TimeZoneConversion tzc = new();
+ Console.WriteLine("\nConvertToUtc:");
+ tzc.ConvertToUtc();
+ Console.WriteLine("\nConvertZonesToUtc:");
+ tzc.ConvertZonesToUtc();
+ Console.WriteLine();
+ tzc.ConvertZonesById();
+ }
- private void ConvertToUtc()
- {
- //
- DateTime datNowLocal = DateTime.Now;
- Console.WriteLine("Converting {0}, Kind {1}:", datNowLocal, datNowLocal.Kind);
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNowLocal), TimeZoneInfo.ConvertTimeToUtc(datNowLocal).Kind);
- Console.WriteLine();
+ private void ConvertToUtc()
+ {
+ //
+ DateTime datNowLocal = DateTime.Now;
+ Console.WriteLine($"Converting {datNowLocal}, Kind {datNowLocal.Kind}:");
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNowLocal)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNowLocal).Kind}");
+ Console.WriteLine();
- DateTime datNowUtc = DateTime.UtcNow;
- Console.WriteLine("Converting {0}, Kind {1}", datNowUtc, datNowUtc.Kind);
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNowUtc), TimeZoneInfo.ConvertTimeToUtc(datNowUtc).Kind);
- Console.WriteLine();
-
- DateTime datNow = new DateTime(2007, 10, 26, 13, 32, 00);
- Console.WriteLine("Converting {0}, Kind {1}", datNow, datNow.Kind);
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNow), TimeZoneInfo.ConvertTimeToUtc(datNow).Kind);
- Console.WriteLine();
-
- DateTime datAmbiguous = new DateTime(2007, 11, 4, 1, 30, 00);
- Console.WriteLine("Converting {0}, Kind {1}, Ambiguous {2}", datAmbiguous, datAmbiguous.Kind, TimeZoneInfo.Local.IsAmbiguousTime(datAmbiguous));
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datAmbiguous), TimeZoneInfo.ConvertTimeToUtc(datAmbiguous).Kind);
- Console.WriteLine();
-
- DateTime datInvalid = new DateTime(2007, 3, 11, 02, 30, 00);
- Console.WriteLine("Converting {0}, Kind {1}, Invalid {2}", datInvalid, datInvalid.Kind, TimeZoneInfo.Local.IsInvalidTime(datInvalid));
- try
- {
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datInvalid), TimeZoneInfo.ConvertTimeToUtc(datInvalid).Kind);
- }
- catch (ArgumentException e)
- {
- Console.WriteLine(" {0}: Cannot convert {1} to UTC.", e.GetType().Name, datInvalid);
- }
- Console.WriteLine();
+ DateTime datNowUtc = DateTime.UtcNow;
+ Console.WriteLine($"Converting {datNowUtc}, Kind {datNowUtc.Kind}");
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNowUtc)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNowUtc).Kind}");
+ Console.WriteLine();
- DateTime datNearMax = new DateTime(9999, 12, 31, 22, 00, 00);
- Console.WriteLine("Converting {0}, Kind {1}", datNearMax, datNearMax.Kind);
- Console.WriteLine(" ConvertTimeToUtc: {0}, Kind {1}", TimeZoneInfo.ConvertTimeToUtc(datNearMax), TimeZoneInfo.ConvertTimeToUtc(datNearMax).Kind);
- Console.WriteLine();
- //
- // This example produces the following output if the local time zone
- // is Pacific Standard Time:
- //
- // Converting 8/31/2007 2:26:28 PM, Kind Local:
- // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc
- //
- // Converting 8/31/2007 9:26:28 PM, Kind Utc
- // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc
- //
- // Converting 10/26/2007 1:32:00 PM, Kind Unspecified
- // ConvertTimeToUtc: 10/26/2007 8:32:00 PM, Kind Utc
- //
- // Converting 11/4/2007 1:30:00 AM, Kind Unspecified, Ambiguous True
- // ConvertTimeToUtc: 11/4/2007 9:30:00 AM, Kind Utc
- //
- // Converting 3/11/2007 2:30:00 AM, Kind Unspecified, Invalid True
- // ArgumentException: Cannot convert 3/11/2007 2:30:00 AM to UTC.
- //
- // Converting 12/31/9999 10:00:00 PM, Kind Unspecified
- // ConvertTimeToUtc: 12/31/9999 11:59:59 PM, Kind Utc
- //
- //
- }
+ DateTime datNow = new(2007, 10, 26, 13, 32, 00);
+ Console.WriteLine($"Converting {datNow}, Kind {datNow.Kind}");
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNow)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNow).Kind}");
+ Console.WriteLine();
- private void ConvertZonesToUtc()
- {
- }
+ DateTime datAmbiguous = new(2007, 11, 4, 1, 30, 00);
+ Console.WriteLine($"Converting {datAmbiguous}, Kind {datAmbiguous.Kind}, Ambiguous {TimeZoneInfo.Local.IsAmbiguousTime(datAmbiguous)}");
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datAmbiguous)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datAmbiguous).Kind}");
+ Console.WriteLine();
- private void ConvertZonesById()
- {
- //
- DateTime currentTime = DateTime.Now;
- Console.WriteLine("Current Times:");
- Console.WriteLine();
- Console.WriteLine("Los Angeles: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time"));
- Console.WriteLine("Chicago: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time"));
- Console.WriteLine("New York: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time"));
- Console.WriteLine("London: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time"));
- Console.WriteLine("Moscow: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time"));
- Console.WriteLine("New Delhi: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time"));
- Console.WriteLine("Beijing: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time"));
- Console.WriteLine("Tokyo: {0}",
- TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time"));
- //
- }
+ DateTime datInvalid = new(2007, 3, 11, 02, 30, 00);
+ Console.WriteLine($"Converting {datInvalid}, Kind {datInvalid.Kind}, Invalid {TimeZoneInfo.Local.IsInvalidTime(datInvalid)}");
+ try
+ {
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datInvalid)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datInvalid).Kind}");
+ }
+ catch (ArgumentException e)
+ {
+ Console.WriteLine($" {e.GetType().Name}: Cannot convert {datInvalid} to UTC.");
+ }
+ Console.WriteLine();
+
+ DateTime datNearMax = new(9999, 12, 31, 22, 00, 00);
+ Console.WriteLine($"Converting {datNearMax}, Kind {datNearMax.Kind}");
+ Console.WriteLine($" ConvertTimeToUtc: {TimeZoneInfo.ConvertTimeToUtc(datNearMax)}, Kind {TimeZoneInfo.ConvertTimeToUtc(datNearMax).Kind}");
+ Console.WriteLine();
+ //
+ // This example produces the following output if the local time zone
+ // is Pacific Standard Time:
+ //
+ // Converting 8/31/2007 2:26:28 PM, Kind Local:
+ // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc
+ //
+ // Converting 8/31/2007 9:26:28 PM, Kind Utc
+ // ConvertTimeToUtc: 8/31/2007 9:26:28 PM, Kind Utc
+ //
+ // Converting 10/26/2007 1:32:00 PM, Kind Unspecified
+ // ConvertTimeToUtc: 10/26/2007 8:32:00 PM, Kind Utc
+ //
+ // Converting 11/4/2007 1:30:00 AM, Kind Unspecified, Ambiguous True
+ // ConvertTimeToUtc: 11/4/2007 9:30:00 AM, Kind Utc
+ //
+ // Converting 3/11/2007 2:30:00 AM, Kind Unspecified, Invalid True
+ // ArgumentException: Cannot convert 3/11/2007 2:30:00 AM to UTC.
+ //
+ // Converting 12/31/9999 10:00:00 PM, Kind Unspecified
+ // ConvertTimeToUtc: 12/31/9999 11:59:59 PM, Kind Utc
+ //
+ //
+ }
+
+ private void ConvertZonesToUtc()
+ {
+ }
+
+ private void ConvertZonesById()
+ {
+ //
+ DateTime currentTime = DateTime.Now;
+ Console.WriteLine("Current Times:");
+ Console.WriteLine();
+ Console.WriteLine($"Los Angeles: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time")}");
+ Console.WriteLine($"Chicago: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time")}");
+ Console.WriteLine($"New York: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time")}");
+ Console.WriteLine($"London: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time")}");
+ Console.WriteLine($"Moscow: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time")}");
+ Console.WriteLine($"New Delhi: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time")}");
+ Console.WriteLine($"Beijing: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time")}");
+ Console.WriteLine($"Tokyo: {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time")}");
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs
index 8840694a6ab..c42551b7094 100644
--- a/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs
+++ b/snippets/csharp/System/TimeZoneInfo/ConvertTimeBySystemTimeZoneId/convertdt2.cs
@@ -3,20 +3,20 @@
public class Example
{
- public static void Main()
- {
- // Get time in local time zone
- DateTime thisTime = DateTime.Now;
- Console.WriteLine("Time in {0} zone: {1}", TimeZoneInfo.Local.IsDaylightSavingTime(thisTime) ?
- TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName, thisTime);
- Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local));
- // Get Tokyo Standard Time zone
- TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
- DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst);
- Console.WriteLine("Time in {0} zone: {1}", tst.IsDaylightSavingTime(tstTime) ?
- tst.DaylightName : tst.StandardName, tstTime);
- Console.WriteLine(" UTC Time: {0}", TimeZoneInfo.ConvertTimeToUtc(tstTime, tst));
- }
+ public static void Main()
+ {
+ // Get time in local time zone
+ DateTime thisTime = DateTime.Now;
+ Console.WriteLine($"Time in {(TimeZoneInfo.Local.IsDaylightSavingTime(thisTime) ?
+ TimeZoneInfo.Local.DaylightName : TimeZoneInfo.Local.StandardName)} zone: {thisTime}");
+ Console.WriteLine($" UTC Time: {TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local)}");
+ // Get Tokyo Standard Time zone
+ TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
+ DateTime tstTime = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst);
+ Console.WriteLine($"Time in {(tst.IsDaylightSavingTime(tstTime) ?
+ tst.DaylightName : tst.StandardName)} zone: {tstTime}");
+ Console.WriteLine($" UTC Time: {TimeZoneInfo.ConvertTimeToUtc(tstTime, tst)}");
+ }
}
// The example displays output like the following when run on a system in the
// U.S. Pacific Standard Time zone:
diff --git a/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs b/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs
index 009775a0c46..ae9f0a3c7b0 100644
--- a/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs
+++ b/snippets/csharp/System/TimeZoneInfo/CreateCustomTimeZone/System.TimeZone2.CreateTimeZone.cs
@@ -2,261 +2,249 @@
using System.IO;
//
using System.Collections.Generic;
-using System.Collections.ObjectModel;
+
//
public class TimeZoneCreation
{
- public static void Main()
- {
- Console.WriteLine("First Overload of CreateCustomTimeZone: ");
- TimeZoneCreation tzc = new TimeZoneCreation();
- tzc.DefineMawsonTime();
- Console.WriteLine();
- Console.WriteLine("Second Overload of CreateCustomTimeZone: ");
- tzc.DefinePalmerTime();
- Console.WriteLine();
- tzc.DefineNonDSTTime();
- Console.WriteLine("About to create Antarctic/South Pole time zone");
- // Define Time Zone for Serialization
- TimeZoneInfo southPole = tzc.InitializeTimeZone();
- tzc.TestCST();
- }
+ public static void Main()
+ {
+ Console.WriteLine("First Overload of CreateCustomTimeZone: ");
+ TimeZoneCreation tzc = new();
+ tzc.DefineMawsonTime();
+ Console.WriteLine();
+ Console.WriteLine("Second Overload of CreateCustomTimeZone: ");
+ tzc.DefinePalmerTime();
+ Console.WriteLine();
+ tzc.DefineNonDSTTime();
+ Console.WriteLine("About to create Antarctic/South Pole time zone");
+ // Define Time Zone for Serialization
+ TimeZoneInfo southPole = tzc.InitializeTimeZone();
+ tzc.TestCST();
+ }
+
+ private void TestCST()
+ {
+ Console.WriteLine();
+ Console.WriteLine("Testing new Central Standard Time zone...");
+ Console.WriteLine();
+ TimeZoneInfo cst = CreateNewCentralStandardTimeZone();
+ //
+ TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+
+ DateTime pastDate1 = new(1942, 2, 11);
+ Console.WriteLine($"Is {pastDate1} daylight saving time: {cst.IsDaylightSavingTime(pastDate1)}");
- private void TestCST()
- {
- Console.WriteLine();
- Console.WriteLine("Testing new Central Standard Time zone...");
- Console.WriteLine();
- TimeZoneInfo cst = CreateNewCentralStandardTimeZone();
- //
- TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ DateTime pastDate2 = new(1967, 10, 29, 1, 30, 00);
+ Console.WriteLine($"Is {pastDate2} ambiguous: {cst.IsAmbiguousTime(pastDate2)}");
- DateTime pastDate1 = new DateTime(1942, 2, 11);
- Console.WriteLine("Is {0} daylight saving time: {1}", pastDate1,
- cst.IsDaylightSavingTime(pastDate1));
-
- DateTime pastDate2 = new DateTime(1967, 10, 29, 1, 30, 00);
- Console.WriteLine("Is {0} ambiguous: {1}", pastDate2,
- cst.IsAmbiguousTime(pastDate2));
+ DateTime pastDate3 = new(1974, 1, 7, 2, 59, 00);
+ Console.WriteLine($"{pastDate3} {(est.IsDaylightSavingTime(pastDate3) ?
+ est.DaylightName : est.StandardName)} is {TimeZoneInfo.ConvertTime(pastDate3, est, cst)} {(cst.IsDaylightSavingTime(TimeZoneInfo.ConvertTime(pastDate3, est, cst)) ?
+ cst.DaylightName : cst.StandardName)}");
+ //
+ // This code produces the following output to the console:
+ //
+ // Is 2/11/1942 12:00:00 AM daylight saving time: True
+ // Is 10/29/1967 1:30:00 AM ambiguous: True
+ // 1/7/1974 2:59:00 AM Eastern Standard Time is 1/7/1974 2:59:00 AM Central Daylight Time
+ //
+ }
- DateTime pastDate3 = new DateTime(1974, 1, 7, 2, 59, 00);
- Console.WriteLine("{0} {1} is {2} {3}", pastDate3,
- est.IsDaylightSavingTime(pastDate3) ?
- est.DaylightName : est.StandardName,
- TimeZoneInfo.ConvertTime(pastDate3, est, cst),
- cst.IsDaylightSavingTime(TimeZoneInfo.ConvertTime(pastDate3, est, cst)) ?
- cst.DaylightName : cst.StandardName);
- //
- // This code produces the following output to the console:
- //
- // Is 2/11/1942 12:00:00 AM daylight saving time: True
- // Is 10/29/1967 1:30:00 AM ambiguous: True
- // 1/7/1974 2:59:00 AM Eastern Standard Time is 1/7/1974 2:59:00 AM Central Daylight Time
- //
- }
+ private void DefineMawsonTime()
+ {
+ //
+ string displayName = "(GMT+06:00) Antarctica/Mawson Time";
+ string standardName = "Mawson Time";
+ TimeSpan offset = new(06, 00, 00);
+ TimeZoneInfo mawson = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName);
+ Console.WriteLine($"The current time is {TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, mawson)} {mawson.StandardName}");
+ //
+ }
- private void DefineMawsonTime()
- {
- //
- string displayName = "(GMT+06:00) Antarctica/Mawson Time";
- string standardName = "Mawson Time";
- TimeSpan offset = new TimeSpan(06, 00, 00);
- TimeZoneInfo mawson = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName);
- Console.WriteLine("The current time is {0} {1}",
- TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, mawson),
- mawson.StandardName);
- //
- }
-
- private void DefinePalmerTime()
- {
- //
- // Define transition times to/from DST
- TimeZoneInfo.TransitionTime startTransition, endTransition;
- startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0),
- 10, 2, DayOfWeek.Sunday);
- endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0),
- 3, 2, DayOfWeek.Sunday);
- // Define adjustment rule
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment;
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
- // Create array for adjustment rules
- TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment};
- // Define other custom time zone arguments
- string displayName = "(GMT-04:00) Antarctica/Palmer Time";
- string standardName = "Palmer Time";
- string daylightName = "Palmer Daylight Time";
- TimeSpan offset = new TimeSpan(-4, 0, 0);
- TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments);
- Console.WriteLine("The current time is {0} {1}",
- TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, palmer),
- palmer.StandardName);
- //
- }
+ private void DefinePalmerTime()
+ {
+ //
+ // Define transition times to/from DST
+ TimeZoneInfo.TransitionTime startTransition, endTransition;
+ startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0),
+ 10, 2, DayOfWeek.Sunday);
+ endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0),
+ 3, 2, DayOfWeek.Sunday);
+ // Define adjustment rule
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment;
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
+ // Create array for adjustment rules
+ TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ];
+ // Define other custom time zone arguments
+ string displayName = "(GMT-04:00) Antarctica/Palmer Time";
+ string standardName = "Palmer Time";
+ string daylightName = "Palmer Daylight Time";
+ TimeSpan offset = new(-4, 0, 0);
+ TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments);
+ Console.WriteLine($"The current time is {TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, palmer)} {palmer.StandardName}");
+ //
+ }
- private void DefineNonDSTTime()
- {
- //
- // Define transition times to/from DST
- TimeZoneInfo.TransitionTime startTransition, endTransition;
- startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0),
- 10, 2, DayOfWeek.Sunday);
- endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1,3, 0, 0),
- 3, 2, DayOfWeek.Sunday);
- // Define adjustment rule
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1),
- DateTime.MaxValue.Date, delta, startTransition, endTransition);
- // Create array for adjustment rules
- TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment};
- // Define other custom time zone arguments
- string displayName = "(GMT-04:00) Antarctica/Palmer Time";
- string standardName = "Palmer Standard Time";
- string daylightName = "Palmer Daylight Time";
- TimeSpan offset = new TimeSpan(-4, 0, 0);
- // Create custom time zone without copying DST information
- TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName,
- daylightName, adjustments, true);
- // Indicate whether new time zone//s adjustment rules are present
- Console.WriteLine("{0} {1}has {2} adjustment rules.",
- palmer.StandardName,
- ! (string.IsNullOrEmpty(palmer.DaylightName)) ? "(" + palmer.DaylightName + ") ": "" ,
- palmer.GetAdjustmentRules().Length);
- // Indicate whether new time zone supports DST
- Console.WriteLine("{0} supports DST: {1}", palmer.StandardName, palmer.SupportsDaylightSavingTime);
- //
- }
+ private void DefineNonDSTTime()
+ {
+ //
+ // Define transition times to/from DST
+ TimeZoneInfo.TransitionTime startTransition, endTransition;
+ startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0),
+ 10, 2, DayOfWeek.Sunday);
+ endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0),
+ 3, 2, DayOfWeek.Sunday);
+ // Define adjustment rule
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1),
+ DateTime.MaxValue.Date, delta, startTransition, endTransition);
+ // Create array for adjustment rules
+ TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ];
+ // Define other custom time zone arguments
+ string displayName = "(GMT-04:00) Antarctica/Palmer Time";
+ string standardName = "Palmer Standard Time";
+ string daylightName = "Palmer Daylight Time";
+ TimeSpan offset = new(-4, 0, 0);
+ // Create custom time zone without copying DST information
+ TimeZoneInfo palmer = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName,
+ daylightName, adjustments, true);
+ // Indicate whether new time zone//s adjustment rules are present
+ Console.WriteLine($"{palmer.StandardName} {(!(string.IsNullOrEmpty(palmer.DaylightName)) ? "(" + palmer.DaylightName + ") " : "")}has {palmer.GetAdjustmentRules().Length} adjustment rules.");
+ // Indicate whether new time zone supports DST
+ Console.WriteLine($"{palmer.StandardName} supports DST: {palmer.SupportsDaylightSavingTime}");
+ //
+ }
- //
- private TimeZoneInfo InitializeTimeZone()
- {
- TimeZoneInfo southPole = null;
- // Determine if South Pole time zone is defined in system
- try
- {
- southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");
- }
- // Time zone does not exist; create it, store it in a text file, and return it
- catch
- {
- const string filename = @".\TimeZoneInfo.txt";
- bool found = false;
-
- if (File.Exists(filename))
- {
- StreamReader reader = new StreamReader(filename);
- string timeZoneInfo;
- while (reader.Peek() >= 0)
+ //
+ private TimeZoneInfo InitializeTimeZone()
+ {
+ TimeZoneInfo southPole = null;
+ // Determine if South Pole time zone is defined in system
+ try
+ {
+ southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");
+ }
+ // Time zone does not exist; create it, store it in a text file, and return it
+ catch
+ {
+ const string filename = @".\TimeZoneInfo.txt";
+ bool found = false;
+
+ if (File.Exists(filename))
{
- timeZoneInfo = reader.ReadLine();
- if (timeZoneInfo.Contains("Antarctica/South Pole"))
- {
- southPole = TimeZoneInfo.FromSerializedString(timeZoneInfo);
- reader.Close();
- found = true;
- break;
- }
+ StreamReader reader = new(filename);
+ string timeZoneInfo;
+ while (reader.Peek() >= 0)
+ {
+ timeZoneInfo = reader.ReadLine();
+ if (timeZoneInfo.Contains("Antarctica/South Pole"))
+ {
+ southPole = TimeZoneInfo.FromSerializedString(timeZoneInfo);
+ reader.Close();
+ found = true;
+ break;
+ }
+ }
}
- }
- if (!found)
- {
- // Define transition times to/from DST
- TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 1, DayOfWeek.Sunday);
- TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 3, DayOfWeek.Sunday);
- // Define adjustment rule
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1989, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
- // Create array for adjustment rules
- TimeZoneInfo.AdjustmentRule[] adjustments = {adjustment};
- // Define other custom time zone arguments
- string displayName = "(GMT+12:00) Antarctica/South Pole";
- string standardName = "Antarctica/South Pole Standard Time";
- string daylightName = "Antarctica/South Pole Daylight Time";
- TimeSpan offset = new TimeSpan(12, 0, 0);
- southPole = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments);
- // Write time zone to the file
- StreamWriter writer = new StreamWriter(filename, true);
- writer.WriteLine(southPole.ToSerializedString());
- writer.Close();
- }
- }
- return southPole;
- }
- //
+ if (!found)
+ {
+ // Define transition times to/from DST
+ TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 1, DayOfWeek.Sunday);
+ TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 3, DayOfWeek.Sunday);
+ // Define adjustment rule
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1989, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition);
+ // Create array for adjustment rules
+ TimeZoneInfo.AdjustmentRule[] adjustments = [ adjustment ];
+ // Define other custom time zone arguments
+ string displayName = "(GMT+12:00) Antarctica/South Pole";
+ string standardName = "Antarctica/South Pole Standard Time";
+ string daylightName = "Antarctica/South Pole Daylight Time";
+ TimeSpan offset = new(12, 0, 0);
+ southPole = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName, daylightName, adjustments);
+ // Write time zone to the file
+ StreamWriter writer = new(filename, true);
+ writer.WriteLine(southPole.ToSerializedString());
+ writer.Close();
+ }
+ }
+ return southPole;
+ }
+ //
+
+ private TimeZoneInfo CreateNewCentralStandardTimeZone()
+ {
+ //
+ TimeZoneInfo cst;
+ // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
+ TimeSpan delta = new(1, 0, 0);
+ TimeZoneInfo.AdjustmentRule adjustment;
+ List adjustmentList = [];
+ // Declare transition time variables to hold transition time information
+ TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
+
+ // Define new Central Standard Time zone 6 hours earlier than UTC
+ // Define rule 1 (for 1918-1919)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 05, DayOfWeek.Sunday);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 05, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1918, 1, 1), new DateTime(1919, 12, 31), delta,
+ transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 2 (for 1942)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 09);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1942, 1, 1), new DateTime(1942, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 3 (for 1945)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 0, 0), 08, 14);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 09, 30);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1945, 1, 1), new DateTime(1945, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define end rule (for 1967-2006)
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday);
+ // Define rule 4 (for 1967-73)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1967, 1, 1), new DateTime(1973, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 5 (for 1974 only)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 01, 06);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1974, 1, 1), new DateTime(1974, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 6 (for 1975 only)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 23);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1975, 1, 1), new DateTime(1975, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 7 (1976-1986)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 8 (1987-2006)
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31),
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+ // Define rule 9 (2007- )
+ transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday);
+ transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday);
+ adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 1, 1), DateTime.MaxValue.Date,
+ delta, transitionRuleStart, transitionRuleEnd);
+ adjustmentList.Add(adjustment);
+
+ // Convert list of adjustment rules to an array
+ TimeZoneInfo.AdjustmentRule[] adjustments = new TimeZoneInfo.AdjustmentRule[adjustmentList.Count];
+ adjustmentList.CopyTo(adjustments);
- private TimeZoneInfo CreateNewCentralStandardTimeZone()
- {
- //
- TimeZoneInfo cst;
- // Declare necessary TimeZoneInfo.AdjustmentRule objects for time zone
- TimeSpan delta = new TimeSpan(1, 0, 0);
- TimeZoneInfo.AdjustmentRule adjustment;
- List adjustmentList = new List();
- // Declare transition time variables to hold transition time information
- TimeZoneInfo.TransitionTime transitionRuleStart, transitionRuleEnd;
-
- // Define new Central Standard Time zone 6 hours earlier than UTC
- // Define rule 1 (for 1918-1919)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 05, DayOfWeek.Sunday);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 05, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1918, 1, 1), new DateTime(1919, 12, 31), delta,
- transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 2 (for 1942)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 09);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1942, 1, 1), new DateTime(1942, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 3 (for 1945)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 0, 0), 08, 14);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 09, 30);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1945, 1, 1), new DateTime(1945, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define end rule (for 1967-2006)
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday);
- // Define rule 4 (for 1967-73)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1967, 1, 1), new DateTime(1973, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 5 (for 1974 only)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 01, 06);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1974, 1, 1), new DateTime(1974, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 6 (for 1975 only)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 02, 23);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1975, 1, 1), new DateTime(1975, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 7 (1976-1986)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 05, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1976, 1, 1), new DateTime(1986, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 8 (1987-2006)
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 04, 01, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1987, 1, 1), new DateTime(2006, 12, 31),
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
- // Define rule 9 (2007- )
- transitionRuleStart = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 03, 02, DayOfWeek.Sunday);
- transitionRuleEnd = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 11, 01, DayOfWeek.Sunday);
- adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2007, 1, 1), DateTime.MaxValue.Date,
- delta, transitionRuleStart, transitionRuleEnd);
- adjustmentList.Add(adjustment);
-
- // Convert list of adjustment rules to an array
- TimeZoneInfo.AdjustmentRule[] adjustments = new TimeZoneInfo.AdjustmentRule[adjustmentList.Count];
- adjustmentList.CopyTo(adjustments);
-
- cst = TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0),
- "(GMT-06:00) Central Time (US Only)", "Central Standard Time",
- "Central Daylight Time", adjustments);
- //
- return cst;
- }
+ cst = TimeZoneInfo.CreateCustomTimeZone("Central Standard Time", new TimeSpan(-6, 0, 0),
+ "(GMT-06:00) Central Time (US Only)", "Central Standard Time",
+ "Central Daylight Time", adjustments);
+ //
+ return cst;
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs b/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs
index 7078d2a0e16..6adfa570872 100644
--- a/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs
+++ b/snippets/csharp/System/TimeZoneInfo/DaylightName/IsDaylightSavingTime.cs
@@ -1,53 +1,43 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
public class DstTest
{
- public static void Main()
- {
- DstTest test = new DstTest();
- test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 05, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local);
- test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 01, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local);
- test.MayBeDST();
- }
+ public static void Main()
+ {
+ DstTest test = new();
+ test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 05, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local);
+ test.DisplayDateWithTimeZoneName(new DateTime(2006, 04, 02, 01, 00, 00, DateTimeKind.Local), TimeZoneInfo.Local);
+ test.MayBeDST();
+ }
- //
- private void DisplayDateWithTimeZoneName(DateTime date1, TimeZoneInfo timeZone)
- {
- Console.WriteLine("The time is {0:t} on {0:d} {1}",
- date1,
- timeZone.IsDaylightSavingTime(date1) ?
- timeZone.DaylightName : timeZone.StandardName);
- }
- // The example displays output similar to the following:
- // The time is 1:00 AM on 4/2/2006 Pacific Standard Time
- //
-
- private void MayBeDST()
- {
- //
- DateTime unclearDate = new DateTime(2007, 11, 4, 1, 30, 0);
- // Test if time is ambiguous.
- Console.WriteLine("In the {0}, {1} is {2}ambiguous.",
- TimeZoneInfo.Local.DisplayName,
- unclearDate,
- TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ? "" : "not ");
- // Test if time is DST.
- Console.WriteLine("In the {0}, {1} is {2}daylight saving time.",
- TimeZoneInfo.Local.DisplayName,
- unclearDate,
- TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate) ? "" : "not ");
- Console.WriteLine();
- // Report time as DST if it is either ambiguous or DST.
- if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ||
- TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate))
- Console.WriteLine("{0} may be daylight saving time in {1}.",
- unclearDate, TimeZoneInfo.Local.DisplayName);
- // The example displays the following output:
- // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is ambiguous.
- // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is not daylight saving time.
- //
- // 11/4/2007 1:30:00 AM may be daylight saving time in (GMT-08:00) Pacific Time (US & Canada).
- //
- }
+ //
+ private void DisplayDateWithTimeZoneName(DateTime date1, TimeZoneInfo timeZone) => Console.WriteLine("The time is {0:t} on {0:d} {1}",
+ date1,
+ timeZone.IsDaylightSavingTime(date1) ?
+ timeZone.DaylightName : timeZone.StandardName);
+ // The example displays output similar to the following:
+ // The time is 1:00 AM on 4/2/2006 Pacific Standard Time
+ //
+
+ private void MayBeDST()
+ {
+ //
+ DateTime unclearDate = new(2007, 11, 4, 1, 30, 0);
+ // Test if time is ambiguous.
+ Console.WriteLine($"In the {TimeZoneInfo.Local.DisplayName}, {unclearDate} is {(TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ? "" : "not ")}ambiguous.");
+ // Test if time is DST.
+ Console.WriteLine($"In the {TimeZoneInfo.Local.DisplayName}, {unclearDate} is {(TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate) ? "" : "not ")}daylight saving time.");
+ Console.WriteLine();
+ // Report time as DST if it is either ambiguous or DST.
+ if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ||
+ TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate))
+ Console.WriteLine($"{unclearDate} may be daylight saving time in {TimeZoneInfo.Local.DisplayName}.");
+ // The example displays the following output:
+ // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is ambiguous.
+ // In the (GMT-08:00) Pacific Time (US & Canada), 11/4/2007 1:30:00 AM is not daylight saving time.
+ //
+ // 11/4/2007 1:30:00 AM may be daylight saving time in (GMT-08:00) Pacific Time (US & Canada).
+ //
+ }
}
diff --git a/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs b/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs
index f2f192d1c2a..d27f1973e91 100644
--- a/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs
+++ b/snippets/csharp/System/TimeZoneInfo/Equals/equals1.cs
@@ -3,17 +3,17 @@
public class Example
{
- public static void Main()
- {
- TimeZoneInfo thisTimeZone;
- object obj1, obj2;
-
- thisTimeZone = TimeZoneInfo.Local;
- obj1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
- obj2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
- Console.WriteLine(thisTimeZone.Equals(obj1));
- Console.WriteLine(thisTimeZone.Equals(obj2));
- }
+ public static void Main()
+ {
+ TimeZoneInfo thisTimeZone;
+ object obj1, obj2;
+
+ thisTimeZone = TimeZoneInfo.Local;
+ obj1 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
+ obj2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
+ Console.WriteLine(thisTimeZone.Equals(obj1));
+ Console.WriteLine(thisTimeZone.Equals(obj2));
+ }
}
// The example displays the following output:
// True
diff --git a/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs b/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs
index e1ab69a2697..9314fc9e9b1 100644
--- a/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs
+++ b/snippets/csharp/System/TimeZoneInfo/GetAmbiguousTimeOffsets/System.TimeZone2.GetAmbiguousTimeOffsets.cs
@@ -1,102 +1,99 @@
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
namespace TimeZoneInfoCode
{
-public class TimeOffsets
-{
- public static void Main()
- {
- TimeOffsets to = new TimeOffsets();
- to.Start();
- }
-
- private void Start()
- {
- //
- Console.WriteLine();
- ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 1, 0, 0),
- TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
- Console.WriteLine();
- ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Local),
- TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
- Console.WriteLine();
- ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 00, 00, 00, DateTimeKind.Local),
- TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
- Console.WriteLine();
- ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Unspecified),
- TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
- Console.WriteLine();
- ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 07, 00, 00, DateTimeKind.Utc),
- TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
- //
- // This example produces the following output if run in the Pacific time zone:
- //
- // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times:
- // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
- // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
- //
- // 11/4/2007 1:00:00 AM Pacific Standard Time is not ambiguous in time zone (GMT-06:00) Central Time (US & Canada).
- //
- // 11/4/2007 12:00:00 AM local time maps to the following possible times:
- // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
- // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
- //
- // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times:
- // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
- // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
- //
- // 11/4/2007 7:00:00 AM UTC maps to the following possible times:
- // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
- // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
- //
- //
- }
-
- //
- private void ShowPossibleUtcTimes(DateTime ambiguousTime, TimeZoneInfo timeZone)
- {
- // Determine if time is ambiguous in target time zone
- if (!timeZone.IsAmbiguousTime(ambiguousTime))
- {
- Console.WriteLine("{0} is not ambiguous in time zone {1}.",
- ambiguousTime,
- timeZone.DisplayName);
- }
- else
- {
- // Display time and its time zone (local, UTC, or indicated by timeZone argument)
- string originalTimeZoneName;
- if (ambiguousTime.Kind == DateTimeKind.Utc)
- originalTimeZoneName = "UTC";
- else if (ambiguousTime.Kind == DateTimeKind.Local)
- originalTimeZoneName = "local time";
- else
- originalTimeZoneName = timeZone.DisplayName;
+ public class TimeOffsets
+ {
+ public static void Main()
+ {
+ TimeOffsets to = new();
+ to.Start();
+ }
- Console.WriteLine("{0} {1} maps to the following possible times:",
- ambiguousTime, originalTimeZoneName);
- // Get ambiguous offsets
- TimeSpan[] offsets = timeZone.GetAmbiguousTimeOffsets(ambiguousTime);
- // Handle times not in time zone of timeZone argument
- // Local time where timeZone is not local zone
- if ((ambiguousTime.Kind == DateTimeKind.Local) && ! timeZone.Equals(TimeZoneInfo.Local))
- ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Local, timeZone);
- // UTC time where timeZone is not UTC zone
- else if ((ambiguousTime.Kind == DateTimeKind.Utc) && ! timeZone.Equals(TimeZoneInfo.Utc))
- ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Utc, timeZone);
+ private void Start()
+ {
+ //
+ Console.WriteLine();
+ ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 1, 0, 0),
+ TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
+ Console.WriteLine();
+ ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Local),
+ TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
+ Console.WriteLine();
+ ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 00, 00, 00, DateTimeKind.Local),
+ TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
+ Console.WriteLine();
+ ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 01, 00, 00, DateTimeKind.Unspecified),
+ TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
+ Console.WriteLine();
+ ShowPossibleUtcTimes(new DateTime(2007, 11, 4, 07, 00, 00, DateTimeKind.Utc),
+ TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
+ //
+ // This example produces the following output if run in the Pacific time zone:
+ //
+ // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times:
+ // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
+ // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
+ //
+ // 11/4/2007 1:00:00 AM Pacific Standard Time is not ambiguous in time zone (GMT-06:00) Central Time (US & Canada).
+ //
+ // 11/4/2007 12:00:00 AM local time maps to the following possible times:
+ // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
+ // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
+ //
+ // 11/4/2007 1:00:00 AM (GMT-06:00) Central Time (US & Canada) maps to the following possible times:
+ // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
+ // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
+ //
+ // 11/4/2007 7:00:00 AM UTC maps to the following possible times:
+ // If 11/4/2007 1:00:00 AM is Central Standard Time, 11/4/2007 7:00:00 AM UTC
+ // If 11/4/2007 1:00:00 AM is Central Daylight Time, 11/4/2007 6:00:00 AM UTC
+ //
+ //
+ }
- // Display each offset and its mapping to UTC
- foreach (TimeSpan offset in offsets)
- {
- if (offset.Equals(timeZone.BaseUtcOffset))
- Console.WriteLine("If {0} is {1}, {2} UTC", ambiguousTime, timeZone.StandardName, ambiguousTime - offset);
+ //
+ private void ShowPossibleUtcTimes(DateTime ambiguousTime, TimeZoneInfo timeZone)
+ {
+ // Determine if time is ambiguous in target time zone
+ if (!timeZone.IsAmbiguousTime(ambiguousTime))
+ {
+ Console.WriteLine($"{ambiguousTime} is not ambiguous in time zone {timeZone.DisplayName}.");
+ }
else
- Console.WriteLine("If {0} is {1}, {2} UTC", ambiguousTime, timeZone.DaylightName, ambiguousTime - offset);
- }
- }
- }
- //
-}
+ {
+ // Display time and its time zone (local, UTC, or indicated by timeZone argument)
+ string originalTimeZoneName;
+ if (ambiguousTime.Kind == DateTimeKind.Utc)
+ originalTimeZoneName = "UTC";
+ else if (ambiguousTime.Kind == DateTimeKind.Local)
+ originalTimeZoneName = "local time";
+ else
+ originalTimeZoneName = timeZone.DisplayName;
+
+ Console.WriteLine($"{ambiguousTime} {originalTimeZoneName} maps to the following possible times:");
+ // Get ambiguous offsets
+ TimeSpan[] offsets = timeZone.GetAmbiguousTimeOffsets(ambiguousTime);
+ // Handle times not in time zone of timeZone argument
+ // Local time where timeZone is not local zone
+ if ((ambiguousTime.Kind == DateTimeKind.Local) && !timeZone.Equals(TimeZoneInfo.Local))
+ ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Local, timeZone);
+ // UTC time where timeZone is not UTC zone
+ else if ((ambiguousTime.Kind == DateTimeKind.Utc) && !timeZone.Equals(TimeZoneInfo.Utc))
+ ambiguousTime = TimeZoneInfo.ConvertTime(ambiguousTime, TimeZoneInfo.Utc, timeZone);
+
+ // Display each offset and its mapping to UTC
+ foreach (TimeSpan offset in offsets)
+ {
+ if (offset.Equals(timeZone.BaseUtcOffset))
+ Console.WriteLine($"If {ambiguousTime} is {timeZone.StandardName}, {ambiguousTime - offset} UTC");
+ else
+ Console.WriteLine($"If {ambiguousTime} is {timeZone.DaylightName}, {ambiguousTime - offset} UTC");
+ }
+ }
+ }
+ //
+ }
} // end namespace
diff --git a/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs b/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs
index e8362f99e5c..45d37a4afd0 100644
--- a/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs
+++ b/snippets/csharp/System/TimeZoneInfo/GetUtcOffset/System.TimeZone2.GetUtcOffset.cs
@@ -1,113 +1,106 @@
//
using System;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
namespace TimeZoneInfoCode
{
- public class TimeOffsets
- {
- public static void Main()
- {
- TimeOffsets timeoff = new TimeOffsets();
- TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
-
- timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Local);
- timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Local);
- timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), TimeZoneInfo.Local);
- timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Local);
- timeoff.ShowOffset(DateTime.UtcNow, TimeZoneInfo.Local);
- timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Utc);
- timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Utc);
- timeoff.ShowOffset(new DateTime(2006, 12, 10, 3, 0, 0), TimeZoneInfo.Utc);
- timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Utc);
- timeoff.ShowOffset(DateTime.Now, TimeZoneInfo.Utc);
- timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), cst);
- timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), cst);
- timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), cst);
- timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0, 0), cst);
- timeoff.ShowOffset(new DateTime(2007, 11, 14, 00, 00, 00, DateTimeKind.Local), cst);
- }
-
- private void ShowOffset(DateTime time, TimeZoneInfo timeZone)
- {
- DateTime convertedTime = time;
- TimeSpan offset;
-
- if (time.Kind == DateTimeKind.Local && ! timeZone.Equals(TimeZoneInfo.Local))
- convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Local, timeZone);
- else if (time.Kind == DateTimeKind.Utc && ! timeZone.Equals(TimeZoneInfo.Utc))
- convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, timeZone);
-
- offset = timeZone.GetUtcOffset(time);
- if (time == convertedTime)
- {
- Console.WriteLine("{0} {1} ", time,
- timeZone.IsDaylightSavingTime(time) ? timeZone.DaylightName : timeZone.StandardName);
- Console.WriteLine(" It differs from UTC by {0} hours, {1} minutes.",
- offset.Hours,
- offset.Minutes);
- }
- else
- {
- Console.WriteLine("{0} {1} ", time,
- time.Kind == DateTimeKind.Utc ? "UTC" : TimeZoneInfo.Local.Id);
- Console.WriteLine(" converts to {0} {1}.",
- convertedTime,
- timeZone.Id);
- Console.WriteLine(" It differs from UTC by {0} hours, {1} minutes.",
- offset.Hours, offset.Minutes);
- }
- Console.WriteLine();
- }
- }
+ public class TimeOffsets
+ {
+ public static void Main()
+ {
+ TimeOffsets timeoff = new();
+ TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
+
+ timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Local);
+ timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Local);
+ timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), TimeZoneInfo.Local);
+ timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Local);
+ timeoff.ShowOffset(DateTime.UtcNow, TimeZoneInfo.Local);
+ timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), TimeZoneInfo.Utc);
+ timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), TimeZoneInfo.Utc);
+ timeoff.ShowOffset(new DateTime(2006, 12, 10, 3, 0, 0), TimeZoneInfo.Utc);
+ timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0), TimeZoneInfo.Utc);
+ timeoff.ShowOffset(DateTime.Now, TimeZoneInfo.Utc);
+ timeoff.ShowOffset(new DateTime(2006, 6, 12, 11, 0, 0), cst);
+ timeoff.ShowOffset(new DateTime(2007, 11, 4, 1, 0, 0), cst);
+ timeoff.ShowOffset(new DateTime(2006, 12, 10, 15, 0, 0), cst);
+ timeoff.ShowOffset(new DateTime(2007, 3, 11, 2, 30, 0, 0), cst);
+ timeoff.ShowOffset(new DateTime(2007, 11, 14, 00, 00, 00, DateTimeKind.Local), cst);
+ }
+
+ private void ShowOffset(DateTime time, TimeZoneInfo timeZone)
+ {
+ DateTime convertedTime = time;
+ TimeSpan offset;
+
+ if (time.Kind == DateTimeKind.Local && !timeZone.Equals(TimeZoneInfo.Local))
+ convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Local, timeZone);
+ else if (time.Kind == DateTimeKind.Utc && !timeZone.Equals(TimeZoneInfo.Utc))
+ convertedTime = TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, timeZone);
+
+ offset = timeZone.GetUtcOffset(time);
+ if (time == convertedTime)
+ {
+ Console.WriteLine($"{time} {(timeZone.IsDaylightSavingTime(time) ? timeZone.DaylightName : timeZone.StandardName)} ");
+ Console.WriteLine($" It differs from UTC by {offset.Hours} hours, {offset.Minutes} minutes.");
+ }
+ else
+ {
+ Console.WriteLine($"{time} {(time.Kind == DateTimeKind.Utc ? "UTC" : TimeZoneInfo.Local.Id)} ");
+ Console.WriteLine($" converts to {convertedTime} {timeZone.Id}.");
+ Console.WriteLine($" It differs from UTC by {offset.Hours} hours, {offset.Minutes} minutes.");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example produces the following output:
//
-// 6/12/2006 11:00:00 AM Pacific Daylight Time
+// 6/12/2006 11:00:00 AM Pacific Daylight Time
// It differs from UTC by -7 hours, 0 minutes.
-//
-// 11/4/2007 1:00:00 AM Pacific Standard Time
+//
+// 11/4/2007 1:00:00 AM Pacific Standard Time
// It differs from UTC by -8 hours, 0 minutes.
-//
-// 12/10/2006 3:00:00 PM Pacific Standard Time
+//
+// 12/10/2006 3:00:00 PM Pacific Standard Time
// It differs from UTC by -8 hours, 0 minutes.
-//
-// 3/11/2007 2:30:00 AM Pacific Standard Time
+//
+// 3/11/2007 2:30:00 AM Pacific Standard Time
// It differs from UTC by -8 hours, 0 minutes.
-//
-// 2/2/2007 8:35:46 PM UTC
+//
+// 2/2/2007 8:35:46 PM UTC
// converts to 2/2/2007 12:35:46 PM Pacific Standard Time.
// It differs from UTC by -8 hours, 0 minutes.
-//
-// 6/12/2006 11:00:00 AM UTC
+//
+// 6/12/2006 11:00:00 AM UTC
// It differs from UTC by 0 hours, 0 minutes.
-//
-// 11/4/2007 1:00:00 AM UTC
+//
+// 11/4/2007 1:00:00 AM UTC
// It differs from UTC by 0 hours, 0 minutes.
-//
-// 12/10/2006 3:00:00 AM UTC
+//
+// 12/10/2006 3:00:00 AM UTC
// It differs from UTC by 0 hours, 0 minutes.
-//
-// 3/11/2007 2:30:00 AM UTC
+//
+// 3/11/2007 2:30:00 AM UTC
// It differs from UTC by 0 hours, 0 minutes.
-//
-// 2/2/2007 12:35:46 PM Pacific Standard Time
+//
+// 2/2/2007 12:35:46 PM Pacific Standard Time
// converts to 2/2/2007 8:35:46 PM UTC.
// It differs from UTC by 0 hours, 0 minutes.
-//
-// 6/12/2006 11:00:00 AM Central Daylight Time
+//
+// 6/12/2006 11:00:00 AM Central Daylight Time
// It differs from UTC by -5 hours, 0 minutes.
-//
-// 11/4/2007 1:00:00 AM Central Standard Time
+//
+// 11/4/2007 1:00:00 AM Central Standard Time
// It differs from UTC by -6 hours, 0 minutes.
-//
-// 12/10/2006 3:00:00 PM Central Standard Time
+//
+// 12/10/2006 3:00:00 PM Central Standard Time
// It differs from UTC by -6 hours, 0 minutes.
-//
-// 3/11/2007 2:30:00 AM Central Standard Time
+//
+// 3/11/2007 2:30:00 AM Central Standard Time
// It differs from UTC by -6 hours, 0 minutes.
-//
-// 11/14/2007 12:00:00 AM Pacific Standard Time
+//
+// 11/14/2007 12:00:00 AM Pacific Standard Time
// converts to 11/14/2007 2:00:00 AM Central Standard Time.
// It differs from UTC by -6 hours, 0 minutes.
//
diff --git a/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs b/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs
index 7cd2afbac76..cbc1b654be9 100644
--- a/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs
+++ b/snippets/csharp/System/TimeZoneInfo/HasSameRules/HasSameRules.cs
@@ -1,37 +1,35 @@
using System;
using System.Collections.ObjectModel;
-[assembly:CLSCompliant(true)]
+[assembly: CLSCompliant(true)]
namespace TimeZoneInfoCode
{
-public sealed class TestSameRules
-{
- private TestSameRules() {}
+ public sealed class TestSameRules
+ {
+ private TestSameRules() { }
- public static void Main()
- {
- //
- ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
- TimeZoneInfo[] timeZoneArray = new TimeZoneInfo[timeZones.Count];
- timeZones.CopyTo(timeZoneArray, 0);
- // Iterate array from top to bottom
- for (int ctr = timeZoneArray.GetUpperBound(0); ctr >= 1; ctr--)
- {
- // Get next item from top
- TimeZoneInfo thisTimeZone = timeZoneArray[ctr];
- for (int compareCtr = 0; compareCtr <= ctr - 1; compareCtr++)
- {
- // Determine if time zones have the same rules
- if (thisTimeZone.HasSameRules(timeZoneArray[compareCtr]))
+ public static void Main()
+ {
+ //
+ ReadOnlyCollection timeZones = TimeZoneInfo.GetSystemTimeZones();
+ TimeZoneInfo[] timeZoneArray = new TimeZoneInfo[timeZones.Count];
+ timeZones.CopyTo(timeZoneArray, 0);
+ // Iterate array from top to bottom
+ for (int ctr = timeZoneArray.GetUpperBound(0); ctr >= 1; ctr--)
{
- Console.WriteLine("{0} has the same rules as {1}",
- thisTimeZone.StandardName,
- timeZoneArray[compareCtr].StandardName);
+ // Get next item from top
+ TimeZoneInfo thisTimeZone = timeZoneArray[ctr];
+ for (int compareCtr = 0; compareCtr <= ctr - 1; compareCtr++)
+ {
+ // Determine if time zones have the same rules
+ if (thisTimeZone.HasSameRules(timeZoneArray[compareCtr]))
+ {
+ Console.WriteLine($"{thisTimeZone.StandardName} has the same rules as {timeZoneArray[compareCtr].StandardName}");
+ }
+ }
}
- }
- }
- //
- }
-}
+ //
+ }
+ }
} // End namespace
diff --git a/snippets/csharp/System/TimeoutException/Overview/Project.csproj b/snippets/csharp/System/TimeoutException/Overview/Project.csproj
new file mode 100644
index 00000000000..32e3c55e48b
--- /dev/null
+++ b/snippets/csharp/System/TimeoutException/Overview/Project.csproj
@@ -0,0 +1,9 @@
+
+
+ Exe
+ net10.0
+
+
+
+
+
diff --git a/snippets/csharp/System/TimeoutException/Overview/to.cs b/snippets/csharp/System/TimeoutException/Overview/to.cs
index 0043143a9cf..474629ad3db 100644
--- a/snippets/csharp/System/TimeoutException/Overview/to.cs
+++ b/snippets/csharp/System/TimeoutException/Overview/to.cs
@@ -9,31 +9,31 @@ class Sample
{
public static void Main()
{
- string input;
- try
+ string input;
+ try
{
-// Set the COM1 serial port to speed = 4800 baud, parity = odd,
-// data bits = 8, stop bits = 1.
- SerialPort sp = new SerialPort("COM1",
- 4800, Parity.Odd, 8, StopBits.One);
-// Timeout after 2 seconds.
- sp.ReadTimeout = 2000;
- sp.Open();
-
-// Read until either the default newline termination string
-// is detected or the read operation times out.
- input = sp.ReadLine();
-
- sp.Close();
-
-// Echo the input.
- Console.WriteLine(input);
+ // Set the COM1 serial port to speed = 4800 baud, parity = odd,
+ // data bits = 8, stop bits = 1.
+ SerialPort sp = new SerialPort("COM1",
+ 4800, Parity.Odd, 8, StopBits.One);
+ // Timeout after 2 seconds.
+ sp.ReadTimeout = 2000;
+ sp.Open();
+
+ // Read until either the default newline termination string
+ // is detected or the read operation times out.
+ input = sp.ReadLine();
+
+ sp.Close();
+
+ // Echo the input.
+ Console.WriteLine(input);
}
-// Only catch timeout exceptions.
- catch (TimeoutException e)
+ // Only catch timeout exceptions.
+ catch (TimeoutException e)
{
- Console.WriteLine(e);
+ Console.WriteLine(e);
}
}
}
@@ -51,4 +51,4 @@ at System.IO.Ports.SerialPort.ReadTo(String value)
at System.IO.Ports.SerialPort.ReadLine()
at Sample.Main()
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Tuple/Overview/Program.cs b/snippets/csharp/System/Tuple/Overview/Program.cs
new file mode 100644
index 00000000000..c56a5555343
--- /dev/null
+++ b/snippets/csharp/System/Tuple/Overview/Program.cs
@@ -0,0 +1,5 @@
+TupleCreateC.Create1.Run(args);
+CreateNTupleExample.Run();
+Constructor8Example.Run();
+TupleOverviewExample.Run(args);
+TupleOverviewExample1.Run();
diff --git a/snippets/csharp/System/Tuple/Overview/Project.csproj b/snippets/csharp/System/Tuple/Overview/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/Tuple/Overview/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/Tuple/Overview/create1.cs b/snippets/csharp/System/Tuple/Overview/create1.cs
index 1de4ab7ccbf..66ea3a5d0ba 100644
--- a/snippets/csharp/System/Tuple/Overview/create1.cs
+++ b/snippets/csharp/System/Tuple/Overview/create1.cs
@@ -4,7 +4,7 @@ namespace TupleCreateC
{
class Create1
{
- static void Main(string[] args)
+ public static void Run(string[] args)
{
Create1Tuple();
New1Tuple();
@@ -47,7 +47,7 @@ private static void Create2Tuple()
{
//
var tuple2 = Tuple.Create("New York", 32.68);
- Console.WriteLine("{0}: {1}", tuple2.Item1, tuple2.Item2);
+ Console.WriteLine($"{tuple2.Item1}: {tuple2.Item2}");
// Displays New York: 32.68
//
}
@@ -56,7 +56,7 @@ private static void New2Tuple()
{
//
var tuple2 = new Tuple("New York", 32.68);
- Console.WriteLine("{0}: {1}", tuple2.Item1, tuple2.Item2);
+ Console.WriteLine($"{tuple2.Item1}: {tuple2.Item2}");
// Displays New York: 32.68
//
}
@@ -65,8 +65,7 @@ private static void Create3Tuple()
{
//
var tuple3 = Tuple.Create("New York", 32.68, 51.87);
- Console.WriteLine("{0}: lo {1}, hi {2}",
- tuple3.Item1, tuple3.Item2, tuple3.Item3);
+ Console.WriteLine($"{tuple3.Item1}: lo {tuple3.Item2}, hi {tuple3.Item3}");
// Displays New York: lo 32.68, hi 51.87
//
}
@@ -76,8 +75,7 @@ private static void New3Tuple()
//
var tuple3 = new Tuple
("New York", 32.68, 51.87);
- Console.WriteLine("{0}: lo {1}, hi {2}",
- tuple3.Item1, tuple3.Item2, tuple3.Item3);
+ Console.WriteLine($"{tuple3.Item1}: lo {tuple3.Item2}, hi {tuple3.Item3}");
// Displays New York: lo 32.68, hi 51.87
//
}
@@ -86,9 +84,7 @@ private static void Create4Tuple()
{
//
var tuple4 = Tuple.Create("New York", 32.68, 51.87, 76.3);
- Console.WriteLine("{0}: Hi {1}, Lo {2}, Ave {3}",
- tuple4.Item1, tuple4.Item4, tuple4.Item2,
- tuple4.Item3);
+ Console.WriteLine($"{tuple4.Item1}: Hi {tuple4.Item4}, Lo {tuple4.Item2}, Ave {tuple4.Item3}");
// Displays New York: Hi 76.3, Lo 32.68, Ave 51.87
//
}
@@ -98,9 +94,7 @@ private static void New4Tuple()
//
var tuple4 = new Tuple
("New York", 32.68, 51.87, 76.3);
- Console.WriteLine("{0}: Hi {1}, Lo {2}, Ave {3}",
- tuple4.Item1, tuple4.Item4, tuple4.Item2,
- tuple4.Item3);
+ Console.WriteLine($"{tuple4.Item1}: Hi {tuple4.Item4}, Lo {tuple4.Item2}, Ave {tuple4.Item3}");
// Displays New York: Hi 76.3, Lo 32.68, Ave 51.87
//
}
@@ -109,9 +103,7 @@ private static void Create5Tuple()
{
//
var tuple5 = Tuple.Create("New York", 1990, 7322564, 2000, 8008278);
- Console.WriteLine("{0}: {1:N0} in {2}, {3:N0} in {4}",
- tuple5.Item1, tuple5.Item3, tuple5.Item2,
- tuple5.Item5, tuple5.Item4);
+ Console.WriteLine($"{tuple5.Item1}: {tuple5.Item3:N0} in {tuple5.Item2}, {tuple5.Item5:N0} in {tuple5.Item4}");
// Displays New York: 7,322,564 in 1990, 8,008,278 in 2000
//
}
@@ -121,9 +113,7 @@ private static void New5Tuple()
//
var tuple5 = new Tuple
("New York", 1990, 7322564, 2000, 8008278);
- Console.WriteLine("{0}: {1:N0} in {2}, {3:N0} in {4}",
- tuple5.Item1, tuple5.Item3, tuple5.Item2,
- tuple5.Item5, tuple5.Item4);
+ Console.WriteLine($"{tuple5.Item1}: {tuple5.Item3:N0} in {tuple5.Item2}, {tuple5.Item5:N0} in {tuple5.Item4}");
// Displays New York: 7,322,564 in 1990, 8,008,278 in 2000
//
}
@@ -132,9 +122,7 @@ private static void Create6Tuple()
{
//
var tuple6 = Tuple.Create("Jane", 90, 87, 93, 67, 100);
- Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}",
- tuple6.Item1, tuple6.Item2, tuple6.Item3,
- tuple6.Item4, tuple6.Item5, tuple6.Item6);
+ Console.WriteLine($"Test scores for {tuple6.Item1}: {tuple6.Item2}, {tuple6.Item3}, {tuple6.Item4}, {tuple6.Item5}, {tuple6.Item6}");
// Displays Test scores for Jane: 90, 87, 93, 67, 100
//
}
@@ -144,9 +132,7 @@ private static void New6Tuple()
//
var tuple6 = new Tuple
("Jane", 90, 87, 93, 67, 100);
- Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}",
- tuple6.Item1, tuple6.Item2, tuple6.Item3,
- tuple6.Item4, tuple6.Item5, tuple6.Item6);
+ Console.WriteLine($"Test scores for {tuple6.Item1}: {tuple6.Item2}, {tuple6.Item3}, {tuple6.Item4}, {tuple6.Item5}, {tuple6.Item6}");
// Displays Test scores for Jane: 90, 87, 93, 67, 100
//
}
@@ -155,10 +141,7 @@ private static void Create7Tuple()
{
//
var tuple7 = Tuple.Create("Jane", 90, 87, 93, 67, 100, 92);
- Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}, {6}",
- tuple7.Item1, tuple7.Item2, tuple7.Item3,
- tuple7.Item4, tuple7.Item5, tuple7.Item6,
- tuple7.Item7);
+ Console.WriteLine($"Test scores for {tuple7.Item1}: {tuple7.Item2}, {tuple7.Item3}, {tuple7.Item4}, {tuple7.Item5}, {tuple7.Item6}, {tuple7.Item7}");
// Displays Test scores for Jane: 90, 87, 93, 67, 100, 92
//
}
@@ -168,44 +151,41 @@ private static void New7Tuple()
//
var tuple7 = new Tuple
("Jane", 90, 87, 93, 67, 100, 92);
- Console.WriteLine("Test scores for {0}: {1}, {2}, {3}, {4}, {5}, {6}",
- tuple7.Item1, tuple7.Item2, tuple7.Item3,
- tuple7.Item4, tuple7.Item5, tuple7.Item6,
- tuple7.Item7);
+ Console.WriteLine($"Test scores for {tuple7.Item1}: {tuple7.Item2}, {tuple7.Item3}, {tuple7.Item4}, {tuple7.Item5}, {tuple7.Item6}, {tuple7.Item7}");
// Displays Test scores for Jane: 90, 87, 93, 67, 100, 92
//
}
private static void CreateNTuple()
{
-// Tuple innerTuple =
-// Tuple.Create(1960, 1670140, 1980, 1203339, 2000, 951270);
-// Tuple> tuple8 =
-// Tuple.Create("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple);
+ // Tuple innerTuple =
+ // Tuple.Create(1960, 1670140, 1980, 1203339, 2000, 951270);
+ // Tuple> tuple8 =
+ // Tuple.Create("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple);
}
private static void NewNTuple()
{
//
- var innerTuple = new Tuple
- (1960, 1670140, 1980, 1203339,
+ var innerTuple = new Tuple
+ (1960, 1670140, 1980, 1203339,
2000, 951270);
var tuple8 =
new Tuple>
("Detroit", 1900, 285704, 1920, 993078, 1940, 1623452, innerTuple);
Console.WriteLine("Population of {0} in:\n {1}: {2,10:N0} \n" +
- " {3}: {4,10:N0} \n" +
- " {5}: {6,10:N0} \n" +
- " {7}: {8,10:N0} \n" +
- " {9}: {10,10:N0} \n" +
+ " {3}: {4,10:N0} \n" +
+ " {5}: {6,10:N0} \n" +
+ " {7}: {8,10:N0} \n" +
+ " {9}: {10,10:N0} \n" +
" {11}: {12,10:N0} \n",
tuple8.Item1, tuple8.Item2, tuple8.Item3,
tuple8.Item4, tuple8.Item5, tuple8.Item6,
tuple8.Item7, tuple8.Rest.Item1, tuple8.Rest.Item2,
tuple8.Rest.Item3, tuple8.Rest.Item4,
- tuple8.Rest.Item5, tuple8.Rest.Item6);
+ tuple8.Rest.Item5, tuple8.Rest.Item6);
// The example displays the following output:
// Population of Detroit in:
// 1900: 285,704
@@ -213,18 +193,18 @@ private static void NewNTuple()
// 1940: 1,623,452
// 1960: 1,670,140
// 1980: 1,203,339
- // 2000: 951,270
+ // 2000: 951,270
//
}
private static void Example()
{
- var from1980 = Tuple.Create(1203339, 1027974, 951270);
- var from1910 = new Tuple>
- (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
- var population = new Tuple>>
- ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
+ var from1980 = Tuple.Create(1203339, 1027974, 951270);
+ var from1910 = new Tuple>
+ (465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
+ var population = new Tuple>>
+ ("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
}
}
}
diff --git a/snippets/csharp/System/Tuple/Overview/createntuple.cs b/snippets/csharp/System/Tuple/Overview/createntuple.cs
index a254a670b99..e3229d8fc79 100644
--- a/snippets/csharp/System/Tuple/Overview/createntuple.cs
+++ b/snippets/csharp/System/Tuple/Overview/createntuple.cs
@@ -1,19 +1,19 @@
using System;
-public class Example
+public class CreateNTupleExample
{
- public static void Main()
- {
- //
- var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19);
- Console.WriteLine("Prime numbers less than 20: " +
- "{0}, {1}, {2}, {3}, {4}, {5}, {6}, and {7}",
- primes.Item1, primes.Item2, primes.Item3,
- primes.Item4, primes.Item5, primes.Item6,
- primes.Item7, primes.Rest.Item1);
- // The example displays the following output:
- // Prime numbers less than 20: 2, 3, 5, 7, 11, 13, 17, and 19
- //
- Console.WriteLine(primes.ToString());
- }
+ public static void Run()
+ {
+ //
+ var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19);
+ Console.WriteLine("Prime numbers less than 20: " +
+ "{0}, {1}, {2}, {3}, {4}, {5}, {6}, and {7}",
+ primes.Item1, primes.Item2, primes.Item3,
+ primes.Item4, primes.Item5, primes.Item6,
+ primes.Item7, primes.Rest.Item1);
+ // The example displays the following output:
+ // Prime numbers less than 20: 2, 3, 5, 7, 11, 13, 17, and 19
+ //
+ Console.WriteLine(primes);
+ }
}
diff --git a/snippets/csharp/System/Tuple/Overview/ctor8.cs b/snippets/csharp/System/Tuple/Overview/ctor8.cs
index d1b551e9334..2ca778424f6 100644
--- a/snippets/csharp/System/Tuple/Overview/ctor8.cs
+++ b/snippets/csharp/System/Tuple/Overview/ctor8.cs
@@ -1,14 +1,14 @@
using System;
-public class Example
+public class Constructor8Example
{
- public static void Main()
- {
- //
- var primes = new Tuple>(2, 3, 5, 7, 11, 13, 16,
- new Tuple(19));
- //
- Console.WriteLine(primes.ToString());
- }
+ public static void Run()
+ {
+ //
+ var primes = new Tuple>(2, 3, 5, 7, 11, 13, 16,
+ new Tuple(19));
+ //
+ Console.WriteLine(primes);
+ }
}
diff --git a/snippets/csharp/System/Tuple/Overview/example.cs b/snippets/csharp/System/Tuple/Overview/example.cs
index 78752e41f58..5677e08b60d 100644
--- a/snippets/csharp/System/Tuple/Overview/example.cs
+++ b/snippets/csharp/System/Tuple/Overview/example.cs
@@ -1,20 +1,20 @@
using System;
-class Example
+class TupleOverviewExample
{
- static void Main(string[] args)
+ public static void Run(string[] args)
{
//
var from1980 = Tuple.Create(1203339, 1027974, 951270);
- var from1910 = new Tuple>
+ var from1910 = new Tuple>
(465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
var population = new Tuple>>
+ Tuple>>
("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
//
- Console.WriteLine("Population of {0}", population.Item1);
+ Console.WriteLine($"Population of {population.Item1}");
Console.WriteLine();
- Console.WriteLine("{0,5} {1,14} {2,10}", "Year", "Population", "Change");
+ Console.WriteLine($"{"Year",5} {"Population",14} {"Change",10}");
int year = population.Item2;
ShowPopulation(year, population.Item3);
@@ -48,16 +48,9 @@ static void Main(string[] args)
ShowPopulationChange(year, population.Rest.Rest.Item3, population.Rest.Rest.Item2);
}
- private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation,
- ((double)(newPopulation - oldPopulation) / oldPopulation) / 10);
- }
+ private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}");
- private static void ShowPopulation(int year, int newPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a");
- }
+ private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}");
}
// The example displays the following output:
//
diff --git a/snippets/csharp/System/Tuple/Overview/example1.cs b/snippets/csharp/System/Tuple/Overview/example1.cs
index dd02f8bc30a..af468923e9a 100644
--- a/snippets/csharp/System/Tuple/Overview/example1.cs
+++ b/snippets/csharp/System/Tuple/Overview/example1.cs
@@ -1,38 +1,36 @@
using System;
-public class Example
+public class TupleOverviewExample1
{
- public static void Main()
- {
- Ctor1();
- Factory();
- }
+ public static void Run()
+ {
+ Ctor1();
+ Factory();
+ }
- private static void Ctor1()
- {
- //
- // Create a 7-tuple.
- var population = new Tuple(
- "New York", 7891957, 7781984,
- 7894862, 7071639, 7322564, 8008278);
- // Display the first and last elements.
- Console.WriteLine("Population of {0} in 2000: {1:N0}",
- population.Item1, population.Item7);
- // The example displays the following output:
- // Population of New York in 2000: 8,008,278
- //
- }
+ private static void Ctor1()
+ {
+ //
+ // Create a 7-tuple.
+ var population = new Tuple(
+ "New York", 7891957, 7781984,
+ 7894862, 7071639, 7322564, 8008278);
+ // Display the first and last elements.
+ Console.WriteLine($"Population of {population.Item1} in 2000: {population.Item7:N0}");
+ // The example displays the following output:
+ // Population of New York in 2000: 8,008,278
+ //
+ }
- private static void Factory()
- {
- //
- // Create a 7-tuple.
- var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);
- // Display the first and last elements.
- Console.WriteLine("Population of {0} in 2000: {1:N0}",
- population.Item1, population.Item7);
- // The example displays the following output:
- // Population of New York in 2000: 8,008,278
- //
- }
+ private static void Factory()
+ {
+ //
+ // Create a 7-tuple.
+ var population = Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278);
+ // Display the first and last elements.
+ Console.WriteLine($"Population of {population.Item1} in 2000: {population.Item7:N0}");
+ // The example displays the following output:
+ // Population of New York in 2000: 8,008,278
+ //
+ }
}
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs
index 4f900260888..09af1b8e0ef 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Equals/equals1.cs
@@ -3,33 +3,33 @@
public class Class1
{
- public static void Main()
- {
- // Create five 8-tuple objects containing prime numbers.
- var prime1 = new Tuple> (2, 3, 5, 7, 11, 13, 17,
- new Tuple(19));
- var prime2 = new Tuple> (23, 29, 31, 37, 41, 43, 47,
- new Tuple(55));
- var prime3 = new Tuple> (3, 2, 5, 7, 11, 13, 17,
- new Tuple(19));
- var prime4 = new Tuple> (2, 3, 5, 7, 11, 13, 17,
- new Tuple(19, 23));
- var prime5 = new Tuple> (2, 3, 5, 7, 11, 13, 17,
- new Tuple(19));
- Console.WriteLine("{0} = {1} : {2}", prime1, prime2, prime1.Equals(prime2));
- Console.WriteLine("{0} = {1} : {2}", prime1, prime3, prime1.Equals(prime3));
- Console.WriteLine("{0} = {1} : {2}", prime1, prime4, prime1.Equals(prime4));
- Console.WriteLine("{0} = {1} : {2}", prime1, prime5, prime1.Equals(prime5));
- }
+ public static void Main()
+ {
+ // Create five 8-tuple objects containing prime numbers.
+ var prime1 = new Tuple>(2, 3, 5, 7, 11, 13, 17,
+ new Tuple(19));
+ var prime2 = new Tuple>(23, 29, 31, 37, 41, 43, 47,
+ new Tuple(55));
+ var prime3 = new Tuple>(3, 2, 5, 7, 11, 13, 17,
+ new Tuple(19));
+ var prime4 = new Tuple>(2, 3, 5, 7, 11, 13, 17,
+ new Tuple(19, 23));
+ var prime5 = new Tuple>(2, 3, 5, 7, 11, 13, 17,
+ new Tuple(19));
+ Console.WriteLine($"{prime1} = {prime2} : {prime1.Equals(prime2)}");
+ Console.WriteLine($"{prime1} = {prime3} : {prime1.Equals(prime3)}");
+ Console.WriteLine($"{prime1} = {prime4} : {prime1.Equals(prime4)}");
+ Console.WriteLine($"{prime1} = {prime5} : {prime1.Equals(prime5)}");
+ }
}
// The example displays the following output:
// (2, 3, 5, 7, 11, 13, 17, 19) = (23, 29, 31, 37, 41, 43, 47, 55) : False
// (2, 3, 5, 7, 11, 13, 17, 19) = (3, 2, 5, 7, 11, 13, 17, 19) : False
// (2, 3, 5, 7, 11, 13, 17, 19) = (2, 3, 5, 7, 11, 13, 17, 19, 23) : False
// (2, 3, 5, 7, 11, 13, 17, 19) = (2, 3, 5, 7, 11, 13, 17, 19) : True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs
index 7c709f3213f..7828b98e0e5 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Item1/item1.cs
@@ -6,15 +6,15 @@ class Example
static void Main(string[] args)
{
Tuple from1980 = Tuple.Create(1203339, 1027974, 951270);
- var from1910 = new Tuple>
+ var from1910 = new Tuple>
(465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
var population = new Tuple>>
+ Tuple>>
("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
- Console.WriteLine("Population of {0}", population.Item1);
+ Console.WriteLine($"Population of {population.Item1}");
Console.WriteLine();
- Console.WriteLine("{0,5} {1,14} {2,10}", "Year", "Population", "Change");
+ Console.WriteLine($"{"Year",5} {"Population",14} {"Change",10}");
int year = population.Item2;
ShowPopulation(year, population.Item3);
@@ -48,16 +48,9 @@ static void Main(string[] args)
ShowPopulationChange(year, population.Rest.Rest.Item3, population.Rest.Rest.Item2);
}
- private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation,
- ((double)(newPopulation - oldPopulation) / oldPopulation) / 10);
- }
+ private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}");
- private static void ShowPopulation(int year, int newPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a");
- }
+ private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}");
}
// The example displays the following output:
//
@@ -78,4 +71,4 @@ private static void ShowPopulation(int year, int newPopulation)
// 1980 1,203,339 -2.04 %
// 1990 1,027,974 -1.46 %
// 2000 951,270 -0.75 %
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs
index e4f1950590e..6e28f8e8778 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/Overview/octuple1.cs
@@ -2,12 +2,12 @@
public class Class1
{
- public static void Main()
- {
- //
- var primes = new Tuple> (2, 3, 5, 7, 11, 13, 17, new Tuple(19));
- //
- Console.WriteLine(primes.ToString());
- }
+ public static void Main()
+ {
+ //
+ var primes = new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19));
+ //
+ Console.WriteLine(primes);
+ }
}
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index d4caf4d74e8..980c072d1e5 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,35 +1,35 @@
//
using System;
-public class Example
+public class CompareToExample1
{
- public static void Main()
- {
- // Create array of 8-tuple objects containing prime numbers.
- Tuple>[] primes =
- { new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19)),
- new Tuple>(23, 29, 31, 37, 41, 43, 47, new Tuple(55)),
- new Tuple>(3, 2, 5, 7, 11, 13, 17, new Tuple(19)) };
- // Display 8-tuples in unsorted order.
- foreach (var prime in primes)
- Console.WriteLine(prime.ToString());
- Console.WriteLine();
-
- // Sort the array and display its 8-tuples.
- Array.Sort(primes);
- foreach (var prime in primes)
- Console.WriteLine(prime.ToString());
- }
+ public static void Run()
+ {
+ // Create array of 8-tuple objects containing prime numbers.
+ Tuple>[] primes =
+ [ new Tuple>(2, 3, 5, 7, 11, 13, 17, new Tuple(19)),
+ new Tuple>(23, 29, 31, 37, 41, 43, 47, new Tuple(55)),
+ new Tuple>(3, 2, 5, 7, 11, 13, 17, new Tuple(19)) ];
+ // Display 8-tuples in unsorted order.
+ foreach (var prime in primes)
+ Console.WriteLine(prime);
+ Console.WriteLine();
+
+ // Sort the array and display its 8-tuples.
+ Array.Sort(primes);
+ foreach (var prime in primes)
+ Console.WriteLine(prime);
+ }
}
// The example displays the following output:
// (2, 3, 5, 7, 11, 13, 17, 19)
// (23, 29, 31, 37, 41, 43, 47, 55)
// (3, 2, 5, 7, 11, 13, 17, 19)
-//
+//
// (2, 3, 5, 7, 11, 13, 17, 19)
// (3, 2, 5, 7, 11, 13, 17, 19)
// (23, 29, 31, 37, 41, 43, 47, 55)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index e9ff5e13cea..436587ab05c 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,85 +5,76 @@
public class PopulationComparer : IComparer
{
- private int itemPosition;
- private int multiplier = -1;
+ private int itemPosition;
+ private int multiplier = -1;
- public PopulationComparer(int component) : this(component, true)
- { }
+ public PopulationComparer(int component) : this(component, true)
+ { }
- public PopulationComparer(int component, bool descending)
- {
- if (!descending) multiplier = 1;
+ public PopulationComparer(int component, bool descending)
+ {
+ if (!descending) multiplier = 1;
- if (component <= 0 || component > 8)
- throw new ArgumentException("The component argument is out of range.");
+ if (component <= 0 || component > 8)
+ throw new ArgumentException("The component argument is out of range.");
- itemPosition = component;
- }
+ itemPosition = component;
+ }
- public int Compare(object x, object y)
- {
- Tuple> tX = x as Tuple>;
- if (tX == null)
- return 0;
+ public int Compare(object x, object y)
+ {
+ Tuple> tX = x as Tuple>;
+ if (tX == null)
+ return 0;
- Tuple> tY = y as Tuple>;
- switch (itemPosition)
- {
- case 1:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- case 2:
- return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier;
- case 3:
- return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier;
- case 4:
- return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier;
- case 5:
- return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier;
- case 6:
- return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier;
- case 7:
- return Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier;
- case 8:
- return Comparer.Default.Compare(tX.Rest.Item1, tY.Rest.Item1) * multiplier;
- default:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- }
- }
+ Tuple> tY = y as Tuple>;
+ return itemPosition switch
+ {
+ 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier,
+ 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier,
+ 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier,
+ 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier,
+ 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier,
+ 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier,
+ 7 => Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier,
+ 8 => Comparer.Default.Compare(tX.Rest.Item1, tY.Rest.Item1) * multiplier,
+ _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier
+ };
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- // Create array of octuples with population data for three U.S.
- // cities, 1940-2000.
- Tuple>[] cities =
- { Tuple.Create("Los Angeles", 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
- Tuple.Create("New York", 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("Chicago", 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016),
- Tuple.Create("Detroit", 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) };
- // Display array in unsorted order.
- Console.WriteLine("In unsorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
-
- Array.Sort(cities, new PopulationComparer(2));
-
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 1950:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
-
- Array.Sort(cities, new PopulationComparer(8));
-
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 2000:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- }
+ public static void Run()
+ {
+ // Create array of octuples with population data for three U.S.
+ // cities, 1940-2000.
+ Tuple>[] cities =
+ [ Tuple.Create("Los Angeles", 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
+ Tuple.Create("New York", 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
+ Tuple.Create("Chicago", 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016),
+ Tuple.Create("Detroit", 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270) ];
+ // Display array in unsorted order.
+ Console.WriteLine("In unsorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
+
+ Array.Sort(cities, new PopulationComparer(2));
+
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 1950:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
+
+ Array.Sort(cities, new PopulationComparer(8));
+
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 2000:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ }
}
// The example displays the following output:
// In unsorted order:
@@ -91,16 +82,16 @@ public static void Main()
// (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270)
-//
+//
// Sorted by population in 1950:
// (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270)
// (Los Angeles, 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
-//
+//
// Sorted by population in 2000:
// (New York, 7454995, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Los Angeles, 1504277, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
// (Chicago, 3396808, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Detroit, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs
index 00ba6e5cf63..d16e813e7ae 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7,TRest/ToString/tostring1.cs
@@ -6,27 +6,20 @@ class Example
static void Main(string[] args)
{
Tuple from1980 = Tuple.Create(1203339, 1027974, 951270);
- var from1910 = new Tuple>
+ var from1910 = new Tuple>
(465766, 993078, 1568622, 1623452, 1849568, 1670144, 1511462, from1980);
var population = new Tuple>>
+ Tuple>>
("Detroit", 1860, 45619, 79577, 116340, 205876, 285704, from1910);
Console.WriteLine(population.ToString());
}
- private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation,
- ((double)(newPopulation - oldPopulation) / oldPopulation) / 10);
- }
+ private static void ShowPopulationChange(int year, int newPopulation, int oldPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {((double)(newPopulation - oldPopulation) / oldPopulation) / 10,10:P2}");
- private static void ShowPopulation(int year, int newPopulation)
- {
- Console.WriteLine("{0,5} {1,14:N0} {2,10:P2}", year, newPopulation, "n/a");
- }
+ private static void ShowPopulation(int year, int newPopulation) => Console.WriteLine($"{year,5} {newPopulation,14:N0} {"n/a",10}");
}
// The example displays the following output:
-// (Detroit, 1860, 45619, 79577, 116340, 205876, 285704, 465766, 993078,
+// (Detroit, 1860, 45619, 79577, 116340, 205876, 285704, 465766, 993078,
// 1568622, 1623452, 1849568, 1670144, 1511462, 1203339, 1027974, 951270)
//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs
new file mode 100644
index 00000000000..76c3e934c0b
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Program.cs
@@ -0,0 +1,2 @@
+EqualsExample1.Run();
+EqualsExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs
index cf24490a8d4..183e82cfabb 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals1.cs
@@ -1,38 +1,37 @@
//
using System;
-public class Example
+public class EqualsExample1
{
- public static void Main()
- {
- // Get population data for New York City and Los Angeles, 1960-2000.
- Tuple[] urbanPopulations =
- { Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
+ public static void Run()
+ {
+ // Get population data for New York City and Los Angeles, 1960-2000.
+ Tuple[] urbanPopulations =
+ [ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
Tuple.Create("New York City", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) };
- // Compare each tuple with every other tuple for equality.
- for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++)
- {
- var urbanPopulation = urbanPopulations[ctr];
- Console.WriteLine(urbanPopulation.ToString() + " = ");
- for (int innerCtr = ctr +1; innerCtr <= urbanPopulations.Length - 1; innerCtr++)
- Console.WriteLine(" {0}: {1}", urbanPopulations[innerCtr],
- urbanPopulation.Equals(urbanPopulations[innerCtr]));
- Console.WriteLine();
- }
- }
+ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) ];
+ // Compare each tuple with every other tuple for equality.
+ for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++)
+ {
+ var urbanPopulation = urbanPopulations[ctr];
+ Console.WriteLine(urbanPopulation + " = ");
+ for (int innerCtr = ctr + 1; innerCtr <= urbanPopulations.Length - 1; innerCtr++)
+ Console.WriteLine($" {urbanPopulations[innerCtr]}: {urbanPopulation.Equals(urbanPopulations[innerCtr])}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) =
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820): False
// (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): True
-//
+//
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820) =
// (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False
-//
+//
// (New York City, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278) =
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs
index 9bacff3b868..64e4aa75c97 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Equals/equals2.cs
@@ -4,61 +4,58 @@
public class RateComparer : IEqualityComparer
{
- private int argument = 0;
+ private int argument = 0;
- public new bool Equals(object x, object y)
- {
- argument++;
- if (argument == 1) return true;
+ public new bool Equals(object x, object y)
+ {
+ argument++;
+ if (argument == 1) return true;
- double fx, fy;
- if (x is Double || x is Single)
- {
- fx = (double) x;
- fy = (double) y;
+ double fx, fy;
+ if (x is double || x is float)
+ {
+ fx = (double)x;
+ fy = (double)y;
return Math.Round(fx * 1000).Equals(Math.Round(fy * 1000));
- }
- else
- {
- return x.Equals(y);
- }
- }
+ }
+ else
+ {
+ return x.Equals(y);
+ }
+ }
- public int GetHashCode(object obj)
- {
- if (obj is Single || obj is Double)
- return Math.Round(((double) obj) * 1000).GetHashCode();
- else
- return obj.GetHashCode();
- }
+ public int GetHashCode(object obj)
+ {
+ if (obj is float || obj is double)
+ return Math.Round(((double)obj) * 1000).GetHashCode();
+ else
+ return obj.GetHashCode();
+ }
}
-public class Example
+public class EqualsExample2
{
- public static void Main()
- {
- var rate1 = Tuple.Create("New York", -.013934, .014505,
- -.1042733, .0354833, .093644, .0290792);
- var rate2 = Tuple.Create("Unknown City", -.013934, .014505,
- -.1042733, .0354833, .093644, .0290792);
- var rate3 = Tuple.Create("Unknown City", -.013934, .014505,
- -.1042733, .0354833, .093644, .029079);
- var rate4 = Tuple.Create("San Francisco", -.0451934, -.0332858,
- -.0512803, .0662544, .0728964, .0491912);
- IStructuralEquatable eq = rate1;
- // Compare first tuple with remaining two tuples.
- Console.WriteLine("{0} = ", rate1.ToString());
- Console.WriteLine(" {0} : {1}", rate2,
- eq.Equals(rate2, new RateComparer()));
- Console.WriteLine(" {0} : {1}", rate3,
- eq.Equals(rate3, new RateComparer()));
- Console.WriteLine(" {0} : {1}", rate4,
- eq.Equals(rate4, new RateComparer()));
- }
+ public static void Run()
+ {
+ var rate1 = Tuple.Create("New York", -.013934, .014505,
+ -.1042733, .0354833, .093644, .0290792);
+ var rate2 = Tuple.Create("Unknown City", -.013934, .014505,
+ -.1042733, .0354833, .093644, .0290792);
+ var rate3 = Tuple.Create("Unknown City", -.013934, .014505,
+ -.1042733, .0354833, .093644, .029079);
+ var rate4 = Tuple.Create("San Francisco", -.0451934, -.0332858,
+ -.0512803, .0662544, .0728964, .0491912);
+ IStructuralEquatable eq = rate1;
+ // Compare first tuple with remaining two tuples.
+ Console.WriteLine($"{rate1} = ");
+ Console.WriteLine($" {rate2} : {eq.Equals(rate2, new RateComparer())}");
+ Console.WriteLine($" {rate3} : {eq.Equals(rate3, new RateComparer())}");
+ Console.WriteLine($" {rate4} : {eq.Equals(rate4, new RateComparer())}");
+ }
}
// The example displays the following output:
// (New York, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) =
// (Unknown City, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) : True
// (Unknown City, -0.013934, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.029079) : True
// (San Francisco, -0.0451934, -0.0332858, -0.0512803, 0.0662544, 0.0728964, 0.0491912) : False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs
index e9ec3039ced..6e957c5fab3 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Item1/item1.cs
@@ -1,31 +1,27 @@
//
using System;
-using System.Text.RegularExpressions;
+
public class Class1
{
- public static void Main()
- {
- // Create tuples containing population data for New York, Chicago,
- // and Los Angeles, 1960-2000.
- Tuple[] cities =
- { Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
+ public static void Main()
+ {
+ // Create tuples containing population data for New York, Chicago,
+ // and Los Angeles, 1960-2000.
+ Tuple[] cities =
+ [ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
- Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) };
+ Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ];
- // Display tuple data in table.
- string header = "Population in";
- Console.WriteLine("{0,-12} {1,66}",
- "City", new String('-',(66-header.Length)/2) + header +
- new String('-', (66-header.Length)/2));
- Console.WriteLine("{0,24}{1,11}{2,11}{3,11}{4,11}{5,11}\n",
- "1950", "1960", "1970", "1980", "1990", "2000");
+ // Display tuple data in table.
+ string header = "Population in";
+ Console.WriteLine($"{"City",-12} {new string('-', (66 - header.Length) / 2) + header +
+ new string('-', (66 - header.Length) / 2),66}");
+ Console.WriteLine($"{"1950",24}{"1960",11}{"1970",11}{"1980",11}{"1990",11}{"2000",11}\n");
- foreach (var city in cities)
- Console.WriteLine("{0,-12} {1,11:N0}{2,11:N0}{3,11:N0}{4,11:N0}{5,11:N0}{6,11:N0}",
- city.Item1, city.Item2, city.Item3, city.Item4,
- city.Item5, city.Item6, city.Item7);
- }
+ foreach (var city in cities)
+ Console.WriteLine($"{city.Item1,-12} {city.Item2,11:N0}{city.Item3,11:N0}{city.Item4,11:N0}{city.Item5,11:N0}{city.Item6,11:N0}{city.Item7,11:N0}");
+ }
}
// The example displays the following output:
// City --------------------------Population in--------------------------
@@ -34,4 +30,4 @@ public static void Main()
// New York 7,891,957 7,781,984 7,894,862 7,071,639 7,322,564 8,008,278
// Los Angeles 1,970,358 2,479,015 2,816,061 2,966,850 3,485,398 3,694,820
// Chicago 3,620,962 3,550,904 3,366,957 3,005,072 2,783,726 2,896,016
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs
index 4e81449329c..9f206853fc2 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/Overview/example1.cs
@@ -3,41 +3,41 @@
public class Example
{
- public static void Main()
- {
- // Get population data for New York City, 1950-2000.
- var population = Tuple.Create("New York", 7891957, 7781984,
- 7894862, 7071639, 7322564, 8008278);
- var rate = ComputePopulationChange(population);
- // Display results.
- Console.WriteLine("Population Change, {0}, 1950-2000\n", population.Item1);
- Console.WriteLine("Year {0,10} {1,9}", "Population", "Annual Rate");
- Console.WriteLine("1950 {0,10:N0} {1,11}", population.Item2, "NA");
- Console.WriteLine("1960 {0,10:N0} {1,11:P2}", population.Item3, rate.Item2/10);
- Console.WriteLine("1970 {0,10:N0} {1,11:P2}", population.Item4, rate.Item3/10);
- Console.WriteLine("1980 {0,10:N0} {1,11:P2}", population.Item5, rate.Item4/10);
- Console.WriteLine("1990 {0,10:N0} {1,11:P2}", population.Item6, rate.Item5/10);
- Console.WriteLine("2000 {0,10:N0} {1,11:P2}", population.Item7, rate.Item6/10);
- Console.WriteLine("1950-2000 {0,10:N0} {1,11:P2}", "", rate.Item7/50);
- }
+ public static void Main()
+ {
+ // Get population data for New York City, 1950-2000.
+ var population = Tuple.Create("New York", 7891957, 7781984,
+ 7894862, 7071639, 7322564, 8008278);
+ var rate = ComputePopulationChange(population);
+ // Display results.
+ Console.WriteLine($"Population Change, {population.Item1}, 1950-2000\n");
+ Console.WriteLine($"Year {"Population",10} {"Annual Rate",9}");
+ Console.WriteLine($"1950 {population.Item2,10:N0} {"NA",11}");
+ Console.WriteLine($"1960 {population.Item3,10:N0} {rate.Item2 / 10,11:P2}");
+ Console.WriteLine($"1970 {population.Item4,10:N0} {rate.Item3 / 10,11:P2}");
+ Console.WriteLine($"1980 {population.Item5,10:N0} {rate.Item4 / 10,11:P2}");
+ Console.WriteLine($"1990 {population.Item6,10:N0} {rate.Item5 / 10,11:P2}");
+ Console.WriteLine($"2000 {population.Item7,10:N0} {rate.Item6 / 10,11:P2}");
+ Console.WriteLine($"1950-2000 {"",10:N0} {rate.Item7 / 50,11:P2}");
+ }
- private static Tuple
- ComputePopulationChange(
- Tuple data)
- {
- var rate = Tuple.Create(data.Item1,
- (double)(data.Item3 - data.Item2)/data.Item2,
- (double)(data.Item4 - data.Item3)/data.Item3,
- (double)(data.Item5 - data.Item4)/data.Item4,
- (double)(data.Item6 - data.Item5)/data.Item5,
- (double)(data.Item7 - data.Item6)/data.Item6,
- (double)(data.Item7 - data.Item2)/data.Item2 );
- return rate;
- }
+ private static Tuple
+ ComputePopulationChange(
+ Tuple data)
+ {
+ var rate = Tuple.Create(data.Item1,
+ (double)(data.Item3 - data.Item2) / data.Item2,
+ (double)(data.Item4 - data.Item3) / data.Item3,
+ (double)(data.Item5 - data.Item4) / data.Item4,
+ (double)(data.Item6 - data.Item5) / data.Item5,
+ (double)(data.Item7 - data.Item6) / data.Item6,
+ (double)(data.Item7 - data.Item2) / data.Item2);
+ return rate;
+ }
}
// The example displays the following output:
// Population Change, New York, 1950-2000
-//
+//
// Year Population Annual Rate
// 1950 7,891,957 NA
// 1960 7,781,984 -0.14 %
@@ -46,4 +46,4 @@ private static Tuple
// 1990 7,322,564 0.35 %
// 2000 8,008,278 0.94 %
// 1950-2000 0.03 %
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index 231499e88ac..c0fd73593c4 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,40 +1,40 @@
//
using System;
-public class Example
+public class CompareToExample1
{
- public static void Main()
- {
- // Create array of sextuple with population data for three U.S.
- // cities, 1950-2000.
- Tuple[] cities =
- { Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
- Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) };
-
- // Display array in unsorted order.
- Console.WriteLine("In unsorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
+ public static void Run()
+ {
+ // Create array of sextuple with population data for three U.S.
+ // cities, 1950-2000.
+ Tuple[] cities =
+ [ Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
+ Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
+ Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ];
- Console.WriteLine();
-
- Array.Sort(cities);
-
- // Display array in sorted order.
- Console.WriteLine("In sorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- }
+ // Display array in unsorted order.
+ Console.WriteLine("In unsorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+
+ Console.WriteLine();
+
+ Array.Sort(cities);
+
+ // Display array in sorted order.
+ Console.WriteLine("In sorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ }
}
// The example displays the following output:
// In unsorted order:
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
-//
+//
// In sorted order:
// (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index 3c9c896baf8..00dd33ca788 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,99 +5,91 @@
public class PopulationComparer : IComparer
{
- private int itemPosition;
- private int multiplier = -1;
+ private int itemPosition;
+ private int multiplier = -1;
- public PopulationComparer(int component) : this(component, true)
- { }
+ public PopulationComparer(int component) : this(component, true)
+ { }
- public PopulationComparer(int component, bool descending)
- {
- if (!descending) multiplier = 1;
+ public PopulationComparer(int component, bool descending)
+ {
+ if (!descending) multiplier = 1;
- if (component <= 0 || component > 7)
- throw new ArgumentException("The component argument is out of range.");
+ if (component <= 0 || component > 7)
+ throw new ArgumentException("The component argument is out of range.");
- itemPosition = component;
- }
+ itemPosition = component;
+ }
- public int Compare(object x, object y)
- {
- Tuple tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- Tuple tY = y as Tuple;
- switch (itemPosition)
- {
- case 1:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- case 2:
- return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier;
- case 3:
- return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier;
- case 4:
- return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier;
- case 5:
- return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier;
- case 6:
- return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier;
- case 7:
- return Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier;
- default:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- }
- }
- }
+ public int Compare(object x, object y)
+ {
+ Tuple tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ Tuple tY = y as Tuple;
+ return itemPosition switch
+ {
+ 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier,
+ 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier,
+ 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier,
+ 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier,
+ 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier,
+ 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier,
+ 7 => Comparer.Default.Compare(tX.Item7, tY.Item7) * multiplier,
+ _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier
+ };
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- // Create array of sextuple with population data for three U.S.
- // cities, 1960-2000.
- Tuple[] cities =
- { Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
+ public static void Run()
+ {
+ // Create array of sextuple with population data for three U.S.
+ // cities, 1960-2000.
+ Tuple[] cities =
+ [ Tuple.Create("Los Angeles", 1970358, 2479015, 2816061, 2966850, 3485398, 3694820),
Tuple.Create("New York", 7891957, 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) };
+ Tuple.Create("Chicago", 3620962, 3550904, 3366957, 3005072, 2783726, 2896016) ];
- // Display array in unsorted order.
- Console.WriteLine("In unsorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
+ // Display array in unsorted order.
+ Console.WriteLine("In unsorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
- Array.Sort(cities, new PopulationComparer(3));
+ Array.Sort(cities, new PopulationComparer(3));
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 1960:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 1960:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
- Array.Sort(cities, new PopulationComparer(6));
+ Array.Sort(cities, new PopulationComparer(6));
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 1990:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- }
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 1990:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ }
}
// The example displays the following output:
// In unsorted order:
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
-//
+//
// Sorted by population in 1960:
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3620962, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
-//
+//
// Sorted by population in 1990:
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Los Angeles, 1970358, 2479015, 2816061, 2966850, 3485398, 3694820)
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs
index 82c8f897b7e..6d5a9ad88cc 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6,T7/ToString/tostring1.cs
@@ -3,13 +3,13 @@
public class Example
{
- public static void Main()
- {
- // Get population data for New York City, 1960-2000.
- var population = Tuple.Create("New York", 7891957, 7781984,
- 7894862, 7071639, 7322564, 8008278);
- Console.WriteLine(population.ToString());
- }
+ public static void Main()
+ {
+ // Get population data for New York City, 1960-2000.
+ var population = Tuple.Create("New York", 7891957, 7781984,
+ 7894862, 7071639, 7322564, 8008278);
+ Console.WriteLine(population.ToString());
+ }
}
// The example displays the following output:
// (New York, 7891957, 7781984, 7894862, 7071639, 7322564, 8008278)
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs
new file mode 100644
index 00000000000..76c3e934c0b
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Program.cs
@@ -0,0 +1,2 @@
+EqualsExample1.Run();
+EqualsExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs
index 38c47c0953b..14b70dcd1f5 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals1.cs
@@ -1,38 +1,37 @@
//
using System;
-public class Example
+public class EqualsExample1
{
- public static void Main()
- {
- // Get population data for New York City and Los Angeles, 1960-2000.
- Tuple[] urbanPopulations =
- { Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
+ public static void Run()
+ {
+ // Get population data for New York City and Los Angeles, 1960-2000.
+ Tuple[] urbanPopulations =
+ [ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
Tuple.Create("New York City", 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278) };
- // Compare each tuple with every other tuple for equality.
- for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++)
- {
- var urbanPopulation = urbanPopulations[ctr];
- Console.WriteLine(urbanPopulation.ToString() + " = ");
- for (int innerCtr = ctr +1; innerCtr <= urbanPopulations.Length - 1; innerCtr++)
- Console.WriteLine(" {0}: {1}", urbanPopulations[innerCtr],
- urbanPopulation.Equals(urbanPopulations[innerCtr]));
- Console.WriteLine();
- }
- }
+ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278) ];
+ // Compare each tuple with every other tuple for equality.
+ for (int ctr = 0; ctr <= urbanPopulations.Length - 2; ctr++)
+ {
+ var urbanPopulation = urbanPopulations[ctr];
+ Console.WriteLine(urbanPopulation + " = ");
+ for (int innerCtr = ctr + 1; innerCtr <= urbanPopulations.Length - 1; innerCtr++)
+ Console.WriteLine($" {urbanPopulations[innerCtr]}: {urbanPopulation.Equals(urbanPopulations[innerCtr])}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278) =
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820): False
// (New York City, 7781984, 7894862, 7071639, 7322564, 8008278): False
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278): True
-//
+//
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820) =
// (New York City, 7781984, 7894862, 7071639, 7322564, 8008278): False
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278): False
-//
+//
// (New York City, 7781984, 7894862, 7071639, 7322564, 8008278) =
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs
index 1714585fed3..af2fec23ed5 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Equals/equals2.cs
@@ -4,61 +4,58 @@
public class RateComparer : IEqualityComparer
{
- private int argument = 0;
+ private int argument = 0;
- public new bool Equals(object x, object y)
- {
- argument++;
- if (argument == 1) return true;
+ public new bool Equals(object x, object y)
+ {
+ argument++;
+ if (argument == 1) return true;
- double fx, fy;
- if (x is Double || x is Single)
- {
- fx = (double) x;
- fy = (double) y;
+ double fx, fy;
+ if (x is double || x is float)
+ {
+ fx = (double)x;
+ fy = (double)y;
return Math.Round(fx * 1000).Equals(Math.Round(fy * 1000));
- }
- else
- {
- return x.Equals(y);
- }
- }
-
- public int GetHashCode(object obj)
- {
- if (obj is Single || obj is Double)
- return Math.Round(((double) obj) * 1000).GetHashCode();
- else
- return obj.GetHashCode();
- }
+ }
+ else
+ {
+ return x.Equals(y);
+ }
+ }
+
+ public int GetHashCode(object obj)
+ {
+ if (obj is float || obj is double)
+ return Math.Round(((double)obj) * 1000).GetHashCode();
+ else
+ return obj.GetHashCode();
+ }
}
-public class Example
+public class EqualsExample2
{
- public static void Main()
- {
- var rate1 = Tuple.Create("New York", .014505, -.1042733,
- .0354833, .093644, .0290792);
- var rate2 = Tuple.Create("Unknown City", .014505, -.1042733,
- .0354833, .093644, .0290792);
- var rate3 = Tuple.Create("Unknown City", .014505, -.1042733,
- .0354833, .093644, .029079);
- var rate4 = Tuple.Create("San Francisco", -.0332858, -.0512803,
- .0662544, .0728964, .0491912);
- IStructuralEquatable eq = rate1;
- // Compare first tuple with remaining two tuples.
- Console.WriteLine("{0} = ", rate1.ToString());
- Console.WriteLine(" {0} : {1}", rate2,
- eq.Equals(rate2, new RateComparer()));
- Console.WriteLine(" {0} : {1}", rate3,
- eq.Equals(rate3, new RateComparer()));
- Console.WriteLine(" {0} : {1}", rate4,
- eq.Equals(rate4, new RateComparer()));
- }
+ public static void Run()
+ {
+ var rate1 = Tuple.Create("New York", .014505, -.1042733,
+ .0354833, .093644, .0290792);
+ var rate2 = Tuple.Create("Unknown City", .014505, -.1042733,
+ .0354833, .093644, .0290792);
+ var rate3 = Tuple.Create("Unknown City", .014505, -.1042733,
+ .0354833, .093644, .029079);
+ var rate4 = Tuple.Create("San Francisco", -.0332858, -.0512803,
+ .0662544, .0728964, .0491912);
+ IStructuralEquatable eq = rate1;
+ // Compare first tuple with remaining two tuples.
+ Console.WriteLine($"{rate1} = ");
+ Console.WriteLine($" {rate2} : {eq.Equals(rate2, new RateComparer())}");
+ Console.WriteLine($" {rate3} : {eq.Equals(rate3, new RateComparer())}");
+ Console.WriteLine($" {rate4} : {eq.Equals(rate4, new RateComparer())}");
+ }
}
// The example displays the following output:
// (New York, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) =
// (Unknown City, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.0290792) : True
// (Unknown City, 0.014505, -0.1042733, 0.0354833, 0.093644, 0.029079) : True
// (San Francisco, -0.0332858, -0.0512803, 0.0662544, 0.0728964, 0.0491912) : False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs
index 39873aa49e6..4cf8e038e53 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Item1/item1.cs
@@ -1,37 +1,33 @@
//
using System;
-using System.Text.RegularExpressions;
+
public class Class1
{
- public static void Main()
- {
- // Create tuples containing population data for New York, Chicago,
- // and Los Angeles, 1960-2000.
- Tuple[] cities =
- { Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
+ public static void Main()
+ {
+ // Create tuples containing population data for New York, Chicago,
+ // and Los Angeles, 1960-2000.
+ Tuple[] cities =
+ [ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
- Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) };
+ Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ];
- // Display tuple data in table.
- string header = "Population in";
- Console.WriteLine("{0,-12} {1,60}",
- "City", new String('-',(60-header.Length)/2) + header +
- new String('-', (60-header.Length)/2));
- Console.WriteLine("{0,25}{1,12}{2,12}{3,12}{4,12}\n",
- "1960", "1970", "1980", "1990", "2000");
+ // Display tuple data in table.
+ string header = "Population in";
+ Console.WriteLine($"{"City",-12} {new string('-', (60 - header.Length) / 2) + header +
+ new string('-', (60 - header.Length) / 2),60}");
+ Console.WriteLine($"{"1960",25}{"1970",12}{"1980",12}{"1990",12}{"2000",12}\n");
- foreach (var city in cities)
- Console.WriteLine("{0,-12} {1,12:N0}{2,12:N0}{3,12:N0}{4,12:N0}{5,12:N0}",
- city.Item1, city.Item2, city.Item3, city.Item4,
- city.Item5, city.Item6);
- }
+ foreach (var city in cities)
+ Console.WriteLine($"{city.Item1,-12} {city.Item2,12:N0}{city.Item3,12:N0}{city.Item4,12:N0}{city.Item5,12:N0}{city.Item6,12:N0}");
+ }
}
// The example displays the following output:
// City -----------------------Population in-----------------------
// 1960 1970 1980 1990 2000
-//
+//
// New York 7,781,984 7,894,862 7,071,639 7,322,564 8,008,278
// Los Angeles 2,479,015 2,816,061 2,966,850 3,485,398 3,694,820
// Chicago 3,550,904 3,366,957 3,005,072 2,783,726 2,896,016
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs
index 6bf08fde43e..a09e91f460a 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/Overview/example1.cs
@@ -3,38 +3,38 @@
public class Example
{
- public static void Main()
- {
- // Get population data for New York City, 1960-2000.
- var population =
- Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278);
- var rate = ComputePopulationChange(population);
- // Display results.
- Console.WriteLine("Population Change, {0}, 1960-2000\n", population.Item1);
- Console.WriteLine("Year {0,10} {1,9}", "Population", "Annual Rate");
- Console.WriteLine("1960 {0,10:N0} {1,11}", population.Item2, "NA");
- Console.WriteLine("1970 {0,10:N0} {1,11:P2}", population.Item3, rate.Item2/10);
- Console.WriteLine("1980 {0,10:N0} {1,11:P2}", population.Item4, rate.Item3/10);
- Console.WriteLine("1990 {0,10:N0} {1,11:P2}", population.Item5, rate.Item4/10);
- Console.WriteLine("2000 {0,10:N0} {1,11:P2}", population.Item6, rate.Item5/10);
- Console.WriteLine("1960-2000 {0,10:N0} {1,11:P2}", "", rate.Item6/50);
- }
+ public static void Main()
+ {
+ // Get population data for New York City, 1960-2000.
+ var population =
+ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278);
+ var rate = ComputePopulationChange(population);
+ // Display results.
+ Console.WriteLine($"Population Change, {population.Item1}, 1960-2000\n");
+ Console.WriteLine($"Year {"Population",10} {"Annual Rate",9}");
+ Console.WriteLine($"1960 {population.Item2,10:N0} {"NA",11}");
+ Console.WriteLine($"1970 {population.Item3,10:N0} {rate.Item2 / 10,11:P2}");
+ Console.WriteLine($"1980 {population.Item4,10:N0} {rate.Item3 / 10,11:P2}");
+ Console.WriteLine($"1990 {population.Item5,10:N0} {rate.Item4 / 10,11:P2}");
+ Console.WriteLine($"2000 {population.Item6,10:N0} {rate.Item5 / 10,11:P2}");
+ Console.WriteLine($"1960-2000 {"",10:N0} {rate.Item6 / 50,11:P2}");
+ }
- private static Tuple ComputePopulationChange(
- Tuple data)
- {
- var rate = Tuple.Create(data.Item1,
- (double)(data.Item3 - data.Item2)/data.Item2,
- (double)(data.Item4 - data.Item3)/data.Item3,
- (double)(data.Item5 - data.Item4)/data.Item4,
- (double)(data.Item6 - data.Item5)/data.Item5,
- (double)(data.Item6 - data.Item2)/data.Item2 );
- return rate;
- }
+ private static Tuple ComputePopulationChange(
+ Tuple data)
+ {
+ var rate = Tuple.Create(data.Item1,
+ (double)(data.Item3 - data.Item2) / data.Item2,
+ (double)(data.Item4 - data.Item3) / data.Item3,
+ (double)(data.Item5 - data.Item4) / data.Item4,
+ (double)(data.Item6 - data.Item5) / data.Item5,
+ (double)(data.Item6 - data.Item2) / data.Item2);
+ return rate;
+ }
}
// The example displays the following output:
// Population Change, New York, 1960-2000
-//
+//
// Year Population Annual Rate
// 1960 7,781,984 NA
// 1970 7,894,862 0.15 %
@@ -42,4 +42,4 @@ private static Tuple ComputePopu
// 1990 7,322,564 0.35 %
// 2000 8,008,278 0.94 %
// 1960-2000 0.06 %
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index a52c2493602..c71795a8bdf 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,40 +1,40 @@
//
using System;
-public class Example
+public class CompareToExample1
{
- public static void Main()
- {
- // Create array of sextuple with population data for three U.S.
- // cities, 1960-2000.
- Tuple[] cities =
- { Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
- Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) };
-
- // Display array in unsorted order.
- Console.WriteLine("In unsorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
+ public static void Run()
+ {
+ // Create array of sextuple with population data for three U.S.
+ // cities, 1960-2000.
+ Tuple[] cities =
+ [ Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
+ Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
+ Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ];
- Console.WriteLine();
-
- Array.Sort(cities);
-
- // Display array in sorted order.
- Console.WriteLine("In sorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- }
+ // Display array in unsorted order.
+ Console.WriteLine("In unsorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+
+ Console.WriteLine();
+
+ Array.Sort(cities);
+
+ // Display array in sorted order.
+ Console.WriteLine("In sorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ }
}
// The example displays the following output:
// In unsorted order:
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016)
-//
+//
// In sorted order:
// (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index 8bd3fa29ccf..6808606184a 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,97 +5,90 @@
public class PopulationComparer : IComparer
{
- private int itemPosition;
- private int multiplier = -1;
+ private int itemPosition;
+ private int multiplier = -1;
- public PopulationComparer(int component) : this(component, true)
- { }
+ public PopulationComparer(int component) : this(component, true)
+ { }
- public PopulationComparer(int component, bool descending)
- {
- if (!descending) multiplier = 1;
+ public PopulationComparer(int component, bool descending)
+ {
+ if (!descending) multiplier = 1;
- if (component <= 0 || component > 6)
- throw new ArgumentException("The component argument is out of range.");
+ if (component <= 0 || component > 6)
+ throw new ArgumentException("The component argument is out of range.");
- itemPosition = component;
- }
+ itemPosition = component;
+ }
- public int Compare(object x, object y)
- {
- var tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- var tY = y as Tuple;
- switch (itemPosition)
- {
- case 1:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- case 2:
- return Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier;
- case 3:
- return Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier;
- case 4:
- return Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier;
- case 5:
- return Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier;
- case 6:
- return Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier;
- default:
- return Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier;
- }
- }
- }
+ public int Compare(object x, object y)
+ {
+ var tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ var tY = y as Tuple;
+ return itemPosition switch
+ {
+ 1 => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier,
+ 2 => Comparer.Default.Compare(tX.Item2, tY.Item2) * multiplier,
+ 3 => Comparer.Default.Compare(tX.Item3, tY.Item3) * multiplier,
+ 4 => Comparer.Default.Compare(tX.Item4, tY.Item4) * multiplier,
+ 5 => Comparer.Default.Compare(tX.Item5, tY.Item5) * multiplier,
+ 6 => Comparer.Default.Compare(tX.Item6, tY.Item6) * multiplier,
+ _ => Comparer.Default.Compare(tX.Item1, tY.Item1) * multiplier
+ };
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- // Create array of sextuple with population data for three U.S.
- // cities, 1960-2000.
- Tuple[] cities =
- { Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
+ public static void Run()
+ {
+ // Create array of sextuple with population data for three U.S.
+ // cities, 1960-2000.
+ Tuple[] cities =
+ [ Tuple.Create("Los Angeles", 2479015, 2816061, 2966850, 3485398, 3694820),
Tuple.Create("New York", 7781984, 7894862, 7071639, 7322564, 8008278),
- Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) };
+ Tuple.Create("Chicago", 3550904, 3366957, 3005072, 2783726, 2896016) ];
- // Display array in unsorted order.
- Console.WriteLine("In unsorted order:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
+ // Display array in unsorted order.
+ Console.WriteLine("In unsorted order:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
- Array.Sort(cities, new PopulationComparer(3));
+ Array.Sort(cities, new PopulationComparer(3));
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 1970:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- Console.WriteLine();
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 1970:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ Console.WriteLine();
- Array.Sort(cities, new PopulationComparer(6));
+ Array.Sort(cities, new PopulationComparer(6));
- // Display array in sorted order.
- Console.WriteLine("Sorted by population in 2000:");
- foreach (var city in cities)
- Console.WriteLine(city.ToString());
- }
+ // Display array in sorted order.
+ Console.WriteLine("Sorted by population in 2000:");
+ foreach (var city in cities)
+ Console.WriteLine(city);
+ }
}
// The example displays the following output:
// In unsorted order:
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820)
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016)
-//
+//
// Sorted by population in 1970:
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Chicago, 3550904, 3366957, 3005072, 2783726, 2896016)
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820)
-//
+//
// Sorted by population in 2000:
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
// (Los Angeles, 2479015, 2816061, 2966850, 3485398, 3694820)
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs
index 4e4d4248140..d8f9ed2e95b 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5,T6/ToString/tostring1.cs
@@ -3,13 +3,13 @@
public class Example
{
- public static void Main()
- {
- // Get population data for New York City, 1960-2000.
- var population = Tuple.Create("New York", 7781984, 7894862,
- 7071639, 7322564, 8008278);
- Console.WriteLine(population.ToString());
- }
+ public static void Main()
+ {
+ // Get population data for New York City, 1960-2000.
+ var population = Tuple.Create("New York", 7781984, 7894862,
+ 7071639, 7322564, 8008278);
+ Console.WriteLine(population.ToString());
+ }
}
// The example displays the following output:
// (New York, 7781984, 7894862, 7071639, 7322564, 8008278)
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs
index cb0a1aa1032..210a0263836 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals1.cs
@@ -3,25 +3,24 @@
public class Class1
{
- public static void Main()
- {
- Tuple[] temperatureInfos =
- { Tuple.Create(2, 97.9, 97.8, 98.0, 98.2),
- Tuple.Create(1, 98.6, 98.8, 98.8, 99.0),
+ public static void Main()
+ {
+ Tuple[] temperatureInfos =
+ [ Tuple.Create(2, 97.9, 97.8, 98.0, 98.2),
+ Tuple.Create(1, 98.6, 98.8, 98.8, 99.0),
Tuple.Create(2, 98.6, 98.6, 98.6, 98.4),
Tuple.Create(1, 98.4, 98.6, 99.0, 99.2),
Tuple.Create(2, 98.6, 98.6, 98.6, 98.4),
- Tuple.Create(1, 98.6, 98.8, 98.8, 99.0) };
- // Compare each item with every other item for equality.
- for (int ctr = 0; ctr < temperatureInfos.Length; ctr++)
- {
- var temperatureInfo = temperatureInfos[ctr];
- for (int ctr2 = ctr + 1; ctr2 < temperatureInfos.Length; ctr2++)
- Console.WriteLine("{0} = {1}: {2}", temperatureInfo, temperatureInfos[ctr2],
- temperatureInfo.Equals(temperatureInfos[ctr2]));
- Console.WriteLine();
- }
- }
+ Tuple.Create(1, 98.6, 98.8, 98.8, 99.0) ];
+ // Compare each item with every other item for equality.
+ for (int ctr = 0; ctr < temperatureInfos.Length; ctr++)
+ {
+ var temperatureInfo = temperatureInfos[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < temperatureInfos.Length; ctr2++)
+ Console.WriteLine($"{temperatureInfo} = {temperatureInfos[ctr2]}: {temperatureInfo.Equals(temperatureInfos[ctr2])}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (2, 97.9, 97.8, 98, 98.2) = (1, 98.6, 98.8, 98.8, 99): False
@@ -29,18 +28,18 @@ public static void Main()
// (2, 97.9, 97.8, 98, 98.2) = (1, 98.4, 98.6, 99, 99.2): False
// (2, 97.9, 97.8, 98, 98.2) = (2, 98.6, 98.6, 98.6, 98.4): False
// (2, 97.9, 97.8, 98, 98.2) = (1, 98.6, 98.8, 98.8, 99): False
-//
+//
// (1, 98.6, 98.8, 98.8, 99) = (2, 98.6, 98.6, 98.6, 98.4): False
// (1, 98.6, 98.8, 98.8, 99) = (1, 98.4, 98.6, 99, 99.2): False
// (1, 98.6, 98.8, 98.8, 99) = (2, 98.6, 98.6, 98.6, 98.4): False
// (1, 98.6, 98.8, 98.8, 99) = (1, 98.6, 98.8, 98.8, 99): True
-//
+//
// (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.4, 98.6, 99, 99.2): False
// (2, 98.6, 98.6, 98.6, 98.4) = (2, 98.6, 98.6, 98.6, 98.4): True
// (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.6, 98.8, 98.8, 99): False
-//
+//
// (1, 98.4, 98.6, 99, 99.2) = (2, 98.6, 98.6, 98.6, 98.4): False
// (1, 98.4, 98.6, 99, 99.2) = (1, 98.6, 98.8, 98.8, 99): False
-//
+//
// (2, 98.6, 98.6, 98.6, 98.4) = (1, 98.6, 98.8, 98.8, 99): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs
index 210eae5e9b4..99b8ce06a56 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Equals/equals2.cs
@@ -4,63 +4,59 @@
public class DoubleComparer : IEqualityComparer
{
- private double difference;
- private int argument = 0;
-
- public DoubleComparer(double difference)
- {
- this.difference = difference;
- }
-
- new public bool Equals(object x, object y)
- {
- argument += 1;
-
- // Return true for Item1.
- if (argument == 1) return true;
+ private double difference;
+ private int argument = 0;
- double d1 = (double) x;
- double d2 = (double) y;
+ public DoubleComparer(double difference) => this.difference = difference;
- if (d1 - d2 < d1 * difference)
- return true;
- else
- return false;
- }
-
- public int GetHashCode(object obj)
- {
- if (obj is T1)
- return ((T1) obj).GetHashCode();
- else if (obj is T2)
- return ((T2) obj).GetHashCode();
- else if (obj is T3)
- return ((T3) obj).GetHashCode();
- else if (obj is T4)
- return ((T4) obj).GetHashCode();
- else
- return ((T5) obj).GetHashCode();
- }
+ new public bool Equals(object x, object y)
+ {
+ argument += 1;
+
+ // Return true for Item1.
+ if (argument == 1) return true;
+
+ double d1 = (double)x;
+ double d2 = (double)y;
+
+ if (d1 - d2 < d1 * difference)
+ return true;
+ else
+ return false;
+ }
+
+ public int GetHashCode(object obj)
+ {
+ if (obj is T1)
+ return ((T1)obj).GetHashCode();
+ else if (obj is T2)
+ return ((T2)obj).GetHashCode();
+ else if (obj is T3)
+ return ((T3)obj).GetHashCode();
+ else if (obj is T4)
+ return ((T4)obj).GetHashCode();
+ else
+ return ((T5)obj).GetHashCode();
+ }
}
public class Example
{
- public static void Main()
- {
- var value1 = GetValues(1);
- var value2 = GetValues(2);
- IStructuralEquatable iValue1 = value1;
- Console.WriteLine("{0} =\n{1} :\n{2}", value1, value2,
- iValue1.Equals(value2,
- new DoubleComparer(.01)));
- }
+ public static void Main()
+ {
+ var value1 = GetValues(1);
+ var value2 = GetValues(2);
+ IStructuralEquatable iValue1 = value1;
+ Console.WriteLine($"{value1} =\n{value2} :\n{iValue1.Equals(value2,
+ new DoubleComparer(.01))}");
+ }
- private static Tuple GetValues(int ctr)
- {
- // Generate four random numbers between 0 and 1
- Random rnd = new Random((int)DateTime.Now.Ticks >> 32 >> ctr);
- return Tuple.Create(ctr, rnd.NextDouble(), rnd.NextDouble(),
- rnd.NextDouble(), rnd.NextDouble());
- }
+ private static Tuple GetValues(int ctr)
+ {
+ // Generate four random numbers between 0 and 1
+ Random rnd = new((int)DateTime.Now.Ticks >> 32 >> ctr);
+ return Tuple.Create(ctr, rnd.NextDouble(), rnd.NextDouble(),
+ rnd.NextDouble(), rnd.NextDouble());
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs
index b8c1131213d..5916cb1bdb4 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Item1/item1.cs
@@ -3,28 +3,24 @@
public class Example
{
- public static void Main()
- {
- // Define array of tuples reflecting population change by state, 1990-2000.
- Tuple[] statesData =
- { Tuple.Create("California", 29760021, 33871648, 4111627, 13.8),
- Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6),
- Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) };
+ public static void Main()
+ {
+ // Define array of tuples reflecting population change by state, 1990-2000.
+ Tuple[] statesData =
+ [ Tuple.Create("California", 29760021, 33871648, 4111627, 13.8),
+ Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6),
+ Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) ];
- // Display the items of each tuple
- Console.WriteLine("{0,-12}{1,18}{2,18}{3,15}{4,12}\n", "State",
- "Population 1990", "Population 2000", "Change",
- "% Change");
- foreach(Tuple stateData in statesData)
- Console.WriteLine("{0,-12}{1,18:N0}{2,18:N0}{3,15:N0}{4,12:P1}",
- stateData.Item1, stateData.Item2,
- stateData.Item3, stateData.Item4, stateData.Item5/100);
- }
+ // Display the items of each tuple
+ Console.WriteLine($"{"State",-12}{"Population 1990",18}{"Population 2000",18}{"Change",15}{"% Change",12}\n");
+ foreach (Tuple stateData in statesData)
+ Console.WriteLine($"{stateData.Item1,-12}{stateData.Item2,18:N0}{stateData.Item3,18:N0}{stateData.Item4,15:N0}{stateData.Item5 / 100,12:P1}");
+ }
}
// The example displays the following output:
// State Population 1990 Population 2000 Change % Change
-//
+//
// California 29,760,021 33,871,648 4,111,627 13.8 %
// Illinois 11,430,602 12,419,293 988,691 8.6 %
// Washington 4,866,692 5,894,121 1,027,429 21.1 %
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs
index f90ff6e9b47..71931116b33 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/Overview/example1.cs
@@ -4,70 +4,65 @@
public class Example
{
- public static void Main()
- {
- // Organization of runningBacks 5-tuple:
- // Component 1: Player name
- // Component 2: Number of games played
- // Component 3: Number of attempts (carries)
- // Component 4: Number of yards gained
- // Component 5: Number of touchdowns
- Tuple[] runningBacks =
- { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
- Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
- Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
- Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
- Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) };
- // Calculate statistics.
- // Organization of runningStats 5-tuple:
- // Component 1: Player name
- // Component 2: Number of attempts per game
- // Component 3: Number of yards per game
- // Component 4: Number of yards per attempt
- // Component 5: Number of touchdowns per attempt
- Tuple[] runningStats =
- ComputeStatistics(runningBacks);
+ public static void Main()
+ {
+ // Organization of runningBacks 5-tuple:
+ // Component 1: Player name
+ // Component 2: Number of games played
+ // Component 3: Number of attempts (carries)
+ // Component 4: Number of yards gained
+ // Component 5: Number of touchdowns
+ Tuple[] runningBacks =
+ [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
+ Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
+ Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
+ Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
+ Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ];
+ // Calculate statistics.
+ // Organization of runningStats 5-tuple:
+ // Component 1: Player name
+ // Component 2: Number of attempts per game
+ // Component 3: Number of yards per game
+ // Component 4: Number of yards per attempt
+ // Component 5: Number of touchdowns per attempt
+ Tuple[] runningStats =
+ ComputeStatistics(runningBacks);
- // Display the result.
- Console.WriteLine("{0,-16} {1,5} {2,6} {3,7} {4,7} {5,7} {6,7} {7,5} {8,7}\n",
- "Name", "Games", "Att", "Att/Gm", "Yards", "Yds/Gm",
- "Yds/Att", "TD", "TD/Att");
- for (int ctr = 0; ctr < runningBacks.Length; ctr++)
- Console.WriteLine("{0,-16} {1,5} {2,6:N0} {3,7:N1} {4,7:N0} {5,7:N1} {6,7:N2} {7,5} {8,7:N3}\n",
- runningBacks[ctr].Item1, runningBacks[ctr].Item2, runningBacks[ctr].Item3,
- runningStats[ctr].Item2, runningBacks[ctr].Item4, runningStats[ctr].Item3,
- runningStats[ctr].Item4, runningBacks[ctr].Item5, runningStats[ctr].Item5);
- }
+ // Display the result.
+ Console.WriteLine($"{"Name",-16} {"Games",5} {"Att",6} {"Att/Gm",7} {"Yards",7} {"Yds/Gm",7} {"Yds/Att",7} {"TD",5} {"TD/Att",7}\n");
+ for (int ctr = 0; ctr < runningBacks.Length; ctr++)
+ Console.WriteLine($"{runningBacks[ctr].Item1,-16} {runningBacks[ctr].Item2,5} {runningBacks[ctr].Item3,6:N0} {runningStats[ctr].Item2,7:N1} {runningBacks[ctr].Item4,7:N0} {runningStats[ctr].Item3,7:N1} {runningStats[ctr].Item4,7:N2} {runningBacks[ctr].Item5,5} {runningStats[ctr].Item5,7:N3}\n");
+ }
- private static Tuple[] ComputeStatistics(
- Tuple[] players)
- {
- Tuple result;
- var list = new List>();
-
- foreach (var player in players)
- {
- // Create result object containing player name and statistics.
- result = Tuple.Create(player.Item1,
- player.Item3/((double)player.Item2),
- player.Item4/((double)player.Item2),
- player.Item4/((double)player.Item3),
- player.Item5/((double)player.Item3));
- list.Add(result);
- }
- return list.ToArray();
- }
+ private static Tuple[] ComputeStatistics(
+ Tuple[] players)
+ {
+ Tuple result;
+ List> list = [];
+
+ foreach (var player in players)
+ {
+ // Create result object containing player name and statistics.
+ result = Tuple.Create(player.Item1,
+ player.Item3 / ((double)player.Item2),
+ player.Item4 / ((double)player.Item2),
+ player.Item4 / ((double)player.Item3),
+ player.Item5 / ((double)player.Item3));
+ list.Add(result);
+ }
+ return list.ToArray();
+ }
}
// The example displays the following output:
// Name Games Att Att/Gm Yards Yds/Gm Yds/Att TD TD/Att
-//
+//
// Payton, Walter 190 3,838 20.2 16,726 88.0 4.36 110 0.029
-//
+//
// Sanders, Barry 153 3,062 20.0 15,269 99.8 4.99 99 0.032
-//
+//
// Brown, Jim 118 2,359 20.0 12,312 104.3 5.22 106 0.045
-//
+//
// Dickerson, Eric 144 2,996 20.8 13,259 92.1 4.43 90 0.030
-//
+//
// Faulk, Marshall 176 2,836 16.1 12,279 69.8 4.33 100 0.035
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index 44ae3b18e8c..539d8161455 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,38 +1,38 @@
//
using System;
-using System.Collections.Generic;
-public class Example
+
+public class CompareToExample1
{
- public static void Main()
- {
- // Organization of runningBacks 5-tuple:
- // Component 1: Player name
- // Component 2: Number of games played
- // Component 3: Number of attempts (carries)
- // Component 4: Number of yards gained
- // Component 5: Number of touchdowns
- Tuple[] runningBacks =
- { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
- Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
- Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
- Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
- Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) };
+ public static void Run()
+ {
+ // Organization of runningBacks 5-tuple:
+ // Component 1: Player name
+ // Component 2: Number of games played
+ // Component 3: Number of attempts (carries)
+ // Component 4: Number of yards gained
+ // Component 5: Number of touchdowns
+ Tuple[] runningBacks =
+ [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
+ Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
+ Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
+ Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
+ Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ];
+
+ // Display the array in unsorted order.
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var runningBack in runningBacks)
+ Console.WriteLine(runningBack);
+ Console.WriteLine();
+
+ // Sort the array
+ Array.Sort(runningBacks);
- // Display the array in unsorted order.
- Console.WriteLine("The values in unsorted order:");
- foreach (var runningBack in runningBacks)
- Console.WriteLine(runningBack.ToString());
- Console.WriteLine();
-
- // Sort the array
- Array.Sort(runningBacks);
-
- // Display the array in sorted order.
- Console.WriteLine("The values in sorted order:");
- foreach (var runningBack in runningBacks)
- Console.WriteLine(runningBack.ToString());
- }
+ // Display the array in sorted order.
+ Console.WriteLine("The values in sorted order:");
+ foreach (var runningBack in runningBacks)
+ Console.WriteLine(runningBack);
+ }
}
// The example displays the following output:
// The values in unsorted order:
@@ -41,11 +41,11 @@ public static void Main()
// (Brown, Jim, 118, 2359, 12312, 106)
// (Dickerson, Eric, 144, 2996, 13259, 90)
// (Faulk, Marshall, 176, 2836, 12279, 100)
-//
+//
// The values in sorted order:
// (Brown, Jim, 118, 2359, 12312, 106)
// (Dickerson, Eric, 144, 2996, 13259, 90)
// (Faulk, Marshall, 176, 2836, 12279, 100)
// (Payton, Walter, 190, 3838, 16726, 110)
// (Sanders, Barry, 153, 3062, 15269, 99)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index a1f9c1c7da2..bf0742d5aeb 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,52 +5,52 @@
public class YardsGained : IComparer
{
- public int Compare(object x, object y)
- {
- Tuple tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- Tuple tY = y as Tuple;
- return -1 * Comparer.Default.Compare(tX.Item4, tY.Item4);
- }
- }
+ public int Compare(object x, object y)
+ {
+ Tuple tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ Tuple tY = y as Tuple;
+ return -1 * Comparer.Default.Compare(tX.Item4, tY.Item4);
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- // Organization of runningBacks 5-tuple:
- // Component 1: Player name
- // Component 2: Number of games played
- // Component 3: Number of attempts (carries)
- // Component 4: Number of yards gained
- // Component 5: Number of touchdowns
- Tuple[] runningBacks =
- { Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
- Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
- Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
- Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
- Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) };
+ public static void Run()
+ {
+ // Organization of runningBacks 5-tuple:
+ // Component 1: Player name
+ // Component 2: Number of games played
+ // Component 3: Number of attempts (carries)
+ // Component 4: Number of yards gained
+ // Component 5: Number of touchdowns
+ Tuple[] runningBacks =
+ [ Tuple.Create("Payton, Walter", 190, 3838, 16726, 110),
+ Tuple.Create("Sanders, Barry", 153, 3062, 15269, 99),
+ Tuple.Create("Brown, Jim", 118, 2359, 12312, 106),
+ Tuple.Create("Dickerson, Eric", 144, 2996, 13259, 90),
+ Tuple.Create("Faulk, Marshall", 176, 2836, 12279, 100) ];
- // Display the array in unsorted order.
- Console.WriteLine("The values in unsorted order:");
- foreach (var runningBack in runningBacks)
- Console.WriteLine(runningBack.ToString());
- Console.WriteLine();
-
- // Sort the array
- Array.Sort(runningBacks, new YardsGained());
-
- // Display the array in sorted order.
- Console.WriteLine("The values in sorted order:");
- foreach (var runningBack in runningBacks)
- Console.WriteLine(runningBack.ToString());
- }
+ // Display the array in unsorted order.
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var runningBack in runningBacks)
+ Console.WriteLine(runningBack);
+ Console.WriteLine();
+
+ // Sort the array
+ Array.Sort(runningBacks, new YardsGained());
+
+ // Display the array in sorted order.
+ Console.WriteLine("The values in sorted order:");
+ foreach (var runningBack in runningBacks)
+ Console.WriteLine(runningBack);
+ }
}
// The example displays the following output:
// The values in unsorted order:
@@ -59,11 +59,11 @@ public static void Main()
// (Brown, Jim, 118, 2359, 12312, 106)
// (Dickerson, Eric, 144, 2996, 13259, 90)
// (Faulk, Marshall, 176, 2836, 12279, 100)
-//
+//
// The values in sorted order:
// (Brown, Jim, 118, 2359, 12312, 106)
// (Dickerson, Eric, 144, 2996, 13259, 90)
// (Faulk, Marshall, 176, 2836, 12279, 100)
// (Payton, Walter, 190, 3838, 16726, 110)
// (Sanders, Barry, 153, 3062, 15269, 99)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs
index 5354516ce78..1aa649bc5b1 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4,T5/ToString/tostring1.cs
@@ -3,20 +3,20 @@
public class Example
{
- public static void Main()
- {
- // Define array of tuples reflecting population change by state, 1990-2000.
- Tuple[] populationChanges =
- { Tuple.Create("California", 29760021, 33871648, 4111627, 13.8),
- Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6),
- Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) };
- // Display each tuple.
- foreach (var item in populationChanges)
- Console.WriteLine(item.ToString());
- }
+ public static void Main()
+ {
+ // Define array of tuples reflecting population change by state, 1990-2000.
+ Tuple[] populationChanges =
+ [ Tuple.Create("California", 29760021, 33871648, 4111627, 13.8),
+ Tuple.Create("Illinois", 11430602, 12419293, 988691, 8.6),
+ Tuple.Create("Washington", 4866692, 5894121, 1027429, 21.1) ];
+ // Display each tuple.
+ foreach (var item in populationChanges)
+ Console.WriteLine(item.ToString());
+ }
}
// The example displays the following output:
// (California, 29760021, 33871648, 4111627, 13.8)
// (Illinois, 11430602, 12419293, 988691, 8.6)
// (Washington, 4866692, 5894121, 1027429, 21.1)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs
index b7bd2128f39..ff7b5fab1a3 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals1.cs
@@ -3,25 +3,24 @@
public class Class1
{
- public static void Main()
- {
- Tuple[] temperatures =
- { Tuple.Create(new DateTime(2009, 1, 16), 3.0, 5.0, 4.0),
- Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0),
+ public static void Main()
+ {
+ Tuple[] temperatures =
+ [ Tuple.Create(new DateTime(2009, 1, 16), 3.0, 5.0, 4.0),
+ Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0),
Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 10.0),
Tuple.Create(new DateTime(2009, 6, 1), 23.0, 28.0, 21.0),
Tuple.Create(new DateTime(2009, 4, 22), 9.0, 14.0, 11.0),
- Tuple.Create(new DateTime(2009, 9, 6), 25.0, 30.0, 25.0) };
- // Compare each item with every other item for equality.
- for (int ctr = 0; ctr < temperatures.Length; ctr++)
- {
- var temperatureInfo = temperatures[ctr];
- for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++)
- Console.WriteLine("{0} = {1}: {2}", temperatureInfo, temperatures[ctr2],
- temperatureInfo.Equals(temperatures[ctr2]));
- Console.WriteLine();
- }
- }
+ Tuple.Create(new DateTime(2009, 9, 6), 25.0, 30.0, 25.0) ];
+ // Compare each item with every other item for equality.
+ for (int ctr = 0; ctr < temperatures.Length; ctr++)
+ {
+ var temperatureInfo = temperatures[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++)
+ Console.WriteLine($"{temperatureInfo} = {temperatures[ctr2]}: {temperatureInfo.Equals(temperatures[ctr2])}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (1/16/2009 12:00:00 AM, 3, 5, 4) = (4/22/2009 12:00:00 AM, 9, 14, 11): False
@@ -29,18 +28,18 @@ public static void Main()
// (1/16/2009 12:00:00 AM, 3, 5, 4) = (6/1/2009 12:00:00 AM, 23, 28, 21): False
// (1/16/2009 12:00:00 AM, 3, 5, 4) = (4/22/2009 12:00:00 AM, 9, 14, 11): False
// (1/16/2009 12:00:00 AM, 3, 5, 4) = (9/6/2009 12:00:00 AM, 25, 30, 25): False
-//
+//
// (4/22/2009 12:00:00 AM, 9, 14, 11) = (4/22/2009 12:00:00 AM, 9, 14, 10): False
// (4/22/2009 12:00:00 AM, 9, 14, 11) = (6/1/2009 12:00:00 AM, 23, 28, 21): False
// (4/22/2009 12:00:00 AM, 9, 14, 11) = (4/22/2009 12:00:00 AM, 9, 14, 11): True
// (4/22/2009 12:00:00 AM, 9, 14, 11) = (9/6/2009 12:00:00 AM, 25, 30, 25): False
-//
+//
// (4/22/2009 12:00:00 AM, 9, 14, 10) = (6/1/2009 12:00:00 AM, 23, 28, 21): False
// (4/22/2009 12:00:00 AM, 9, 14, 10) = (4/22/2009 12:00:00 AM, 9, 14, 11): False
// (4/22/2009 12:00:00 AM, 9, 14, 10) = (9/6/2009 12:00:00 AM, 25, 30, 25): False
-//
+//
// (6/1/2009 12:00:00 AM, 23, 28, 21) = (4/22/2009 12:00:00 AM, 9, 14, 11): False
// (6/1/2009 12:00:00 AM, 23, 28, 21) = (9/6/2009 12:00:00 AM, 25, 30, 25): False
-//
+//
// (4/22/2009 12:00:00 AM, 9, 14, 11) = (9/6/2009 12:00:00 AM, 25, 30, 25): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs
index d660b7a65cf..96e453de0f1 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Equals/equals2.cs
@@ -4,56 +4,54 @@
public class Item3And4Comparer : IEqualityComparer
{
- private int argument = 0;
-
- new public bool Equals(object x, object y)
- {
- argument++;
-
- // Return true for all values of Item1, Item2.
- if (argument <= 2)
- return true;
- else
- return x.Equals(y);
- }
-
- public int GetHashCode(object obj)
- {
- if (obj is T1)
- return ((T1) obj).GetHashCode();
- else if (obj is T2)
- return ((T2) obj).GetHashCode();
- else if (obj is T3)
- return ((T3) obj).GetHashCode();
- else
- return ((T4) obj).GetHashCode();
- }
+ private int argument = 0;
+
+ new public bool Equals(object x, object y)
+ {
+ argument++;
+
+ // Return true for all values of Item1, Item2.
+ if (argument <= 2)
+ return true;
+ else
+ return x.Equals(y);
+ }
+
+ public int GetHashCode(object obj)
+ {
+ if (obj is T1)
+ return ((T1)obj).GetHashCode();
+ else if (obj is T2)
+ return ((T2)obj).GetHashCode();
+ else if (obj is T3)
+ return ((T3)obj).GetHashCode();
+ else
+ return ((T4)obj).GetHashCode();
+ }
}
public class Example
{
- public static void Main()
- {
- Tuple[] temperatures =
- { Tuple.Create("New York, NY", 4, 61.0, 43.0),
- Tuple.Create("Chicago, IL", 2, 34.0, 18.0),
+ public static void Main()
+ {
+ Tuple[] temperatures =
+ [ Tuple.Create("New York, NY", 4, 61.0, 43.0),
+ Tuple.Create("Chicago, IL", 2, 34.0, 18.0),
Tuple.Create("Newark, NJ", 4, 61.0, 43.0),
Tuple.Create("Boston, MA", 6, 77.0, 59.0),
Tuple.Create("Detroit, MI", 9, 74.0, 53.0),
- Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) };
- // Compare each item with every other item for equality.
- for (int ctr = 0; ctr < temperatures.Length; ctr++)
- {
- IStructuralEquatable temperatureInfo = temperatures[ctr];
- for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++)
- Console.WriteLine("{0} = {1}: {2}",
- temperatureInfo, temperatures[ctr2],
- temperatureInfo.Equals(temperatures[ctr2],
- new Item3And4Comparer()));
+ Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) ];
+ // Compare each item with every other item for equality.
+ for (int ctr = 0; ctr < temperatures.Length; ctr++)
+ {
+ IStructuralEquatable temperatureInfo = temperatures[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++)
+ Console.WriteLine($"{temperatureInfo} = {temperatures[ctr2]}: {temperatureInfo.Equals(temperatures[ctr2],
+ new Item3And4Comparer())}");
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (New York, NY, 4, 61, 43) = (Chicago, IL, 2, 34, 18): False
@@ -61,18 +59,18 @@ public static void Main()
// (New York, NY, 4, 61, 43) = (Boston, MA, 6, 77, 59): False
// (New York, NY, 4, 61, 43) = (Detroit, MI, 9, 74, 53): False
// (New York, NY, 4, 61, 43) = (Minneapolis, MN, 8, 81, 61): False
-//
+//
// (Chicago, IL, 2, 34, 18) = (Newark, NJ, 4, 61, 43): False
// (Chicago, IL, 2, 34, 18) = (Boston, MA, 6, 77, 59): False
// (Chicago, IL, 2, 34, 18) = (Detroit, MI, 9, 74, 53): False
// (Chicago, IL, 2, 34, 18) = (Minneapolis, MN, 8, 81, 61): False
-//
+//
// (Newark, NJ, 4, 61, 43) = (Boston, MA, 6, 77, 59): False
// (Newark, NJ, 4, 61, 43) = (Detroit, MI, 9, 74, 53): False
// (Newark, NJ, 4, 61, 43) = (Minneapolis, MN, 8, 81, 61): False
-//
+//
// (Boston, MA, 6, 77, 59) = (Detroit, MI, 9, 74, 53): False
// (Boston, MA, 6, 77, 59) = (Minneapolis, MN, 8, 81, 61): False
-//
+//
// (Detroit, MI, 9, 74, 53) = (Minneapolis, MN, 8, 81, 61): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs
index 74b42593592..c4f2a8aaab0 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Item1/item1.cs
@@ -4,34 +4,30 @@
public class Example
{
- public static void Main()
- {
- Tuple[] temperatures =
- { Tuple.Create("New York, NY", 4, 61.0, 43.0),
- Tuple.Create("Chicago, IL", 2, 34.0, 18.0),
+ public static void Main()
+ {
+ Tuple[] temperatures =
+ [ Tuple.Create("New York, NY", 4, 61.0, 43.0),
+ Tuple.Create("Chicago, IL", 2, 34.0, 18.0),
Tuple.Create("Newark, NJ", 4, 61.0, 43.0),
Tuple.Create("Boston, MA", 6, 77.0, 59.0),
Tuple.Create("Detroit, MI", 9, 74.0, 53.0),
- Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) };
- // Display the array of 4-tuple objects.
- Console.WriteLine("{0,41}", "Temperatures");
- Console.WriteLine("{0,-20} {1,5} {2,4} {3,4}\n",
- "City", "Month", "High", "Low");
- foreach (var temperature in temperatures)
- Console.WriteLine("{0,-20} {1,5} {2,4:N1} {3,4:N1}",
- temperature.Item1,
- DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(temperature.Item2 - 1),
- temperature.Item3, temperature.Item4);
- }
+ Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) ];
+ // Display the array of 4-tuple objects.
+ Console.WriteLine($"{"Temperatures",41}");
+ Console.WriteLine($"{"City",-20} {"Month",5} {"High",4} {"Low",4}\n");
+ foreach (var temperature in temperatures)
+ Console.WriteLine($"{temperature.Item1,-20} {DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(temperature.Item2 - 1),5} {temperature.Item3,4:N1} {temperature.Item4,4:N1}");
+ }
}
// The example displays the following output:
// Temperatures
// City Month High Low
-//
+//
// New York, NY Mar 61.0 43.0
// Chicago, IL Jan 34.0 18.0
// Newark, NJ Mar 61.0 43.0
// Boston, MA May 77.0 59.0
// Detroit, MI Aug 74.0 53.0
// Minneapolis, MN Jul 81.0 61.0
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs
index 503e29b5222..4f0eb494b13 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/Overview/example1.cs
@@ -4,50 +4,47 @@
public class Example
{
- public static void Main()
- {
- Tuple[] pitchers =
- { Tuple.Create("McHale, Joe", 240.1m, 221, 96),
- Tuple.Create("Paul, Dave", 233.1m, 231, 84),
+ public static void Main()
+ {
+ Tuple[] pitchers =
+ [ Tuple.Create("McHale, Joe", 240.1m, 221, 96),
+ Tuple.Create("Paul, Dave", 233.1m, 231, 84),
Tuple.Create("Williams, Mike", 193.2m, 183, 86),
- Tuple.Create("Blair, Jack", 168.1m, 146, 65),
+ Tuple.Create("Blair, Jack", 168.1m, 146, 65),
Tuple.Create("Henry, Walt", 140.1m, 96, 30),
Tuple.Create("Lee, Adam", 137.2m, 109, 45),
- Tuple.Create("Rohr, Don", 101.0m, 110, 42) };
- Tuple[] results= ComputeStatistics(pitchers);
+ Tuple.Create("Rohr, Don", 101.0m, 110, 42) ];
+ Tuple[] results = ComputeStatistics(pitchers);
- // Display the results.
- Console.WriteLine("{0,-20} {1,9} {2,11} {3,15}\n",
- "Pitcher", "ERA", "Hits/Inn.", "Effectiveness");
- foreach (var result in results)
- Console.WriteLine("{0,-20} {1,9:F2} {2,11:F2} {3,15:F2}",
- result.Item1, result.Item2, result.Item3, result.Item4);
- }
+ // Display the results.
+ Console.WriteLine($"{"Pitcher",-20} {"ERA",9} {"Hits/Inn.",11} {"Effectiveness",15}\n");
+ foreach (var result in results)
+ Console.WriteLine($"{result.Item1,-20} {result.Item2,9:F2} {result.Item3,11:F2} {result.Item4,15:F2}");
+ }
- private static Tuple[] ComputeStatistics(Tuple[] pitchers)
- {
- var list = new List>();
- Tuple result;
+ private static Tuple[] ComputeStatistics(Tuple[] pitchers)
+ {
+ List> list = [];
+ Tuple result;
- foreach (var pitcher in pitchers)
- {
- // Decimal portion of innings pitched represents 1/3 of an inning
- double innings = (double) Math.Truncate(pitcher.Item2);
- innings = innings + (((double)pitcher.Item2 - innings) * .33);
-
- double ERA = pitcher.Item4/innings * 9;
- double hitsPerInning = pitcher.Item3/innings;
- double EI = (ERA * 2 + hitsPerInning * 9)/3;
- result = new Tuple
- (pitcher.Item1, ERA, hitsPerInning, EI);
- list.Add(result);
- }
- return list.ToArray();
- }
+ foreach (var pitcher in pitchers)
+ {
+ // Decimal portion of innings pitched represents 1/3 of an inning
+ double innings = (double)Math.Truncate(pitcher.Item2);
+ innings = innings + (((double)pitcher.Item2 - innings) * .33);
+
+ double ERA = pitcher.Item4 / innings * 9;
+ double hitsPerInning = pitcher.Item3 / innings;
+ double EI = (ERA * 2 + hitsPerInning * 9) / 3;
+ result = new(pitcher.Item1, ERA, hitsPerInning, EI);
+ list.Add(result);
+ }
+ return list.ToArray();
+ }
}
// The example displays the following output;
// Pitcher ERA Hits/Inn. Effectiveness
-//
+//
// McHale, Joe 3.60 0.92 5.16
// Paul, Dave 3.24 0.99 5.14
// Williams, Mike 4.01 0.95 5.52
@@ -55,4 +52,4 @@ private static Tuple[] ComputeStatistics(Tuple
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index 81c29e178a4..507cec4e02d 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,34 +1,34 @@
//
using System;
-using System.Collections.Generic;
-public class Example
+
+public class CompareToExample1
{
- public static void Main()
- {
- Tuple[] pitchers =
- { Tuple.Create("McHale, Joe", 240.1m, 221, 96),
- Tuple.Create("Paul, Dave", 233.1m, 231, 84),
+ public static void Run()
+ {
+ Tuple[] pitchers =
+ [ Tuple.Create("McHale, Joe", 240.1m, 221, 96),
+ Tuple.Create("Paul, Dave", 233.1m, 231, 84),
Tuple.Create("Williams, Mike", 193.2m, 183, 86),
- Tuple.Create("Blair, Jack", 168.1m, 146, 65),
+ Tuple.Create("Blair, Jack", 168.1m, 146, 65),
Tuple.Create("Henry, Walt", 140.1m, 96, 30),
Tuple.Create("Lee, Adam", 137.2m, 109, 45),
- Tuple.Create("Rohr, Don", 101.0m, 110, 42) };
+ Tuple.Create("Rohr, Don", 101.0m, 110, 42) ];
+
+ // Display the array in unsorted order.
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var pitcher in pitchers)
+ Console.WriteLine(pitcher);
+ Console.WriteLine();
+
+ // Sort the array
+ Array.Sort(pitchers);
- // Display the array in unsorted order.
- Console.WriteLine("The values in unsorted order:");
- foreach (var pitcher in pitchers)
- Console.WriteLine(pitcher.ToString());
- Console.WriteLine();
-
- // Sort the array
- Array.Sort(pitchers);
-
- // Display the array in sorted order.
- Console.WriteLine("The values in sorted order:");
- foreach (var pitcher in pitchers)
- Console.WriteLine(pitcher.ToString());
- }
+ // Display the array in sorted order.
+ Console.WriteLine("The values in sorted order:");
+ foreach (var pitcher in pitchers)
+ Console.WriteLine(pitcher);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -39,7 +39,7 @@ public static void Main()
// (Henry, Walt, 140.1, 96, 30)
// (Lee, Adam, 137.2, 109, 45)
// (Rohr, Don, 101, 110, 42)
-//
+//
// The values in sorted order:
// (Blair, Jack, 168.1, 146, 65)
// (Henry, Walt, 140.1, 96, 30)
@@ -48,4 +48,4 @@ public static void Main()
// (Paul, Dave, 233.1, 231, 84)
// (Rohr, Don, 101, 110, 42)
// (Williams, Mike, 193.2, 183, 86)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index 63ac793f8b2..e865230ce19 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,46 +5,46 @@
public class PitcherComparer : IComparer
{
- public int Compare(object x, object y)
- {
- Tuple tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- Tuple tY = y as Tuple;
- return Comparer.Default.Compare(tX.Item3, tY.Item3);
- }
- }
+ public int Compare(object x, object y)
+ {
+ Tuple tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ Tuple tY = y as Tuple;
+ return Comparer.Default.Compare(tX.Item3, tY.Item3);
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- Tuple[] pitchers =
- { Tuple.Create("McHale, Joe", 240.1, 3.60, 221),
- Tuple.Create("Paul, Dave", 233.1, 3.24, 231),
+ public static void Run()
+ {
+ Tuple[] pitchers =
+ [ Tuple.Create("McHale, Joe", 240.1, 3.60, 221),
+ Tuple.Create("Paul, Dave", 233.1, 3.24, 231),
Tuple.Create("Williams, Mike", 193.2, 4.00, 183),
- Tuple.Create("Blair, Jack", 168.1, 3.48, 146),
+ Tuple.Create("Blair, Jack", 168.1, 3.48, 146),
Tuple.Create("Henry, Walt", 140.1, 1.92, 96),
Tuple.Create("Lee, Adam", 137.2, 2.94, 109),
- Tuple.Create("Rohr, Don", 101.0, 3.74, 110) };
+ Tuple.Create("Rohr, Don", 101.0, 3.74, 110) ];
- Console.WriteLine("The values in unsorted order:");
- foreach (var pitcher in pitchers)
- Console.WriteLine(pitcher.ToString());
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var pitcher in pitchers)
+ Console.WriteLine(pitcher);
- Console.WriteLine();
+ Console.WriteLine();
- Array.Sort(pitchers, new PitcherComparer());
+ Array.Sort(pitchers, new PitcherComparer());
- Console.WriteLine("The values sorted by earned run average (component 3):");
- foreach (var pitcher in pitchers)
- Console.WriteLine(pitcher.ToString());
- }
+ Console.WriteLine("The values sorted by earned run average (component 3):");
+ foreach (var pitcher in pitchers)
+ Console.WriteLine(pitcher);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -55,7 +55,7 @@ public static void Main()
// (Henry, Walt, 140.1, 1.92, 96)
// (Lee, Adam, 137.2, 2.94, 109)
// (Rohr, Don, 101, 3.74, 110)
-//
+//
// The values sorted by earned run average (component 3):
// (Henry, Walt, 140.1, 1.92, 96)
// (Lee, Adam, 137.2, 2.94, 109)
diff --git a/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs
index 009918fab0a..d2763f2aa90 100644
--- a/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3,T4/ToString/tostring1.cs
@@ -3,19 +3,19 @@
public class Example
{
- public static void Main()
- {
- Tuple[] temperatures =
- { Tuple.Create("New York, NY", 4, 61, 43),
- Tuple.Create("Chicago, IL", 2, 34, 18),
+ public static void Main()
+ {
+ Tuple[] temperatures =
+ [ Tuple.Create("New York, NY", 4, 61, 43),
+ Tuple.Create("Chicago, IL", 2, 34, 18),
Tuple.Create("Newark, NJ", 4, 61, 43),
Tuple.Create("Boston, MA", 6, 77, 59),
Tuple.Create("Detroit, MI", 9, 74, 53),
- Tuple.Create("Minneapolis, MN", 8, 81, 61) };
- // Display the array of 4-tuple objects.
- foreach (var temperature in temperatures)
- Console.WriteLine(temperature.ToString());
- }
+ Tuple.Create("Minneapolis, MN", 8, 81, 61) ];
+ // Display the array of 4-tuple objects.
+ foreach (var temperature in temperatures)
+ Console.WriteLine(temperature.ToString());
+ }
}
// The example displays the following output:
// (New York, NY, 4, 61, 43)
@@ -24,4 +24,4 @@ public static void Main()
// (Boston, MA, 6, 77, 59)
// (Detroit, MI, 9, 74, 53)
// (Minneapolis, MN, 8, 81, 61)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs
new file mode 100644
index 00000000000..76c3e934c0b
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/Program.cs
@@ -0,0 +1,2 @@
+EqualsExample1.Run();
+EqualsExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs
index 24aec55f956..8ba5dddad3e 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals1.cs
@@ -1,31 +1,30 @@
//
using System;
-public class Example
+public class EqualsExample1
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Ed", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ public static void Run()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Ed", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Ed", 71.2, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Ed", 71.2, 9),
- Tuple.Create("Judith", 84.3, 9) };
+ Tuple.Create("Judith", 84.3, 9) ];
- // Test each tuple object for equality with every other tuple.
- for (int ctr = 0; ctr < scores.Length; ctr++)
- {
- var currentTuple = scores[ctr];
- for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++)
- Console.WriteLine("{0} = {1}: {2}", currentTuple, scores[ctr2],
- currentTuple.Equals(scores[ctr2]));
+ // Test each tuple object for equality with every other tuple.
+ for (int ctr = 0; ctr < scores.Length; ctr++)
+ {
+ var currentTuple = scores[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++)
+ Console.WriteLine($"{currentTuple} = {scores[ctr2]}: {currentTuple.Equals(scores[ctr2])}");
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output;
// (Ed, 78.8, 8) = (Abbey, 92.1, 9): False
@@ -35,31 +34,31 @@ public static void Main()
// (Ed, 78.8, 8) = (Penelope, 82.9, 8): False
// (Ed, 78.8, 8) = (Ed, 71.2, 9): False
// (Ed, 78.8, 8) = (Judith, 84.3, 9): False
-//
+//
// (Abbey, 92.1, 9) = (Ed, 71.2, 9): False
// (Abbey, 92.1, 9) = (Sam, 91.7, 8): False
// (Abbey, 92.1, 9) = (Ed, 71.2, 5): False
// (Abbey, 92.1, 9) = (Penelope, 82.9, 8): False
// (Abbey, 92.1, 9) = (Ed, 71.2, 9): False
// (Abbey, 92.1, 9) = (Judith, 84.3, 9): False
-//
+//
// (Ed, 71.2, 9) = (Sam, 91.7, 8): False
// (Ed, 71.2, 9) = (Ed, 71.2, 5): False
// (Ed, 71.2, 9) = (Penelope, 82.9, 8): False
// (Ed, 71.2, 9) = (Ed, 71.2, 9): True
// (Ed, 71.2, 9) = (Judith, 84.3, 9): False
-//
+//
// (Sam, 91.7, 8) = (Ed, 71.2, 5): False
// (Sam, 91.7, 8) = (Penelope, 82.9, 8): False
// (Sam, 91.7, 8) = (Ed, 71.2, 9): False
// (Sam, 91.7, 8) = (Judith, 84.3, 9): False
-//
+//
// (Ed, 71.2, 5) = (Penelope, 82.9, 8): False
// (Ed, 71.2, 5) = (Ed, 71.2, 9): False
// (Ed, 71.2, 5) = (Judith, 84.3, 9): False
-//
+//
// (Penelope, 82.9, 8) = (Ed, 71.2, 9): False
// (Penelope, 82.9, 8) = (Judith, 84.3, 9): False
-//
+//
// (Ed, 71.2, 9) = (Judith, 84.3, 9): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs
index dff73822973..23b181ee11c 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/Equals/equals2.cs
@@ -4,55 +4,53 @@
public class Item2Comparer : IEqualityComparer
{
- new public bool Equals(object x, object y)
- {
- // Return true for all values of Item1.
- if (x is T1)
- return true;
- else if (x is T2)
- return x.Equals(y);
- else
- return true;
- }
-
- public int GetHashCode(object obj)
- {
- if (obj is T1)
- return ((T1) obj).GetHashCode();
- else if (obj is T2)
- return ((T2) obj).GetHashCode();
- else
- return ((T3) obj).GetHashCode();
- }
+ new public bool Equals(object x, object y)
+ {
+ // Return true for all values of Item1.
+ if (x is T1)
+ return true;
+ else if (x is T2)
+ return x.Equals(y);
+ else
+ return true;
+ }
+
+ public int GetHashCode(object obj)
+ {
+ if (obj is T1)
+ return ((T1)obj).GetHashCode();
+ else if (obj is T2)
+ return ((T2)obj).GetHashCode();
+ else
+ return ((T3)obj).GetHashCode();
+ }
}
-public class Example
+public class EqualsExample2
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Ed", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ public static void Run()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Ed", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Jim", 71.2, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Sandy", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Serena", 71.2, 9),
- Tuple.Create("Judith", 84.3, 9) };
+ Tuple.Create("Judith", 84.3, 9) ];
- for (int ctr = 0; ctr < scores.Length; ctr++)
- {
- IStructuralEquatable score = scores[ctr];
- for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++)
- {
- Console.WriteLine("{0} = {1}: {2}", score,
- scores[ctr2],
- score.Equals(scores[ctr2],
- new Item2Comparer()));
- }
- Console.WriteLine();
- }
- }
+ for (int ctr = 0; ctr < scores.Length; ctr++)
+ {
+ IStructuralEquatable score = scores[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < scores.Length; ctr2++)
+ {
+ Console.WriteLine($"{score} = {scores[ctr2]}: {score.Equals(scores[ctr2],
+ new Item2Comparer())}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (Ed, 78.8, 8) = (Abbey, 92.1, 9): False
@@ -69,7 +67,7 @@ public static void Main()
// (Abbey, 92.1, 9) = (Penelope, 82.9, 8): False
// (Abbey, 92.1, 9) = (Serena, 71.2, 9): False
// (Abbey, 92.1, 9) = (Judith, 84.3, 9): False
-//
+//
// (Jim, 71.2, 9) = (Sam, 91.7, 8): False
// (Jim, 71.2, 9) = (Sandy, 71.2, 5): True
// (Jim, 71.2, 9) = (Penelope, 82.9, 8): False
@@ -89,4 +87,4 @@ public static void Main()
// (Penelope, 82.9, 8) = (Judith, 84.3, 9): False
//
// (Serena, 71.2, 9) = (Judith, 84.3, 9): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs
index 9a557df905a..1a54d079df8 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/Overview/example1.cs
@@ -1,47 +1,48 @@
-//
-using System;
+using System;
public class Example
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Jack", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ //
+ public static void Main()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Jack", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Dave", 88.3, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Linda", 99.0, 9),
- Tuple.Create("Judith", 84.3, 9) };
- var result = ComputeStatistics(scores);
- Console.WriteLine("Mean score: {0:N2} (SD={1:N2}) (n={2})",
- result.Item2, result.Item3, result.Item1);
- }
+ Tuple.Create("Judith", 84.3, 9) ];
+ var result = ComputeStatistics(scores);
+ Console.WriteLine($"Mean score: {result.Item2:N2} (SD={result.Item3:N2}) (n={result.Item1})");
+ }
- private static Tuple ComputeStatistics(Tuple[] scores)
- {
- int n = 0;
- double sum = 0;
+ private static Tuple ComputeStatistics(Tuple[] scores)
+ {
+ int n = 0;
+ double sum = 0;
- // Compute the mean.
- foreach (var score in scores)
- {
- n += score.Item3;
- sum += score.Item2 * score.Item3;
- }
- double mean = sum / n;
-
- // Compute the standard deviation.
- double ss = 0;
- foreach (var score in scores)
- {
- ss = Math.Pow(score.Item2 - mean, 2);
- }
- double sd = Math.Sqrt(ss/scores.Length);
- return Tuple.Create(scores.Length, mean, sd);
- }
+ // Compute the mean.
+ foreach (Tuple score in scores)
+ {
+ n += score.Item3;
+ sum += score.Item2 * score.Item3;
+ }
+ double mean = sum / n;
+
+ // Compute the standard deviation.
+ double ss = 0;
+ foreach (Tuple score in scores)
+ {
+ ss += Math.Pow(score.Item2 - mean, 2);
+ }
+ double sd = Math.Sqrt(ss / scores.Length);
+ return Tuple.Create(scores.Length, mean, sd);
+ }
+
+ // The example displays the following output:
+ // Mean score: 87.02 (SD=8.18) (n=8)
+
+ //
}
-// The example displays the following output:
-// Mean score: 87.02 (SD=0.96) (n=8)
-//
\ No newline at end of file
diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index a1ad9e789f0..d708ac6b3fb 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,32 +1,32 @@
//
using System;
-public class Example
+public class CompareToExample1
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Jack", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ public static void Run()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Jack", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Dave", 88.3, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Linda", 99.0, 9),
- Tuple.Create("Judith", 84.3, 9) };
+ Tuple.Create("Judith", 84.3, 9) ];
- Console.WriteLine("The values in unsorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
- Console.WriteLine();
+ Console.WriteLine();
- Array.Sort(scores);
+ Array.Sort(scores);
- Console.WriteLine("The values in sorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
- }
+ Console.WriteLine("The values in sorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -38,7 +38,7 @@ public static void Main()
// (Penelope, 82.9, 8)
// (Linda, 99, 9)
// (Judith, 84.3, 9)
-//
+//
// The values in sorted order:
// (Abbey, 92.1, 9)
// (Dave, 88.3, 9)
diff --git a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index 1af88bd54ed..0b9b3e25782 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,47 +5,47 @@
public class ScoreComparer : IComparer
{
- public int Compare(object x, object y)
- {
- Tuple tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- Tuple tY = y as Tuple;
- return Comparer.Default.Compare(tX.Item2, tY.Item2);
- }
- }
+ public int Compare(object x, object y)
+ {
+ Tuple tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ Tuple tY = y as Tuple;
+ return Comparer.Default.Compare(tX.Item2, tY.Item2);
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Jack", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ public static void Run()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Jack", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Dave", 88.3, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Linda", 99.0, 9),
- Tuple.Create("Judith", 84.3, 9) };
+ Tuple.Create("Judith", 84.3, 9) ];
- Console.WriteLine("The values in unsorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
- Console.WriteLine();
+ Console.WriteLine();
- Array.Sort(scores, new ScoreComparer());
+ Array.Sort(scores, new ScoreComparer());
- Console.WriteLine("The values in sorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
- }
+ Console.WriteLine("The values in sorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -57,7 +57,7 @@ public static void Main()
// (Penelope, 82.9, 8)
// (Linda, 99, 9)
// (Judith, 84.3, 9)
-//
+//
// The values in sorted order:
// (Ed, 71.2, 5)
// (Jack, 78.8, 8)
diff --git a/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs
index a42543f6550..832c29ade58 100644
--- a/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2,T3/ToString/tostring1.cs
@@ -3,21 +3,21 @@
public class Example
{
- public static void Main()
- {
- Tuple[] scores =
- { Tuple.Create("Jack", 78.8, 8),
- Tuple.Create("Abbey", 92.1, 9),
+ public static void Main()
+ {
+ Tuple[] scores =
+ [ Tuple.Create("Jack", 78.8, 8),
+ Tuple.Create("Abbey", 92.1, 9),
Tuple.Create("Dave", 88.3, 9),
- Tuple.Create("Sam", 91.7, 8),
+ Tuple.Create("Sam", 91.7, 8),
Tuple.Create("Ed", 71.2, 5),
Tuple.Create("Penelope", 82.9, 8),
Tuple.Create("Linda", 99.0, 9),
- Tuple.Create("Judith", 84.3, 9) };
- Array.Sort(scores);
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
- }
+ Tuple.Create("Judith", 84.3, 9) ];
+ Array.Sort(scores);
+ foreach (var score in scores)
+ Console.WriteLine(score.ToString());
+ }
}
// The example displays the following output;
// (Abbey, 92.1, 9)
diff --git a/snippets/csharp/System/TupleT1,T2/Equals/Program.cs b/snippets/csharp/System/TupleT1,T2/Equals/Program.cs
new file mode 100644
index 00000000000..76c3e934c0b
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2/Equals/Program.cs
@@ -0,0 +1,2 @@
+EqualsExample1.Run();
+EqualsExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj b/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2/Equals/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs b/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs
index 9ccf93e354a..0ca2da4557f 100644
--- a/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs
+++ b/snippets/csharp/System/TupleT1,T2/Equals/equals1.cs
@@ -1,30 +1,28 @@
//
using System;
-public class Example
+public class EqualsExample1
{
- public static void Main()
- {
- Tuple>[] scores =
- { new Tuple>("Dan", 90),
+ public static void Run()
+ {
+ Tuple>[] scores =
+ [ new Tuple>("Dan", 90),
new Tuple>("Ernie", null),
new Tuple>("Jill", 88),
- new Tuple>("Ernie", null),
- new Tuple>("Nancy", 88),
- new Tuple>("Dan", 90) };
+ new Tuple>("Ernie", null),
+ new Tuple>("Nancy", 88),
+ new Tuple>("Dan", 90) ];
- // Compare the Tuple objects
- for (int ctr = 0; ctr < scores.Length; ctr++)
- {
- for (int innerCtr = ctr + 1; innerCtr < scores.Length; innerCtr++)
- {
- Console.WriteLine("{0} = {1}: {2}",
- scores[ctr], scores[innerCtr],
- scores[ctr].Equals(scores[innerCtr]));
- }
- Console.WriteLine();
- }
- }
+ // Compare the Tuple objects
+ for (int ctr = 0; ctr < scores.Length; ctr++)
+ {
+ for (int innerCtr = ctr + 1; innerCtr < scores.Length; innerCtr++)
+ {
+ Console.WriteLine($"{scores[ctr]} = {scores[innerCtr]}: {scores[ctr].Equals(scores[innerCtr])}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (Dan, 90) = (Ernie, ): False
@@ -32,18 +30,18 @@ public static void Main()
// (Dan, 90) = (Ernie, ): False
// (Dan, 90) = (Nancy, 88): False
// (Dan, 90) = (Dan, 90): True
-//
+//
// (Ernie, ) = (Jill, 88): False
// (Ernie, ) = (Ernie, ): True
// (Ernie, ) = (Nancy, 88): False
// (Ernie, ) = (Dan, 90): False
-//
+//
// (Jill, 88) = (Ernie, ): False
// (Jill, 88) = (Nancy, 88): False
// (Jill, 88) = (Dan, 90): False
-//
+//
// (Ernie, ) = (Nancy, 88): False
// (Ernie, ) = (Dan, 90): False
-//
+//
// (Nancy, 88) = (Dan, 90): False
//
diff --git a/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs b/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs
index f045c09c1c3..dc343a7d775 100644
--- a/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs
+++ b/snippets/csharp/System/TupleT1,T2/Equals/equals2.cs
@@ -4,61 +4,59 @@
public class Item2Comparer : IEqualityComparer
{
- new public bool Equals(object x, object y)
- {
- // Return true for all values of Item1.
- if (x is T1)
- //if (typeof(x) is string)
- return true;
- else
- return x.Equals(y);
- }
-
- public int GetHashCode(object obj)
- {
- if (obj is T1)
- return ((T1) obj).GetHashCode();
- else
- return ((T2) obj).GetHashCode();
- }
+ new public bool Equals(object x, object y)
+ {
+ // Return true for all values of Item1.
+ if (x is T1)
+ //if (typeof(x) is string)
+ return true;
+ else
+ return x.Equals(y);
+ }
+
+ public int GetHashCode(object obj)
+ {
+ if (obj is T1)
+ return ((T1)obj).GetHashCode();
+ else
+ return ((T2)obj).GetHashCode();
+ }
}
-public class Example
+public class EqualsExample2
{
- public static void Main()
- {
- Tuple[] distancesWalked = {
- Tuple.Create("Jan", Double.NaN),
- Tuple.Create("Joe", Double.NaN),
- Tuple.Create("Adam", 1.36),
+ public static void Run()
+ {
+ Tuple[] distancesWalked = [
+ Tuple.Create("Jan", double.NaN),
+ Tuple.Create("Joe", double.NaN),
+ Tuple.Create("Adam", 1.36),
Tuple.Create("Selena", 2.01),
- Tuple.Create("Jake", 1.36) };
- for (int ctr = 0; ctr < distancesWalked.Length; ctr++)
- {
- Tuple distanceWalked = distancesWalked[ctr];
- for (int ctr2 = ctr + 1; ctr2 < distancesWalked.Length; ctr2++)
- {
- Console.WriteLine("{0} = {1}: {2}", distanceWalked,
- distancesWalked[ctr2],
- ((IStructuralEquatable)distanceWalked).Equals(distancesWalked[ctr2],
- new Item2Comparer()));
- }
- Console.WriteLine();
- }
- }
+ Tuple.Create("Jake", 1.36) ];
+ for (int ctr = 0; ctr < distancesWalked.Length; ctr++)
+ {
+ Tuple distanceWalked = distancesWalked[ctr];
+ for (int ctr2 = ctr + 1; ctr2 < distancesWalked.Length; ctr2++)
+ {
+ Console.WriteLine($"{distanceWalked} = {distancesWalked[ctr2]}: {((IStructuralEquatable)distanceWalked).Equals(distancesWalked[ctr2],
+ new Item2Comparer())}");
+ }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// (Jan, NaN) = (Joe, NaN): True
// (Jan, NaN) = (Adam, 1.36): False
// (Jan, NaN) = (Selena, 2.01): False
// (Jan, NaN) = (Jake, 1.36): False
-//
+//
// (Joe, NaN) = (Adam, 1.36): False
// (Joe, NaN) = (Selena, 2.01): False
// (Joe, NaN) = (Jake, 1.36): False
-//
+//
// (Adam, 1.36) = (Selena, 2.01): False
// (Adam, 1.36) = (Jake, 1.36): True
-//
+//
// (Selena, 2.01) = (Jake, 1.36): False
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2/Overview/example1.cs b/snippets/csharp/System/TupleT1,T2/Overview/example1.cs
index a1a02fcecdc..02dc697b4e3 100644
--- a/snippets/csharp/System/TupleT1,T2/Overview/example1.cs
+++ b/snippets/csharp/System/TupleT1,T2/Overview/example1.cs
@@ -3,40 +3,40 @@
public class Example
{
- public static void Main()
- {
- Tuple>[] scores =
- { new Tuple>("Jack", 78),
- new Tuple>("Abbey", 92),
+ public static void Main()
+ {
+ Tuple>[] scores =
+ [ new Tuple>("Jack", 78),
+ new Tuple>("Abbey", 92),
new Tuple>("Dave", 88),
- new Tuple>("Sam", 91),
+ new Tuple>("Sam", 91),
new Tuple>("Ed", null),
new Tuple>("Penelope", 82),
new Tuple>("Linda", 99),
- new Tuple>("Judith", 84) };
- int number;
- double mean = ComputeMean(scores, out number);
- Console.WriteLine("Average test score: {0:N2} (n={1})", mean, number);
- }
+ new Tuple>("Judith", 84) ];
+ int number;
+ double mean = ComputeMean(scores, out number);
+ Console.WriteLine($"Average test score: {mean:N2} (n={number})");
+ }
- private static double ComputeMean(Tuple>[] scores, out int n)
- {
- n = 0;
- int sum = 0;
- foreach (var score in scores)
- {
- if (score.Item2.HasValue)
- {
- n += 1;
- sum += score.Item2.Value;
- }
- }
- if (n > 0)
- return sum / (double) n;
- else
- return 0;
- }
+ private static double ComputeMean(Tuple>[] scores, out int n)
+ {
+ n = 0;
+ int sum = 0;
+ foreach (var score in scores)
+ {
+ if (score.Item2.HasValue)
+ {
+ n += 1;
+ sum += score.Item2.Value;
+ }
+ }
+ if (n > 0)
+ return sum / (double)n;
+ else
+ return 0;
+ }
}
// The example displays the following output:
// Average test score: 87.71 (n=7)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2/Overview/item1.cs b/snippets/csharp/System/TupleT1,T2/Overview/item1.cs
index a57aef25409..c861a905a2d 100644
--- a/snippets/csharp/System/TupleT1,T2/Overview/item1.cs
+++ b/snippets/csharp/System/TupleT1,T2/Overview/item1.cs
@@ -3,41 +3,41 @@
public class Class1
{
- public static void Main()
- {
- int dividend, divisor;
- Tuple result;
-
- dividend = 136945; divisor = 178;
- result = IntegerDivide(dividend, divisor);
- if (result != null)
- Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
- dividend, divisor, result.Item1, result.Item2);
- else
- Console.WriteLine(@"{0} \ {1} = ", dividend, divisor);
-
- dividend = Int32.MaxValue; divisor = -2073;
- result = IntegerDivide(dividend, divisor);
- if (result != null)
- Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
- dividend, divisor, result.Item1, result.Item2);
- else
- Console.WriteLine(@"{0} \ {1} = ", dividend, divisor);
- }
+ public static void Main()
+ {
+ int dividend, divisor;
+ Tuple result;
- private static Tuple IntegerDivide(int dividend, int divisor)
- {
- try {
- int remainder;
- int quotient = Math.DivRem(dividend, divisor, out remainder);
- return new Tuple(quotient, remainder);
- }
- catch (DivideByZeroException) {
- return null;
- }
- }
+ dividend = 136945; divisor = 178;
+ result = IntegerDivide(dividend, divisor);
+ if (result != null)
+ Console.WriteLine($"{dividend} \\ {divisor} = {result.Item1}, remainder {result.Item2}");
+ else
+ Console.WriteLine($"{dividend} \\ {divisor} = ");
+
+ dividend = int.MaxValue; divisor = -2073;
+ result = IntegerDivide(dividend, divisor);
+ if (result != null)
+ Console.WriteLine($"{dividend} \\ {divisor} = {result.Item1}, remainder {result.Item2}");
+ else
+ Console.WriteLine($"{dividend} \\ {divisor} = ");
+ }
+
+ private static Tuple IntegerDivide(int dividend, int divisor)
+ {
+ try
+ {
+ int remainder;
+ int quotient = Math.DivRem(dividend, divisor, out remainder);
+ return new Tuple(quotient, remainder);
+ }
+ catch (DivideByZeroException)
+ {
+ return null;
+ }
+ }
}
// The example displays the following output:
// 136945 \ 178 = 769, remainder 63
// 2147483647 \ -2073 = -1035930, remainder 757
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs
new file mode 100644
index 00000000000..e84b3c44eae
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Program.cs
@@ -0,0 +1,2 @@
+CompareToExample1.Run();
+CompareToExample2.Run();
diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj
new file mode 100644
index 00000000000..36a29620edb
--- /dev/null
+++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/Project.csproj
@@ -0,0 +1,6 @@
+
+
+ Exe
+ net10.0
+
+
diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
index d0996174ea7..73b2143e66d 100644
--- a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
+++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto1.cs
@@ -1,32 +1,32 @@
//
using System;
-public class Example
+public class CompareToExample1
{
- public static void Main()
- {
- Tuple>[] scores =
- { new Tuple>("Jack", 78),
- new Tuple>("Abbey", 92),
+ public static void Run()
+ {
+ Tuple>[] scores =
+ [ new Tuple>("Jack", 78),
+ new Tuple>("Abbey", 92),
new Tuple>("Dave", 88),
- new Tuple>("Sam", 91),
+ new Tuple>("Sam", 91),
new Tuple>("Ed", null),
new Tuple>("Penelope", 82),
new Tuple>("Linda", 99),
- new Tuple>("Judith", 84) };
+ new Tuple>("Judith", 84) ];
- Console.WriteLine("The values in unsorted order:");
- foreach (Tuple> score in scores)
- Console.WriteLine(score.ToString());
+ Console.WriteLine("The values in unsorted order:");
+ foreach (Tuple> score in scores)
+ Console.WriteLine(score);
- Console.WriteLine();
+ Console.WriteLine();
- Array.Sort(scores);
+ Array.Sort(scores);
- Console.WriteLine("The values in sorted order:");
- foreach (Tuple> score in scores)
- Console.WriteLine(score.ToString());
- }
+ Console.WriteLine("The values in sorted order:");
+ foreach (Tuple> score in scores)
+ Console.WriteLine(score);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -38,7 +38,7 @@ public static void Main()
// (Penelope, 82)
// (Linda, 99)
// (Judith, 84)
-//
+//
// The values in sorted order:
// (Abbey, 92)
// (Dave, 88)
diff --git a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
index 10f13edf8ca..7cc9e07b8c3 100644
--- a/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
+++ b/snippets/csharp/System/TupleT1,T2/System.Collections.IStructuralComparable.CompareTo/compareto2.cs
@@ -5,47 +5,47 @@
public class ScoreComparer : IComparer
{
- public int Compare(object x, object y)
- {
- Tuple tX = x as Tuple;
- if (tX == null)
- {
- return 0;
- }
- else
- {
- Tuple tY = y as Tuple;
- return Comparer.Default.Compare(tX.Item2, tY.Item2);
- }
- }
+ public int Compare(object x, object y)
+ {
+ Tuple tX = x as Tuple;
+ if (tX == null)
+ {
+ return 0;
+ }
+ else
+ {
+ Tuple tY = y as Tuple;
+ return Comparer.Default.Compare(tX.Item2, tY.Item2);
+ }
+ }
}
-public class Example
+public class CompareToExample2
{
- public static void Main()
- {
- Tuple>[] scores =
- { new Tuple>("Jack", 78),
- new Tuple>("Abbey", 92),
+ public static void Run()
+ {
+ Tuple>[] scores =
+ [ new Tuple>("Jack", 78),
+ new Tuple>("Abbey", 92),
new Tuple>("Dave", 88),
- new Tuple>("Sam", 91),
+ new Tuple>("Sam", 91),
new Tuple>("Ed", null),
new Tuple>("Penelope", 82),
new Tuple>("Linda", 99),
- new Tuple>("Judith", 84) };
+ new Tuple>("Judith", 84) ];
- Console.WriteLine("The values in unsorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
+ Console.WriteLine("The values in unsorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
- Console.WriteLine();
+ Console.WriteLine();
- Array.Sort(scores, new ScoreComparer>());
+ Array.Sort(scores, new ScoreComparer>());
- Console.WriteLine("The values in sorted order:");
- foreach (var score in scores)
- Console.WriteLine(score.ToString());
- }
+ Console.WriteLine("The values in sorted order:");
+ foreach (var score in scores)
+ Console.WriteLine(score);
+ }
}
// The example displays the following output;
// The values in unsorted order:
@@ -57,7 +57,7 @@ public static void Main()
// (Penelope, 82)
// (Linda, 99)
// (Judith, 84)
-//
+//
// The values in sorted order:
// (Ed, )
// (Jack, 78)
diff --git a/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs b/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs
index 47d86b30856..0356a33334f 100644
--- a/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs
+++ b/snippets/csharp/System/TupleT1,T2/ToString/tostring1.cs
@@ -3,20 +3,20 @@
public class Class1
{
- public static void Main()
- {
- Tuple>[] scores =
- { new Tuple>("Abbey", 92),
+ public static void Main()
+ {
+ Tuple>[] scores =
+ [ new Tuple