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:
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/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs b/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs
index 3e245b91d86..f93cd9ac9f4 100644
--- a/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs
+++ b/snippets/csharp/System/ParamArrayAttribute/Overview/Example.cs
@@ -3,81 +3,75 @@
public class Temperature
{
- private decimal temp;
+ private decimal temp;
- public Temperature(decimal temperature)
- {
- this.temp = temperature;
- }
+ public Temperature(decimal temperature) => this.temp = temperature;
- public override string ToString()
- {
- return ToString("C");
- }
+ public override string ToString() => ToString("C");
- public string ToString(string format)
- {
- if (String.IsNullOrEmpty(format))
- format = "G";
+ public string ToString(string format)
+ {
+ if (string.IsNullOrEmpty(format))
+ format = "G";
- switch (format.ToUpper())
- {
- case "G":
- case "C":
- return temp.ToString("N") + " °C";
- case "F":
- return (9 * temp / 5 + 32).ToString("N") + " °F";
- case "K":
- return (temp + 273.15m).ToString("N") + " °K";
- default:
- throw new FormatException(String.Format("The '{0}' format specifier is not supported",
- format));
- }
- }
+ switch (format.ToUpperInvariant())
+ {
+ case "G":
+ case "C":
+ return temp.ToString("N") + " °C";
+ case "F":
+ return (9 * temp / 5 + 32).ToString("N") + " °F";
+ case "K":
+ return (temp + 273.15m).ToString("N") + " °K";
+ default:
+ throw new FormatException($"The '{format}' format specifier is not supported");
+ }
+ }
- public void Display(params string []formats)
- {
- if (formats.Length == 0)
- {
- Console.WriteLine(this.ToString("G"));
- }
- else
- {
- foreach (string format in formats)
- {
- try {
- Console.WriteLine(this.ToString(format));
+ public void Display(params string[] formats)
+ {
+ if (formats.Length == 0)
+ {
+ Console.WriteLine(this.ToString("G"));
+ }
+ else
+ {
+ foreach (string format in formats)
+ {
+ try
+ {
+ Console.WriteLine(this.ToString(format));
+ }
+ // If there is an exception, do nothing.
+ catch { }
}
- // If there is an exception, do nothing.
- catch { }
- }
- }
- }
+ }
+ }
}
//
//
public class Class1
{
- public static void Main()
- {
- Temperature temp1 = new Temperature(100);
- string[] formats = { "C", "G", "F", "K" };
+ public static void Main()
+ {
+ Temperature temp1 = new(100);
+ string[] formats = [ "C", "G", "F", "K" ];
- // Call Display method with a string array.
- Console.WriteLine("Calling Display with a string array:");
- temp1.Display(formats);
- Console.WriteLine();
+ // Call Display method with a string array.
+ Console.WriteLine("Calling Display with a string array:");
+ temp1.Display(formats);
+ Console.WriteLine();
- // Call Display method with individual string arguments.
- Console.WriteLine("Calling Display with individual arguments:");
- temp1.Display("C", "F", "K", "G");
- Console.WriteLine();
+ // Call Display method with individual string arguments.
+ Console.WriteLine("Calling Display with individual arguments:");
+ temp1.Display("C", "F", "K", "G");
+ Console.WriteLine();
- // Call parameterless Display method.
- Console.WriteLine("Calling Display with an implicit parameter array:");
- temp1.Display();
- }
+ // Call parameterless Display method.
+ Console.WriteLine("Calling Display with an implicit parameter array:");
+ temp1.Display();
+ }
}
// The example displays the following output:
// Calling Display with a string array:
diff --git a/snippets/csharp/System/PlatformID/Overview/pid.cs b/snippets/csharp/System/PlatformID/Overview/pid.cs
index 0f3f208e9d6..f93b59ce4f9 100644
--- a/snippets/csharp/System/PlatformID/Overview/pid.cs
+++ b/snippets/csharp/System/PlatformID/Overview/pid.cs
@@ -6,28 +6,28 @@ class Sample
{
public static void Main()
{
- string msg1 = "This is a Windows operating system.";
- string msg2 = "This is a Unix operating system.";
- string msg3 = "ERROR: This platform identifier is invalid.";
+ string msg1 = "This is a Windows operating system.";
+ string msg2 = "This is a Unix operating system.";
+ string msg3 = "ERROR: This platform identifier is invalid.";
-// Assume this example is run on a Windows operating system.
+ // Assume this example is run on a Windows operating system.
- OperatingSystem os = Environment.OSVersion;
- PlatformID pid = os.Platform;
- switch (pid)
+ OperatingSystem os = Environment.OSVersion;
+ PlatformID pid = os.Platform;
+ switch (pid)
{
- case PlatformID.Win32NT:
- case PlatformID.Win32S:
- case PlatformID.Win32Windows:
- case PlatformID.WinCE:
- Console.WriteLine(msg1);
- break;
- case PlatformID.Unix:
- Console.WriteLine(msg2);
- break;
- default:
- Console.WriteLine(msg3);
- break;
+ case PlatformID.Win32NT:
+ case PlatformID.Win32S:
+ case PlatformID.Win32Windows:
+ case PlatformID.WinCE:
+ Console.WriteLine(msg1);
+ break;
+ case PlatformID.Unix:
+ Console.WriteLine(msg2);
+ break;
+ default:
+ Console.WriteLine(msg3);
+ break;
}
}
}
@@ -36,4 +36,4 @@ public static void Main()
This is a Windows operating system.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/PredicateT/Overview/Project.csproj b/snippets/csharp/System/PredicateT/Overview/Project.csproj
new file mode 100644
index 00000000000..dfdef3fd2a7
--- /dev/null
+++ b/snippets/csharp/System/PredicateT/Overview/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Library
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/PredicateT/Overview/predicate1.cs b/snippets/csharp/System/PredicateT/Overview/predicate1.cs
index a70880bda97..99512cdf2a4 100644
--- a/snippets/csharp/System/PredicateT/Overview/predicate1.cs
+++ b/snippets/csharp/System/PredicateT/Overview/predicate1.cs
@@ -1,44 +1,42 @@
-//
+namespace PredicateExample3;
+
+//
using System;
using System.Collections.Generic;
public class HockeyTeam
{
- private string _name;
- private int _founded;
+ private string _name;
+ private int _founded;
- public HockeyTeam(string name, int year)
- {
- _name = name;
- _founded = year;
- }
+ public HockeyTeam(string name, int year)
+ {
+ _name = name;
+ _founded = year;
+ }
- public string Name {
- get { return _name; }
- }
+ public string Name => _name;
- public int Founded {
- get { return _founded; }
- }
+ public int Founded => _founded;
}
public class Example
{
- public static void Main()
- {
- Random rnd = new Random();
- List teams = new List();
- teams.AddRange( new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926),
+ public static void Main()
+ {
+ Random rnd = new();
+ List teams = new();
+ teams.AddRange(new HockeyTeam[] { new HockeyTeam("Detroit Red Wings", 1926),
new HockeyTeam("Chicago Blackhawks", 1926),
new HockeyTeam("San Jose Sharks", 1991),
new HockeyTeam("Montreal Canadiens", 1909),
- new HockeyTeam("St. Louis Blues", 1967) } );
- int[] years = { 1920, 1930, 1980, 2000 };
- int foundedBeforeYear = years[rnd.Next(0, years.Length)];
- Console.WriteLine("Teams founded before {0}:", foundedBeforeYear);
- foreach (var team in teams.FindAll( x => x.Founded <= foundedBeforeYear))
- Console.WriteLine("{0}: {1}", team.Name, team.Founded);
- }
+ new HockeyTeam("St. Louis Blues", 1967) });
+ int[] years = { 1920, 1930, 1980, 2000 };
+ int foundedBeforeYear = years[rnd.Next(0, years.Length)];
+ Console.WriteLine($"Teams founded before {foundedBeforeYear}:");
+ foreach (var team in teams.FindAll(x => x.Founded <= foundedBeforeYear))
+ Console.WriteLine($"{team.Name}: {team.Founded}");
+ }
}
// The example displays output similar to the following:
// Teams founded before 1930:
diff --git a/snippets/csharp/System/PredicateT/Overview/predicateex1.cs b/snippets/csharp/System/PredicateT/Overview/predicateex1.cs
index dfe5e2b61f9..fb66c274e66 100644
--- a/snippets/csharp/System/PredicateT/Overview/predicateex1.cs
+++ b/snippets/csharp/System/PredicateT/Overview/predicateex1.cs
@@ -1,23 +1,25 @@
-//
+namespace PredicateExample2;
+
+//
using System;
using System.Drawing;
public class Example
{
- public static void Main()
- {
- // Create an array of Point structures.
- Point[] points = { new Point(100, 200),
+ public static void Main()
+ {
+ // Create an array of Point structures.
+ Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
- // Find the first Point structure for which X times Y
- // is greater than 100000.
- Point first = Array.Find(points, x => x.X * x.Y > 100000 );
+ // Find the first Point structure for which X times Y
+ // is greater than 100000.
+ Point first = Array.Find(points, x => x.X * x.Y > 100000);
- // Display the first structure found.
- Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
- }
+ // Display the first structure found.
+ Console.WriteLine($"Found: X = {first.X}, Y = {first.Y}");
+ }
}
// The example displays the following output:
// Found: X = 275, Y = 395
diff --git a/snippets/csharp/System/PredicateT/Overview/predicateex2.cs b/snippets/csharp/System/PredicateT/Overview/predicateex2.cs
index bcba19c7089..9b89982d5e2 100644
--- a/snippets/csharp/System/PredicateT/Overview/predicateex2.cs
+++ b/snippets/csharp/System/PredicateT/Overview/predicateex2.cs
@@ -1,31 +1,30 @@
-//
+namespace PredicateExample4;
+
+//
using System;
using System.Drawing;
public class Example
{
- public static void Main()
- {
- // Create an array of Point structures.
- Point[] points = { new Point(100, 200),
+ public static void Main()
+ {
+ // Create an array of Point structures.
+ Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
- // Define the Predicate delegate.
- Predicate predicate = FindPoints;
+ // Define the Predicate delegate.
+ Predicate predicate = FindPoints;
- // Find the first Point structure for which X times Y
- // is greater than 100000.
- Point first = Array.Find(points, predicate);
+ // Find the first Point structure for which X times Y
+ // is greater than 100000.
+ Point first = Array.Find(points, predicate);
- // Display the first structure found.
- Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
- }
+ // Display the first structure found.
+ Console.WriteLine($"Found: X = {first.X}, Y = {first.Y}");
+ }
- private static bool FindPoints(Point obj)
- {
- return obj.X * obj.Y > 100000;
- }
+ private static bool FindPoints(Point obj) => obj.X * obj.Y > 100000;
}
// The example displays the following output:
// Found: X = 275, Y = 395
diff --git a/snippets/csharp/System/Random/.ctor/ctor.cs b/snippets/csharp/System/Random/.ctor/ctor.cs
index 7c9875c8f70..5239b2c5fe9 100644
--- a/snippets/csharp/System/Random/.ctor/ctor.cs
+++ b/snippets/csharp/System/Random/.ctor/ctor.cs
@@ -10,13 +10,13 @@ public class RandomObjectDemo
static void RunIntNDoubleRandoms(Random randObj)
{
// Generate the first six random integers.
- for(int j = 0; j < 6; j++)
- Console.Write(" {0,10} ", randObj.Next());
+ for (int j = 0; j < 6; j++)
+ Console.Write($" {randObj.Next(),10} ");
Console.WriteLine();
// Generate the first six random doubles.
- for(int j = 0; j < 6; j++)
- Console.Write(" {0:F8} ", randObj.NextDouble());
+ for (int j = 0; j < 6; j++)
+ Console.Write($" {randObj.NextDouble():F8} ");
Console.WriteLine();
}
@@ -26,7 +26,7 @@ static void FixedSeedRandoms(int seed)
Console.WriteLine(
"\nRandom numbers from a Random object with " +
"seed = {0}:", seed);
- Random fixRand = new Random(seed);
+ Random fixRand = new(seed);
RunIntNDoubleRandoms(fixRand);
}
@@ -40,13 +40,13 @@ static void AutoSeedRandoms()
Console.WriteLine(
"\nRandom numbers from a Random object " +
"with an auto-generated seed:");
- Random autoRand = new Random();
+ Random autoRand = new();
RunIntNDoubleRandoms(autoRand);
}
static void Main()
- {
+ {
Console.WriteLine(
"This example of the Random class constructors and " +
"Random.NextDouble() \n" +
@@ -108,19 +108,19 @@ 0.04937517 0.44618494 0.83879212 0.43139707 0.36163507 0.11024451
// same timer value that will produce unique random number sequences.
public class FixTimerResolution
{
- public static void CreateEnginesWithSameTimer()
- {
-//
- int randomInstancesToCreate = 4;
- Random[] randomEngines = new Random[randomInstancesToCreate];
- for (int ctr = 0; ctr < randomInstancesToCreate; ctr++)
- {
- randomEngines[ctr] = new Random(unchecked((int) (DateTime.Now.Ticks >> ctr)));
- }
-//
- for (int ctr = 0; ctr < randomInstancesToCreate; ctr++)
- {
- Console.WriteLine(randomEngines[ctr].Next());
- }
- }
+ public static void CreateEnginesWithSameTimer()
+ {
+ //
+ int randomInstancesToCreate = 4;
+ Random[] randomEngines = new Random[randomInstancesToCreate];
+ for (int ctr = 0; ctr < randomInstancesToCreate; ctr++)
+ {
+ randomEngines[ctr] = new(unchecked((int)(DateTime.Now.Ticks >> ctr)));
+ }
+ //
+ for (int ctr = 0; ctr < randomInstancesToCreate; ctr++)
+ {
+ Console.WriteLine(randomEngines[ctr].Next());
+ }
+ }
}
diff --git a/snippets/csharp/System/Random/.ctor/ctor1.cs b/snippets/csharp/System/Random/.ctor/ctor1.cs
index e9e61383e04..ede86d28b58 100644
--- a/snippets/csharp/System/Random/.ctor/ctor1.cs
+++ b/snippets/csharp/System/Random/.ctor/ctor1.cs
@@ -4,26 +4,26 @@
public class RandomNumbers
{
- public static void Main()
- {
- Random rand1 = new Random();
- Random rand2 = new Random();
- Thread.Sleep(2000);
- Random rand3 = new Random();
- ShowRandomNumbers(rand1);
- ShowRandomNumbers(rand2);
- ShowRandomNumbers(rand3);
- }
+ public static void Main()
+ {
+ Random rand1 = new();
+ Random rand2 = new();
+ Thread.Sleep(2000);
+ Random rand3 = new();
+ ShowRandomNumbers(rand1);
+ ShowRandomNumbers(rand2);
+ ShowRandomNumbers(rand3);
+ }
- private static void ShowRandomNumbers(Random rand)
- {
- Console.WriteLine();
- byte[] values = new byte[5];
- rand.NextBytes(values);
- foreach (byte value in values)
- Console.Write("{0, 5}", value);
- Console.WriteLine();
- }
+ private static void ShowRandomNumbers(Random rand)
+ {
+ Console.WriteLine();
+ byte[] values = new byte[5];
+ rand.NextBytes(values);
+ foreach (byte value in values)
+ Console.Write($"{value,5}");
+ Console.WriteLine();
+ }
}
// The example displays an output similar to the following:
// 28 35 133 224 58
@@ -31,4 +31,4 @@ private static void ShowRandomNumbers(Random rand)
// 28 35 133 224 58
//
// 32 222 43 251 49
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/Random/.ctor/ctor4.cs b/snippets/csharp/System/Random/.ctor/ctor4.cs
index 01b219da8e5..9358c8f9141 100644
--- a/snippets/csharp/System/Random/.ctor/ctor4.cs
+++ b/snippets/csharp/System/Random/.ctor/ctor4.cs
@@ -4,27 +4,27 @@
public class Example
{
- public static void Main()
- {
- Random rand1 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
- Random rand2 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
- Thread.Sleep(20);
- Random rand3 = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
- ShowRandomNumbers(rand1);
- ShowRandomNumbers(rand2);
- ShowRandomNumbers(rand3);
- }
+ public static void Main()
+ {
+ Random rand1 = new((int)DateTime.Now.Ticks & 0x0000FFFF);
+ Random rand2 = new((int)DateTime.Now.Ticks & 0x0000FFFF);
+ Thread.Sleep(20);
+ Random rand3 = new((int)DateTime.Now.Ticks & 0x0000FFFF);
+ ShowRandomNumbers(rand1);
+ ShowRandomNumbers(rand2);
+ ShowRandomNumbers(rand3);
+ }
- private static void ShowRandomNumbers(Random rand)
- {
- Console.WriteLine();
- byte[] values = new byte[4];
- rand.NextBytes(values);
- foreach (var value in values)
- Console.Write("{0, 5}", value);
+ private static void ShowRandomNumbers(Random rand)
+ {
+ Console.WriteLine();
+ byte[] values = new byte[4];
+ rand.NextBytes(values);
+ foreach (byte value in values)
+ Console.Write($"{value,5}");
- Console.WriteLine();
- }
+ Console.WriteLine();
+ }
}
// The example displays output similar to the following:
// 145 214 177 134 173
diff --git a/snippets/csharp/System/Random/Next/sample.cs b/snippets/csharp/System/Random/Next/sample.cs
index 75ce9349484..ef7ff03ff47 100644
--- a/snippets/csharp/System/Random/Next/sample.cs
+++ b/snippets/csharp/System/Random/Next/sample.cs
@@ -7,31 +7,25 @@ public class RandomProportional : Random
{
// The Sample method generates a distribution proportional to the value
// of the random numbers, in the range [0.0, 1.0].
- protected override double Sample()
- {
- return Math.Sqrt(base.Sample());
- }
+ protected override double Sample() => Math.Sqrt(base.Sample());
- public override int Next()
- {
- return (int) (Sample() * int.MaxValue);
- }
+ public override int Next() => (int)(Sample() * int.MaxValue);
}
public class RandomSampleDemo
{
static void Main()
- {
+ {
const int rows = 4, cols = 6;
const int runCount = 1000000;
const int distGroupCount = 10;
const double intGroupSize =
((double)int.MaxValue + 1.0) / (double)distGroupCount;
- RandomProportional randObj = new RandomProportional();
+ RandomProportional randObj = new();
- int[ ] intCounts = new int[ distGroupCount ];
- int[ ] realCounts = new int[ distGroupCount ];
+ int[] intCounts = new int[distGroupCount];
+ int[] realCounts = new int[distGroupCount];
Console.WriteLine(
"\nThe derived RandomProportional class overrides " +
@@ -49,7 +43,7 @@ static void Main()
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
- Console.Write("{0,12:F8}", randObj.NextDouble());
+ Console.Write($"{randObj.NextDouble(),12:F8}");
Console.WriteLine();
}
@@ -61,7 +55,7 @@ static void Main()
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
- Console.Write("{0,12}", randObj.Next());
+ Console.Write($"{randObj.Next(),12}");
Console.WriteLine();
}
@@ -71,33 +65,22 @@ static void Main()
"into {1} equal value ranges. This \n" +
"is the count of values in each range:\n",
runCount, distGroupCount);
- Console.WriteLine(
- "{0,21}{1,10}{2,20}{3,10}", "Integer Range",
- "Count", "Double Range", "Count");
- Console.WriteLine(
- "{0,21}{1,10}{2,20}{3,10}", "-------------",
- "-----", "------------", "-----");
+ Console.WriteLine($"{"Integer Range",21}{"Count",10}{"Double Range",20}{"Count",10}");
+ Console.WriteLine($"{"-------------",21}{"-----",10}{"------------",20}{"-----",10}");
// Generate random integers and doubles, and then count
// them by group.
for (int i = 0; i < runCount; i++)
{
- intCounts[ (int)((double)randObj.Next() /
- intGroupSize) ]++;
- realCounts[ (int)(randObj.NextDouble() *
- (double)distGroupCount) ]++;
+ intCounts[(int)((double)randObj.Next() /
+ intGroupSize)]++;
+ realCounts[(int)(randObj.NextDouble() *
+ (double)distGroupCount)]++;
}
// Display the count of each group.
for (int i = 0; i < distGroupCount; i++)
- Console.WriteLine(
- "{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}",
- (int)((double)i * intGroupSize),
- (int)((double)(i + 1) * intGroupSize - 1.0),
- intCounts[ i ],
- ((double)i) / (double)distGroupCount,
- ((double)(i + 1)) / (double)distGroupCount,
- realCounts[ i ]);
+ Console.WriteLine($"{(int)((double)i * intGroupSize),10}-{(int)((double)(i + 1) * intGroupSize - 1.0),10}{intCounts[i],10:N0}{((double)i) / (double)distGroupCount,12:N5}-{((double)(i + 1)) / (double)distGroupCount,7:N5}{realCounts[i],10:N0}");
}
}
diff --git a/snippets/csharp/System/Random/NextBytes/source.cs b/snippets/csharp/System/Random/NextBytes/source.cs
index 5f05b24328f..d340bd97112 100644
--- a/snippets/csharp/System/Random/NextBytes/source.cs
+++ b/snippets/csharp/System/Random/NextBytes/source.cs
@@ -5,12 +5,12 @@ public class Example
public static void Main()
{
//
- Random rnd = new Random();
- Byte[] b = new Byte[10];
+ Random rnd = new();
+ byte[] b = new byte[10];
rnd.NextBytes(b);
Console.WriteLine("The Random bytes are: ");
for (int i = 0; i <= b.GetUpperBound(0); i++)
- Console.WriteLine("{0}: {1}", i, b[i]);
+ Console.WriteLine($"{i}: {b[i]}");
// The example displays output similar to the following:
// The Random bytes are:
diff --git a/snippets/csharp/System/Random/NextDouble/nextdouble1.cs b/snippets/csharp/System/Random/NextDouble/nextdouble1.cs
index c4b0b13e099..b6204b8c8bd 100644
--- a/snippets/csharp/System/Random/NextDouble/nextdouble1.cs
+++ b/snippets/csharp/System/Random/NextDouble/nextdouble1.cs
@@ -2,33 +2,34 @@
public class Example
{
- public static void Main()
- {
- //
- int[] frequency = new int[10];
- double number;
- Random rnd = new Random();
+ public static void Main()
+ {
+ //
+ int[] frequency = new int[10];
+ double number;
+ Random rnd = new();
- for (int ctr = 0; ctr <= 99; ctr++) {
- number = rnd.NextDouble();
- frequency[(int) Math.Floor(number*10)] ++;
- }
- Console.WriteLine("Distribution of Random Numbers:");
- for (int ctr = frequency.GetLowerBound(0); ctr <= frequency.GetUpperBound(0); ctr++)
- Console.WriteLine("0.{0}0-0.{0}9 {1}", ctr, frequency[ctr]);
+ for (int ctr = 0; ctr <= 99; ctr++)
+ {
+ number = rnd.NextDouble();
+ frequency[(int)Math.Floor(number * 10)]++;
+ }
+ Console.WriteLine("Distribution of Random Numbers:");
+ for (int ctr = frequency.GetLowerBound(0); ctr <= frequency.GetUpperBound(0); ctr++)
+ Console.WriteLine("0.{0}0-0.{0}9 {1}", ctr, frequency[ctr]);
- // The following example displays output similar to the following:
- // Distribution of Random Numbers:
- // 0.00-0.09 16
- // 0.10-0.19 8
- // 0.20-0.29 8
- // 0.30-0.39 11
- // 0.40-0.49 9
- // 0.50-0.59 6
- // 0.60-0.69 13
- // 0.70-0.79 6
- // 0.80-0.89 9
- // 0.90-0.99 14
- //
- }
+ // The following example displays output similar to the following:
+ // Distribution of Random Numbers:
+ // 0.00-0.09 16
+ // 0.10-0.19 8
+ // 0.20-0.29 8
+ // 0.30-0.39 11
+ // 0.40-0.49 9
+ // 0.50-0.59 6
+ // 0.60-0.69 13
+ // 0.70-0.79 6
+ // 0.80-0.89 9
+ // 0.90-0.99 14
+ //
+ }
}
diff --git a/snippets/csharp/System/Random/Overview/Next2.cs b/snippets/csharp/System/Random/Overview/Next2.cs
index 123ae011b2c..6571e692ebd 100644
--- a/snippets/csharp/System/Random/Overview/Next2.cs
+++ b/snippets/csharp/System/Random/Overview/Next2.cs
@@ -2,50 +2,50 @@
public class Example9
{
- public static void Main()
- {
- //
- Random rnd = new();
+ public static void Main()
+ {
+ //
+ Random rnd = new();
- Console.WriteLine("\n20 random integers from -100 to 100:");
- for (int ctr = 1; ctr <= 20; ctr++)
- {
- Console.Write("{0,6}", rnd.Next(-100, 101));
- if (ctr % 5 == 0) Console.WriteLine();
- }
+ Console.WriteLine("\n20 random integers from -100 to 100:");
+ for (int ctr = 1; ctr <= 20; ctr++)
+ {
+ Console.Write($"{rnd.Next(-100, 101),6}");
+ if (ctr % 5 == 0) Console.WriteLine();
+ }
- Console.WriteLine("\n20 random integers from 1000 to 10000:");
- for (int ctr = 1; ctr <= 20; ctr++)
- {
- Console.Write("{0,8}", rnd.Next(1000, 10001));
- if (ctr % 5 == 0) Console.WriteLine();
- }
+ Console.WriteLine("\n20 random integers from 1000 to 10000:");
+ for (int ctr = 1; ctr <= 20; ctr++)
+ {
+ Console.Write($"{rnd.Next(1000, 10001),8}");
+ if (ctr % 5 == 0) Console.WriteLine();
+ }
- Console.WriteLine("\n20 random integers from 1 to 10:");
- for (int ctr = 1; ctr <= 20; ctr++)
- {
- Console.Write("{0,6}", rnd.Next(1, 11));
- if (ctr % 5 == 0) Console.WriteLine();
- }
+ Console.WriteLine("\n20 random integers from 1 to 10:");
+ for (int ctr = 1; ctr <= 20; ctr++)
+ {
+ Console.Write($"{rnd.Next(1, 11),6}");
+ if (ctr % 5 == 0) Console.WriteLine();
+ }
- // The example displays output similar to the following:
- // 20 random integers from -100 to 100:
- // 65 -95 -10 90 -35
- // -83 -16 -15 -19 41
- // -67 -93 40 12 62
- // -80 -95 67 -81 -21
- //
- // 20 random integers from 1000 to 10000:
- // 4857 9897 4405 6606 1277
- // 9238 9113 5151 8710 1187
- // 2728 9746 1719 3837 3736
- // 8191 6819 4923 2416 3028
- //
- // 20 random integers from 1 to 10:
- // 9 8 5 9 9
- // 9 1 2 3 8
- // 1 4 8 10 5
- // 9 7 9 10 5
- //
- }
+ // The example displays output similar to the following:
+ // 20 random integers from -100 to 100:
+ // 65 -95 -10 90 -35
+ // -83 -16 -15 -19 41
+ // -67 -93 40 12 62
+ // -80 -95 67 -81 -21
+ //
+ // 20 random integers from 1000 to 10000:
+ // 4857 9897 4405 6606 1277
+ // 9238 9113 5151 8710 1187
+ // 2728 9746 1719 3837 3736
+ // 8191 6819 4923 2416 3028
+ //
+ // 20 random integers from 1 to 10:
+ // 9 8 5 9 9
+ // 9 1 2 3 8
+ // 1 4 8 10 5
+ // 9 7 9 10 5
+ //
+ }
}
diff --git a/snippets/csharp/System/Random/Overview/Random2.cs b/snippets/csharp/System/Random/Overview/Random2.cs
index c95f92491d6..66a60fdea13 100644
--- a/snippets/csharp/System/Random/Overview/Random2.cs
+++ b/snippets/csharp/System/Random/Overview/Random2.cs
@@ -13,37 +13,37 @@ public static void Main()
rand.NextBytes(bytes);
Console.WriteLine("Five random byte values:");
foreach (byte byteValue in bytes)
- Console.Write("{0, 5}", byteValue);
+ Console.Write($"{byteValue,5}");
Console.WriteLine();
// Generate and display 5 random integers.
Console.WriteLine("Five random integer values:");
for (int ctr = 0; ctr <= 4; ctr++)
- Console.Write("{0,15:N0}", rand.Next());
+ Console.Write($"{rand.Next(),15:N0}");
Console.WriteLine();
// Generate and display 5 random integers between 0 and 100.
Console.WriteLine("Five random integers between 0 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
- Console.Write("{0,8:N0}", rand.Next(101));
+ Console.Write($"{rand.Next(101),8:N0}");
Console.WriteLine();
// Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:");
for (int ctr = 0; ctr <= 4; ctr++)
- Console.Write("{0,8:N0}", rand.Next(50, 101));
+ Console.Write($"{rand.Next(50, 101),8:N0}");
Console.WriteLine();
// Generate and display 5 random floating point values from 0 to 1.
Console.WriteLine("Five Doubles.");
for (int ctr = 0; ctr <= 4; ctr++)
- Console.Write("{0,8:N3}", rand.NextDouble());
+ Console.Write($"{rand.NextDouble(),8:N3}");
Console.WriteLine();
// Generate and display 5 random floating point values from 0 to 5.
Console.WriteLine("Five Doubles between 0 and 5.");
for (int ctr = 0; ctr <= 4; ctr++)
- Console.Write("{0,8:N3}", rand.NextDouble() * 5);
+ Console.Write($"{rand.NextDouble() * 5,8:N3}");
// The example displays output like the following:
// Five random byte values:
diff --git a/snippets/csharp/System/Random/Overview/booleans1.cs b/snippets/csharp/System/Random/Overview/booleans1.cs
index 8c2a2a9ed54..078734bfcad 100644
--- a/snippets/csharp/System/Random/Overview/booleans1.cs
+++ b/snippets/csharp/System/Random/Overview/booleans1.cs
@@ -18,12 +18,8 @@ public static void Main()
else
totalFalse++;
}
- Console.WriteLine("Number of true values: {0,7:N0} ({1:P3})",
- totalTrue,
- ((double)totalTrue) / (totalTrue + totalFalse));
- Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})",
- totalFalse,
- ((double)totalFalse) / (totalTrue + totalFalse));
+ Console.WriteLine($"Number of true values: {totalTrue,7:N0} ({((double)totalTrue) / (totalTrue + totalFalse):P3})");
+ Console.WriteLine($"Number of false values: {totalFalse,7:N0} ({((double)totalFalse) / (totalTrue + totalFalse):P3})");
}
}
@@ -31,15 +27,9 @@ public class BooleanGenerator
{
Random rnd;
- public BooleanGenerator()
- {
- rnd = new Random();
- }
+ public BooleanGenerator() => rnd = new();
- public bool NextBoolean()
- {
- return rnd.Next(0, 2) == 1;
- }
+ public bool NextBoolean() => rnd.Next(0, 2) == 1;
}
// The example displays output like the following:
// Number of true values: 500,004 (50.000 %)
diff --git a/snippets/csharp/System/Random/Overview/booleans2.cs b/snippets/csharp/System/Random/Overview/booleans2.cs
index 70483c07c19..f892675e01c 100644
--- a/snippets/csharp/System/Random/Overview/booleans2.cs
+++ b/snippets/csharp/System/Random/Overview/booleans2.cs
@@ -18,17 +18,10 @@ public static void Main()
else
totalFalse++;
}
- Console.WriteLine("Number of true values: {0,7:N0} ({1:P3})",
- totalTrue,
- ((double)totalTrue) / (totalTrue + totalFalse));
- Console.WriteLine("Number of false values: {0,7:N0} ({1:P3})",
- totalFalse,
- ((double)totalFalse) / (totalTrue + totalFalse));
+ Console.WriteLine($"Number of true values: {totalTrue,7:N0} ({((double)totalTrue) / (totalTrue + totalFalse):P3})");
+ Console.WriteLine($"Number of false values: {totalFalse,7:N0} ({((double)totalFalse) / (totalTrue + totalFalse):P3})");
- bool NextBoolean()
- {
- return rnd.Next(0, 2) == 1;
- }
+ bool NextBoolean() => rnd.Next(0, 2) == 1;
// The example displays output like the following:
// Number of true values: 499,777 (49.978 %)
diff --git a/snippets/csharp/System/Random/Overview/doublerange1.cs b/snippets/csharp/System/Random/Overview/doublerange1.cs
index a5098632c36..bf80c8915c4 100644
--- a/snippets/csharp/System/Random/Overview/doublerange1.cs
+++ b/snippets/csharp/System/Random/Overview/doublerange1.cs
@@ -19,11 +19,9 @@ public static void Main()
count[(int)(number / ONE_TENTH)]++;
}
// Display breakdown by range.
- Console.WriteLine("{0,28} {1,32} {2,7}\n", "Range", "Count", "Pct.");
+ Console.WriteLine($"{"Range",28} {"Count",32} {"Pct.",7}\n");
for (int ctr = 0; ctr <= 9; ctr++)
- Console.WriteLine("{0,25:N0}-{1,25:N0} {2,8:N0} {3,7:P2}", ctr * ONE_TENTH,
- ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue,
- count[ctr], count[ctr] / 20000000.0);
+ Console.WriteLine($"{ctr * ONE_TENTH,25:N0}-{(ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue),25:N0} {count[ctr],8:N0} {count[ctr] / 20000000.0,7:P2}");
// The example displays output like the following:
// Range Count Pct.
diff --git a/snippets/csharp/System/Random/Overview/doublerange3.cs b/snippets/csharp/System/Random/Overview/doublerange3.cs
index 92c4a7ebe33..53460f7617e 100644
--- a/snippets/csharp/System/Random/Overview/doublerange3.cs
+++ b/snippets/csharp/System/Random/Overview/doublerange3.cs
@@ -18,9 +18,7 @@ public static void Main()
for (int ctr = 0; ctr <= 9; ctr++)
{
double lowerRange = 10 + ctr * .1;
- Console.WriteLine("{0:N1} to {1:N1}: {2,8:N0} ({3,7:P2})",
- lowerRange, lowerRange + .1, range[ctr],
- range[ctr] / 1000000.0);
+ Console.WriteLine($"{lowerRange:N1} to {lowerRange + .1:N1}: {range[ctr],8:N0} ({range[ctr] / 1000000.0,7:P2})");
}
// The example displays output like the following:
diff --git a/snippets/csharp/System/Random/Overview/long1.cs b/snippets/csharp/System/Random/Overview/long1.cs
index 10f76c4b328..5ae2f401f6f 100644
--- a/snippets/csharp/System/Random/Overview/long1.cs
+++ b/snippets/csharp/System/Random/Overview/long1.cs
@@ -19,11 +19,9 @@ public static void Main()
count[(int)(number / ONE_TENTH)]++;
}
// Display breakdown by range.
- Console.WriteLine("{0,28} {1,32} {2,7}\n", "Range", "Count", "Pct.");
+ Console.WriteLine($"{"Range",28} {"Count",32} {"Pct.",7}\n");
for (int ctr = 0; ctr <= 9; ctr++)
- Console.WriteLine("{0,25:N0}-{1,25:N0} {2,8:N0} {3,7:P2}", ctr * ONE_TENTH,
- ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue,
- count[ctr], count[ctr] / 20000000.0);
+ Console.WriteLine($"{ctr * ONE_TENTH,25:N0}-{(ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : long.MaxValue),25:N0} {count[ctr],8:N0} {count[ctr] / 20000000.0,7:P2}");
// The example displays output like the following:
// Range Count Pct.
diff --git a/snippets/csharp/System/Random/Overview/next.cs b/snippets/csharp/System/Random/Overview/next.cs
index 39ac1861c06..fbf4eb1efe3 100644
--- a/snippets/csharp/System/Random/Overview/next.cs
+++ b/snippets/csharp/System/Random/Overview/next.cs
@@ -4,7 +4,7 @@
public class RandomNextDemo
{
static void Main()
- {
+ {
//
Console.WriteLine(
"""
@@ -20,7 +20,7 @@ bounds. Note the effect\nthat the various
combinations of bounds have on the sequences.
"""
);
-
+
NoBoundsRandoms(234);
UpperBoundRandoms(234, int.MaxValue);
diff --git a/snippets/csharp/System/Random/Overview/threadsafeex1.cs b/snippets/csharp/System/Random/Overview/threadsafeex1.cs
index ea88b8c3e9d..9e86f956c27 100644
--- a/snippets/csharp/System/Random/Overview/threadsafeex1.cs
+++ b/snippets/csharp/System/Random/Overview/threadsafeex1.cs
@@ -16,11 +16,11 @@ public class Example18
public Example18()
{
- s_rand = new Random();
- s_randLock = new object();
- s_numericLock = new object();
- s_countdown = new CountdownEvent(1);
- s_source = new CancellationTokenSource();
+ s_rand = new();
+ s_randLock = new();
+ s_numericLock = new();
+ s_countdown = new(1);
+ s_source = new();
}
public static void Main()
diff --git a/snippets/csharp/System/Random/Overview/threadsafeex2.cs b/snippets/csharp/System/Random/Overview/threadsafeex2.cs
index 9f7ef357321..85bd6a4b84a 100644
--- a/snippets/csharp/System/Random/Overview/threadsafeex2.cs
+++ b/snippets/csharp/System/Random/Overview/threadsafeex2.cs
@@ -14,10 +14,10 @@ public class Example19
public Example19()
{
- s_rand = new Random();
- s_randLock = new object();
- s_numericLock = new object();
- s_source = new CancellationTokenSource();
+ s_rand = new();
+ s_randLock = new();
+ s_numericLock = new();
+ s_source = new();
}
public static async Task Main()
@@ -65,10 +65,10 @@ private async Task Execute()
}
// Show result.
- Console.WriteLine("Task {0} finished execution.", taskNo);
- Console.WriteLine("Random numbers generated: {0:N0}", taskCtr);
- Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal);
- Console.WriteLine("Random number mean: {0:N4}\n", taskTotal / taskCtr);
+ Console.WriteLine($"Task {taskNo} finished execution.");
+ Console.WriteLine($"Random numbers generated: {taskCtr:N0}");
+ Console.WriteLine($"Sum of random numbers: {taskTotal:N2}");
+ Console.WriteLine($"Random number mean: {taskTotal / taskCtr:N4}\n");
// Update overall totals.
lock (s_numericLock)
@@ -91,9 +91,9 @@ private async Task Execute()
foreach (Exception inner in e.InnerExceptions)
{
if (inner is TaskCanceledException canc)
- Console.WriteLine("Task #{0} cancelled.", canc.Task.Id);
+ Console.WriteLine($"Task #{canc.Task.Id} cancelled.");
else
- Console.WriteLine("Exception: {0}", inner.GetType().Name);
+ Console.WriteLine($"Exception: {inner.GetType().Name}");
}
}
finally
diff --git a/snippets/csharp/System/Random/Overview/unique.cs b/snippets/csharp/System/Random/Overview/unique.cs
index dcc2da0789f..7403d1d422b 100644
--- a/snippets/csharp/System/Random/Overview/unique.cs
+++ b/snippets/csharp/System/Random/Overview/unique.cs
@@ -13,11 +13,11 @@ public static void Main()
Console.WriteLine("\nThe first random number generator:");
for (int ctr = 1; ctr <= 10; ctr++)
- Console.WriteLine(" {0}", rnd1.Next());
+ Console.WriteLine($" {rnd1.Next()}");
Console.WriteLine("\nThe second random number generator:");
for (int ctr = 1; ctr <= 10; ctr++)
- Console.WriteLine(" {0}", rnd2.Next());
+ Console.WriteLine($" {rnd2.Next()}");
}
}
// The example displays output like the following:
diff --git a/snippets/csharp/System/Random/Overview/uniquearray1.cs b/snippets/csharp/System/Random/Overview/uniquearray1.cs
index 3d570b52193..8e05e57dec6 100644
--- a/snippets/csharp/System/Random/Overview/uniquearray1.cs
+++ b/snippets/csharp/System/Random/Overview/uniquearray1.cs
@@ -7,10 +7,7 @@ public class Card
public Suit Suit;
public FaceValue FaceValue;
- public override string ToString()
- {
- return string.Format("{0:F} of {1:F}", FaceValue, Suit);
- }
+ public override string ToString() => $"{FaceValue:F} of {Suit:F}";
}
public enum Suit { Hearts, Diamonds, Spades, Clubs };
@@ -36,7 +33,7 @@ public class Dealer
public Dealer()
{
- _rnd = new Random();
+ _rnd = new();
// Initialize the deck.
int deckCtr = 0;
foreach (object suit in Enum.GetValues(typeof(Suit)))
@@ -97,7 +94,7 @@ private static void ShowCards(Card[] cards)
{
foreach (Card card in cards)
if (card != null)
- Console.WriteLine("{0} of {1}", card.FaceValue, card.Suit);
+ Console.WriteLine($"{card.FaceValue} of {card.Suit}");
}
}
// The example displays output like the following:
diff --git a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs
index 0a696d41bb1..f1f685688b8 100644
--- a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs
+++ b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
// Note: you must compile this sample using the unsafe flag.
// From the command line, type the following: csc sample.cs /unsafe
@@ -34,10 +34,7 @@ public static unsafe void Main()
}
}
- private static int[] CreateInt32Array()
- {
- return new int[] { 100, 200, 300, 400, 500 };
- }
+ private static int[] CreateInt32Array() =>[ 100, 200, 300, 400, 500 ];
}
// The example displays the following output:
diff --git a/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs b/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs
index 3a4def83465..ce060d61ac7 100644
--- a/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs
+++ b/snippets/csharp/System/RuntimeTypeHandle/Overview/type_gettypehandle.cs
@@ -1,41 +1,35 @@
//
using System;
-using System.Reflection;
+
public class MyClass1
{
- private int x=0;
- public int MyMethod()
- {
- return x;
- }
+ private int x = 0;
+ public int MyMethod() => x;
}
public class MyClass2
{
public static void Main()
{
- MyClass1 myClass1 = new MyClass1();
+ MyClass1 myClass1 = new();
// Get the RuntimeTypeHandle from an object.
RuntimeTypeHandle myRTHFromObject = Type.GetTypeHandle(myClass1);
// Get the RuntimeTypeHandle from a type.
RuntimeTypeHandle myRTHFromType = typeof(MyClass1).TypeHandle;
- Console.WriteLine("\nmyRTHFromObject.Value: {0}", myRTHFromObject.Value);
- Console.WriteLine("myRTHFromObject.GetType(): {0}", myRTHFromObject.GetType());
+ Console.WriteLine($"\nmyRTHFromObject.Value: {myRTHFromObject.Value}");
+ Console.WriteLine($"myRTHFromObject.GetType(): {myRTHFromObject.GetType()}");
Console.WriteLine("Get the type back from the handle...");
- Console.WriteLine("Type.GetTypeFromHandle(myRTHFromObject): {0}",
- Type.GetTypeFromHandle(myRTHFromObject));
+ Console.WriteLine($"Type.GetTypeFromHandle(myRTHFromObject): {Type.GetTypeFromHandle(myRTHFromObject)}");
- Console.WriteLine("\nmyRTHFromObject.Equals(myRTHFromType): {0}",
- myRTHFromObject.Equals(myRTHFromType));
+ Console.WriteLine($"\nmyRTHFromObject.Equals(myRTHFromType): {myRTHFromObject.Equals(myRTHFromType)}");
- Console.WriteLine("\nmyRTHFromType.Value: {0}", myRTHFromType.Value);
- Console.WriteLine("myRTHFromType.GetType(): {0}", myRTHFromType.GetType());
+ Console.WriteLine($"\nmyRTHFromType.Value: {myRTHFromType.Value}");
+ Console.WriteLine($"myRTHFromType.GetType(): {myRTHFromType.GetType()}");
Console.WriteLine("Get the type back from the handle...");
- Console.WriteLine("Type.GetTypeFromHandle(myRTHFromType): {0}",
- Type.GetTypeFromHandle(myRTHFromType));
+ Console.WriteLine($"Type.GetTypeFromHandle(myRTHFromType): {Type.GetTypeFromHandle(myRTHFromType)}");
}
}
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
diff --git a/snippets/csharp/System/String/.ctor/char2_ctor.cs b/snippets/csharp/System/String/.ctor/char2_ctor.cs
index ea152e7404d..15308e8a806 100644
--- a/snippets/csharp/System/String/.ctor/char2_ctor.cs
+++ b/snippets/csharp/System/String/.ctor/char2_ctor.cs
@@ -3,27 +3,28 @@
public class Example1
{
- public static unsafe void Main()
- {
- char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ',
- 'w', 'o', 'r', 'l', 'd', '!', '\u0000' };
- String value;
-
- fixed (char* charPtr = characters) {
- int length = 0;
- Char* iterator = charPtr;
-
- while (*iterator != '\x0000')
- {
- if (*iterator == '!' || *iterator == '.')
- break;
- iterator++;
- length++;
- }
- value = new String(charPtr, 0, length);
- }
- Console.WriteLine(value);
- }
+ public static unsafe void Main()
+ {
+ char[] characters = [ 'H', 'e', 'l', 'l', 'o', ' ',
+ 'w', 'o', 'r', 'l', 'd', '!', '\u0000' ];
+ string value;
+
+ fixed (char* charPtr = characters)
+ {
+ int length = 0;
+ char* iterator = charPtr;
+
+ while (*iterator != '\x0000')
+ {
+ if (*iterator == '!' || *iterator == '.')
+ break;
+ iterator++;
+ length++;
+ }
+ value = new(charPtr, 0, length);
+ }
+ Console.WriteLine(value);
+ }
}
// The example displays the following output:
// Hello World
diff --git a/snippets/csharp/System/String/.ctor/chptrctor_null.cs b/snippets/csharp/System/String/.ctor/chptrctor_null.cs
index 41eb2e7fa08..1fe18ae543c 100644
--- a/snippets/csharp/System/String/.ctor/chptrctor_null.cs
+++ b/snippets/csharp/System/String/.ctor/chptrctor_null.cs
@@ -3,27 +3,29 @@
public class Example2
{
- public unsafe static void Main()
- {
- char[] chars = { 'a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0' };
- string s = null;
-
- fixed(char* chPtr = chars) {
- s = new string(chPtr, 0, chars.Length);
- }
+ public unsafe static void Main()
+ {
+ char[] chars = ['a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0'];
+ string s = null;
- foreach (var ch in s)
- Console.Write($"{(ushort)ch:X4} ");
- Console.WriteLine();
-
- fixed(char* chPtr = chars) {
- s = new string(chPtr);
- }
-
- foreach (var ch in s)
- Console.Write($"{(ushort)ch:X4} ");
- Console.WriteLine();
- }
+ fixed (char* chPtr = chars)
+ {
+ s = new(chPtr, 0, chars.Length);
+ }
+
+ foreach (char ch in s)
+ Console.Write($"{(ushort)ch:X4} ");
+ Console.WriteLine();
+
+ fixed (char* chPtr = chars)
+ {
+ s = new(chPtr);
+ }
+
+ foreach (char ch in s)
+ Console.Write($"{(ushort)ch:X4} ");
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
diff --git a/snippets/csharp/System/String/.ctor/ctor1.cs b/snippets/csharp/System/String/.ctor/ctor1.cs
index c3ff8a27bd1..c54fbceca92 100644
--- a/snippets/csharp/System/String/.ctor/ctor1.cs
+++ b/snippets/csharp/System/String/.ctor/ctor1.cs
@@ -3,13 +3,13 @@
public class Example3
{
- public static void Main()
- {
- String value1 = "This is a string.";
- String value2 = value1;
- Console.WriteLine(value1);
- Console.WriteLine(value2);
- }
+ public static void Main()
+ {
+ string value1 = "This is a string.";
+ string value2 = value1;
+ Console.WriteLine(value1);
+ Console.WriteLine(value2);
+ }
}
// The example displays the following output:
// This is a string.
diff --git a/snippets/csharp/System/String/.ctor/ctor2.cs b/snippets/csharp/System/String/.ctor/ctor2.cs
index b6e0d7f7885..51f35bd6b99 100644
--- a/snippets/csharp/System/String/.ctor/ctor2.cs
+++ b/snippets/csharp/System/String/.ctor/ctor2.cs
@@ -3,17 +3,18 @@
public class Example4
{
- public static unsafe void Main()
- {
- char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ',
- 'w', 'o', 'r', 'l', 'd', '!', '\u0000' };
- string value;
-
- fixed (char* charPtr = characters) {
- value = new String(charPtr);
- }
- Console.WriteLine(value);
- }
+ public static unsafe void Main()
+ {
+ char[] characters = [ 'H', 'e', 'l', 'l', 'o', ' ',
+ 'w', 'o', 'r', 'l', 'd', '!', '\u0000' ];
+ string value;
+
+ fixed (char* charPtr = characters)
+ {
+ value = new(charPtr);
+ }
+ Console.WriteLine(value);
+ }
}
// The example displays the following output:
// Hello world!
diff --git a/snippets/csharp/System/String/.ctor/ptrctor_null.cs b/snippets/csharp/System/String/.ctor/ptrctor_null.cs
index 7209113786f..a8bd9fbf4f8 100644
--- a/snippets/csharp/System/String/.ctor/ptrctor_null.cs
+++ b/snippets/csharp/System/String/.ctor/ptrctor_null.cs
@@ -3,28 +3,30 @@
public class Example5
{
- public unsafe static void Main()
- {
- sbyte[] bytes = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42, 0x43, 0x44, 0x00 };
-
- string s = null;
- fixed (sbyte* bytePtr = bytes) {
- s = new string(bytePtr, 0, bytes.Length);
- }
-
- foreach (var ch in s)
- Console.Write($"{(ushort)ch:X4} ");
-
- Console.WriteLine();
+ public unsafe static void Main()
+ {
+ sbyte[] bytes = [0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42, 0x43, 0x44, 0x00];
- fixed(sbyte* bytePtr = bytes) {
- s = new string(bytePtr);
- }
-
- foreach (var ch in s)
- Console.Write($"{(ushort)ch:X4} ");
- Console.WriteLine();
- }
+ string s = null;
+ fixed (sbyte* bytePtr = bytes)
+ {
+ s = new(bytePtr, 0, bytes.Length);
+ }
+
+ foreach (char ch in s)
+ Console.Write($"{(ushort)ch:X4} ");
+
+ Console.WriteLine();
+
+ fixed (sbyte* bytePtr = bytes)
+ {
+ s = new(bytePtr);
+ }
+
+ foreach (char ch in s)
+ Console.Write($"{(ushort)ch:X4} ");
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// 0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
diff --git a/snippets/csharp/System/String/.ctor/source.cs b/snippets/csharp/System/String/.ctor/source.cs
index 7eebd4e46d9..11c6449f472 100644
--- a/snippets/csharp/System/String/.ctor/source.cs
+++ b/snippets/csharp/System/String/.ctor/source.cs
@@ -8,56 +8,56 @@ class ConsoleApp
[STAThread]
static void Main(string[] args)
{
-//
+ //
// Unicode Mathematical operators
- char [] charArr1 = {'\u2200','\u2202','\u200F','\u2205'};
- String szMathSymbols = new String(charArr1);
+ char[] charArr1 = ['\u2200', '\u2202', '\u200F', '\u2205'];
+ string szMathSymbols = new(charArr1);
// Unicode Letterlike Symbols
- char [] charArr2 = {'\u2111','\u2118','\u2122','\u2126'};
- String szLetterLike = new String (charArr2);
+ char[] charArr2 = ['\u2111', '\u2118', '\u2122', '\u2126'];
+ string szLetterLike = new(charArr2);
// Compare Strings - the result is false
Console.WriteLine("The Strings are equal? " +
- (String.Compare(szMathSymbols, szLetterLike)==0?"true":"false") );
-//
-//
+ (string.Compare(szMathSymbols, szLetterLike) == 0 ? "true" : "false"));
+ //
+ //
unsafe
{
// Null terminated ASCII characters in an sbyte array
- String szAsciiUpper = null;
- sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 };
+ string szAsciiUpper = null;
+ sbyte[] sbArr1 = [0x41, 0x42, 0x43, 0x00];
// Instruct the Garbage Collector not to move the memory
- fixed(sbyte* pAsciiUpper = sbArr1)
+ fixed (sbyte* pAsciiUpper = sbArr1)
{
- szAsciiUpper = new String(pAsciiUpper);
+ szAsciiUpper = new(pAsciiUpper);
}
- String szAsciiLower = null;
- sbyte[] sbArr2 = { 0x61, 0x62, 0x63, 0x00 };
+ string szAsciiLower = null;
+ sbyte[] sbArr2 = [0x61, 0x62, 0x63, 0x00];
// Instruct the Garbage Collector not to move the memory
- fixed(sbyte* pAsciiLower = sbArr2)
+ fixed (sbyte* pAsciiLower = sbArr2)
{
- szAsciiLower = new String(pAsciiLower, 0, sbArr2.Length);
+ szAsciiLower = new(pAsciiLower, 0, sbArr2.Length);
}
// Prints "ABC abc"
Console.WriteLine(szAsciiUpper + " " + szAsciiLower);
// Compare Strings - the result is true
Console.WriteLine("The Strings are equal when capitalized ? " +
- (String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper())==0?"true":"false") );
+ (string.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper()) == 0 ? "true" : "false"));
// This is the effective equivalent of another Compare method, which ignores case
Console.WriteLine("The Strings are equal when capitalized ? " +
- (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") );
+ (string.Compare(szAsciiUpper, szAsciiLower, true) == 0 ? "true" : "false"));
}
-//
-//
+ //
+ //
// Create a Unicode String with 5 Greek Alpha characters
- String szGreekAlpha = new String('\u0391',5);
+ string szGreekAlpha = new('\u0391', 5);
// Create a Unicode String with a Greek Omega character
- String szGreekOmega = new String(new char [] {'\u03A9','\u03A9','\u03A9'},2,1);
+ string szGreekOmega = new(['\u03A9', '\u03A9', '\u03A9'], 2, 1);
- String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone());
+ string szGreekLetters = string.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone());
// Examine the result
Console.WriteLine(szGreekLetters);
@@ -69,23 +69,23 @@ static void Main(string[] args)
Console.WriteLine("The Greek letter Alpha first appears at index " + ialpha +
" and Omega last appears at index " + iomega + " in this String.");
-//
+ //
-//
+ //
unsafe
{
- String utfeightstring = null;
- sbyte [] asciiChars = new sbyte[] { 0x51,0x52,0x53,0x54,0x54,0x56 };
- UTF8Encoding encoding = new UTF8Encoding(true, true);
+ string utfeightstring = null;
+ sbyte[] asciiChars = [0x51, 0x52, 0x53, 0x54, 0x54, 0x56];
+ UTF8Encoding encoding = new(true, true);
// Instruct the Garbage Collector not to move the memory
- fixed(sbyte* pAsciiChars = asciiChars)
+ fixed (sbyte* pAsciiChars = asciiChars)
{
- utfeightstring = new String(pAsciiChars,0,asciiChars.Length,encoding);
+ utfeightstring = new(pAsciiChars, 0, asciiChars.Length, encoding);
}
- Console.WriteLine("The UTF8 String is " + utfeightstring ); // prints "QRSTTV"
+ Console.WriteLine("The UTF8 String is " + utfeightstring); // prints "QRSTTV"
}
-//
+ //
}
}
-}
\ No newline at end of file
+}
diff --git a/snippets/csharp/System/String/Chars/chars1.cs b/snippets/csharp/System/String/Chars/chars1.cs
index 12081f2f6e9..65459d62154 100644
--- a/snippets/csharp/System/String/Chars/chars1.cs
+++ b/snippets/csharp/System/String/Chars/chars1.cs
@@ -2,14 +2,14 @@
public class Example
{
- public static void Main()
- {
- //
- string str1 = "Test";
- for (int ctr = 0; ctr <= str1.Length - 1; ctr++ )
- Console.Write("{0} ", str1[ctr]);
- // The example displays the following output:
- // T e s t
- //
- }
+ public static void Main()
+ {
+ //
+ string str1 = "Test";
+ for (int ctr = 0; ctr <= str1.Length - 1; ctr++)
+ Console.Write($"{str1[ctr]} ");
+ // The example displays the following output:
+ // T e s t
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Chars/uri_ishexdigit.cs b/snippets/csharp/System/String/Chars/uri_ishexdigit.cs
index 443ed53ec1b..2bc8b71c248 100644
--- a/snippets/csharp/System/String/Chars/uri_ishexdigit.cs
+++ b/snippets/csharp/System/String/Chars/uri_ishexdigit.cs
@@ -8,18 +8,18 @@ specified character is valid hexadecimal digit.
using System;
class MyIsHexDigitSample
{
- public static void Main()
- {
- try
- {
+ public static void Main()
+ {
+ try
+ {
//
- Console.Write("Type a string : ");
- string myString = Console.ReadLine();
- for (int i = 0; i < myString.Length; i ++)
- if(Uri.IsHexDigit(myString[i]))
- Console.WriteLine("{0} is a hexadecimal digit.", myString[i]);
- else
- Console.WriteLine("{0} is not a hexadecimal digit.", myString[i]);
+ Console.Write("Type a string : ");
+ string myString = Console.ReadLine();
+ for (int i = 0; i < myString.Length; i++)
+ if (Uri.IsHexDigit(myString[i]))
+ Console.WriteLine($"{myString[i]} is a hexadecimal digit.");
+ else
+ Console.WriteLine($"{myString[i]} is not a hexadecimal digit.");
// The example produces output like the following:
// Type a string : 3f5EaZ
// 3 is a hexadecimal digit.
@@ -29,14 +29,14 @@ public static void Main()
// a is a hexadecimal digit.
// Z is not a hexadecimal digit.
//
- }
- catch(Exception e)
- {
- Console.WriteLine(e.Message);
- }
- }
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine(e.Message);
+ }
+ }
}
// ***** Output *****
/*
-*/
\ No newline at end of file
+*/
diff --git a/snippets/csharp/System/String/Compare/ArrayListSample.cs b/snippets/csharp/System/String/Compare/ArrayListSample.cs
index d85c1ff9a0d..acf6be7feda 100644
--- a/snippets/csharp/System/String/Compare/ArrayListSample.cs
+++ b/snippets/csharp/System/String/Compare/ArrayListSample.cs
@@ -1,7 +1,7 @@
//
using System;
-using System.Text;
using System.Collections;
+using System.Text;
public class SamplesArrayList
{
@@ -10,20 +10,22 @@ public static void Main()
{
//
// Creates and initializes a new ArrayList.
- ArrayList myAL = new ArrayList();
- myAL.Add("Eric");
- myAL.Add("Mark");
- myAL.Add("Lance");
- myAL.Add("Rob");
- myAL.Add("Kris");
- myAL.Add("Brad");
- myAL.Add("Kit");
- myAL.Add("Bradley");
- myAL.Add("Keith");
- myAL.Add("Susan");
+ ArrayList myAL = new ArrayList()
+ {
+ "Eric",
+ "Mark",
+ "Lance",
+ "Rob",
+ "Kris",
+ "Brad",
+ "Kit",
+ "Bradley",
+ "Keith",
+ "Susan"
+ };
// Displays the properties and values of the ArrayList.
- Console.WriteLine("Count: {0}", myAL.Count);
+ Console.WriteLine($"Count: {myAL.Count}");
//
PrintValues("Unsorted", myAL);
@@ -43,7 +45,7 @@ public static void Main()
//
public static void PrintValues(string title, IEnumerable myList)
{
- Console.Write("{0,10}: ", title);
+ Console.Write($"{title,10}: ");
StringBuilder sb = new StringBuilder();
foreach (string s in myList)
{
@@ -62,7 +64,7 @@ public int Compare(object? x, object? y)
string? s1 = x as string;
string? s2 = y as string;
//negate the return value to get the reverse order
- return -String.Compare(s1, s2);
+ return -string.Compare(s1, s2);
}
}
//
diff --git a/snippets/csharp/System/String/Compare/Compare18.cs b/snippets/csharp/System/String/Compare/Compare18.cs
index d570605d221..e10c4b7a483 100644
--- a/snippets/csharp/System/String/Compare/Compare18.cs
+++ b/snippets/csharp/System/String/Compare/Compare18.cs
@@ -5,19 +5,16 @@ public class Example18
public static void Main()
{
//
- String s1, s2;
+ string s1, s2;
s1 = "car"; s2 = "Car";
- Console.WriteLine("'{0}' and '{1}': {2}", s1, s2,
- String.Compare(s1, s2));
-
- s1 = "fork"; s2 = "forks";
- Console.WriteLine("'{0}' and '{1}': {2}", s1, s2,
- String.Compare(s1, s2));
+ Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}");
+
+ s1 = "fork"; s2 = "forks";
+ Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}");
s1 = "mammal"; s2 = "fish";
- Console.WriteLine("'{0}' and '{1}': {2}", s1, s2,
- String.Compare(s1, s2));
+ Console.WriteLine($"'{s1}' and '{s2}': {string.Compare(s1, s2)}");
// The example displays the following output:
// 'car' and 'Car': -1
diff --git a/snippets/csharp/System/String/Compare/Example.cs b/snippets/csharp/System/String/Compare/Example.cs
index f2a50dead54..b80d4d96cfd 100644
--- a/snippets/csharp/System/String/Compare/Example.cs
+++ b/snippets/csharp/System/String/Compare/Example.cs
@@ -12,7 +12,7 @@ public static void Main()
int result;
// Cultural (linguistic) comparison.
- result = String.Compare(string1, string2, new CultureInfo("en-US"),
+ result = string.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.None);
if (result > 0)
relation = "comes after";
@@ -21,11 +21,10 @@ public static void Main()
else
relation = "comes before";
- Console.WriteLine("'{0}' {1} '{2}'.",
- string1, relation, string2);
+ Console.WriteLine($"'{string1}' {relation} '{string2}'.");
// Cultural (linguistic) case-insensitive comparison.
- result = String.Compare(string1, string2, new CultureInfo("en-US"),
+ result = string.Compare(string1, string2, new CultureInfo("en-US"),
CompareOptions.IgnoreCase);
if (result > 0)
relation = "comes after";
@@ -34,11 +33,10 @@ public static void Main()
else
relation = "comes before";
- Console.WriteLine("'{0}' {1} '{2}'.",
- string1, relation, string2);
-
+ Console.WriteLine($"'{string1}' {relation} '{string2}'.");
+
// Culture-insensitive ordinal comparison.
- result = String.CompareOrdinal(string1, string2);
+ result = string.CompareOrdinal(string1, string2);
if (result > 0)
relation = "comes after";
else if (result == 0)
@@ -46,11 +44,10 @@ public static void Main()
else
relation = "comes before";
- Console.WriteLine("'{0}' {1} '{2}'.",
- string1, relation, string2);
+ Console.WriteLine($"'{string1}' {relation} '{string2}'.");
// The example produces the following output:
- // 'brother' comes before 'Brother'.
+ // 'brother' comes before 'Brother'.
// 'brother' is the same as 'Brother'.
// 'brother' comes after 'Brother'.
}
diff --git a/snippets/csharp/System/String/Compare/Example1.cs b/snippets/csharp/System/String/Compare/Example1.cs
index c70346e32dd..4208632f68c 100644
--- a/snippets/csharp/System/String/Compare/Example1.cs
+++ b/snippets/csharp/System/String/Compare/Example1.cs
@@ -19,11 +19,11 @@ public static void Main()
int length = Math.Max(name1.Length, name2.Length);
Console.WriteLine("Sorted alphabetically by last name:");
- if (String.Compare(name1, index1, name2, index2, length,
+ if (string.Compare(name1, index1, name2, index2, length,
new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
- Console.WriteLine("{0}\n{1}", name1, name2);
+ Console.WriteLine($"{name1}\n{name2}");
else
- Console.WriteLine("{0}\n{1}", name2, name1);
+ Console.WriteLine($"{name2}\n{name1}");
// The example displays the following output:
// Sorted alphabetically by last name:
diff --git a/snippets/csharp/System/String/Compare/cmpcmp.cs b/snippets/csharp/System/String/Compare/cmpcmp.cs
index e1326d072a9..a862ef2ff26 100644
--- a/snippets/csharp/System/String/Compare/cmpcmp.cs
+++ b/snippets/csharp/System/String/Compare/cmpcmp.cs
@@ -1,20 +1,20 @@
//
-// This example demonstrates the
+// This example demonstrates the
// System.String.Compare(String, String, StringComparison) method.
using System;
using System.Threading;
-class Sample
+class Sample
{
- public static void Main()
+ public static void Main()
{
- string intro = "Compare three versions of the letter I using different " +
+ string intro = "Compare three versions of the letter I using different " +
"values of StringComparison.";
- // Define an array of strings where each element contains a version of the
- // letter I. (An array of strings is used so you can easily modify this
- // code example to test additional or different combinations of strings.)
+ // Define an array of strings where each element contains a version of the
+ // letter I. (An array of strings is used so you can easily modify this
+ // code example to test additional or different combinations of strings.)
string[] threeIs = new string[3];
// LATIN SMALL LETTER I (U+0069)
@@ -24,10 +24,10 @@ public static void Main()
// LATIN CAPITAL LETTER I (U+0049)
threeIs[2] = "\u0049";
- string[] unicodeNames =
+ string[] unicodeNames =
{
- "LATIN SMALL LETTER I (U+0069)",
- "LATIN SMALL LETTER DOTLESS I (U+0131)",
+ "LATIN SMALL LETTER I (U+0069)",
+ "LATIN SMALL LETTER DOTLESS I (U+0131)",
"LATIN CAPITAL LETTER I (U+0049)"
};
@@ -46,13 +46,12 @@ public static void Main()
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
- Console.WriteLine(
- "The current culture is {0}.\n", Thread.CurrentThread.CurrentCulture.Name);
+ Console.WriteLine($"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n");
- // Determine the relative sort order of three versions of the letter I.
+ // Determine the relative sort order of three versions of the letter I.
foreach (StringComparison sc in scValues)
{
- Console.WriteLine("StringComparison.{0}:", sc);
+ Console.WriteLine($"StringComparison.{sc}:");
// LATIN SMALL LETTER I (U+0069) : LATIN SMALL LETTER DOTLESS I (U+0131)
Test(0, 1, sc, threeIs, unicodeNames);
@@ -74,7 +73,7 @@ protected static void Test(
string result = "equal to";
int cmpValue = 0;
- cmpValue = String.Compare(testI[x], testI[y], comparison);
+ cmpValue = string.Compare(testI[x], testI[y], comparison);
if (cmpValue < 0)
result = "less than";
else if (cmpValue > 0)
diff --git a/snippets/csharp/System/String/Compare/comp3.cs b/snippets/csharp/System/String/Compare/comp3.cs
index 89664c5dc38..7cef9a0f887 100644
--- a/snippets/csharp/System/String/Compare/comp3.cs
+++ b/snippets/csharp/System/String/Compare/comp3.cs
@@ -6,18 +6,18 @@ class Sample3
public static void Main()
{
//
- String str1 = "machine";
- String str2 = "device";
- String str;
+ string str1 = "machine";
+ string str2 = "device";
+ string str;
int result;
Console.WriteLine();
- Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
- result = String.Compare(str1, 2, str2, 0, 2);
+ Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'");
+ result = string.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
- Console.Write("{0} ", str);
- Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
+ Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"substring '{str2.Substring(0, 2)}' in '{str2}'.");
/*
This example produces the following results:
diff --git a/snippets/csharp/System/String/Compare/comp4.cs b/snippets/csharp/System/String/Compare/comp4.cs
index d803d385a27..29d2db41492 100644
--- a/snippets/csharp/System/String/Compare/comp4.cs
+++ b/snippets/csharp/System/String/Compare/comp4.cs
@@ -6,28 +6,28 @@ class Sample4
public static void Main()
{
//
- String str1 = "MACHINE";
- String str2 = "machine";
- String str;
+ string str1 = "MACHINE";
+ string str2 = "machine";
+ string str;
int result;
Console.WriteLine();
- Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
+ Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'");
Console.WriteLine("Ignore case:");
- result = String.Compare(str1, 2, str2, 2, 2, true);
+ result = string.Compare(str1, 2, str2, 2, 2, true);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
- Console.Write("{0} ", str);
- Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
+ Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"substring '{str2.Substring(2, 2)}' in '{str2}'.");
Console.WriteLine();
Console.WriteLine("Honor case:");
- result = String.Compare(str1, 2, str2, 2, 2, false);
+ result = string.Compare(str1, 2, str2, 2, 2, false);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
- Console.Write("{0} ", str);
- Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
+ Console.Write($"Substring '{str1.Substring(2, 2)}' in '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"substring '{str2.Substring(2, 2)}' in '{str2}'.");
/*
This example produces the following results:
diff --git a/snippets/csharp/System/String/Compare/comp5.cs b/snippets/csharp/System/String/Compare/comp5.cs
index dbfc689f393..7b63b5266dc 100644
--- a/snippets/csharp/System/String/Compare/comp5.cs
+++ b/snippets/csharp/System/String/Compare/comp5.cs
@@ -8,27 +8,27 @@ class Sample5
public static void Main()
{
// 0123456
- String str1 = "MACHINE";
- String str2 = "machine";
- String str;
+ string str1 = "MACHINE";
+ string str2 = "machine";
+ string str;
int result;
Console.WriteLine();
- Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
+ Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'");
Console.WriteLine("Ignore case, Turkish culture:");
- result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
+ result = string.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
- Console.Write("{0} ", str);
- Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
+ Console.Write($"Substring '{str1.Substring(4, 2)}' in '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"substring '{str2.Substring(4, 2)}' in '{str2}'.");
Console.WriteLine();
Console.WriteLine("Ignore case, invariant culture:");
- result = String.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture);
+ result = string.Compare(str1, 4, str2, 4, 2, true, CultureInfo.InvariantCulture);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
- Console.Write("{0} ", str);
- Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
+ Console.Write($"Substring '{str1.Substring(4, 2)}' in '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"substring '{str2.Substring(4, 2)}' in '{str2}'.");
}
}
/*
diff --git a/snippets/csharp/System/String/Compare/compare02.cs b/snippets/csharp/System/String/Compare/compare02.cs
index d9335e5a87d..4492e2bbbba 100644
--- a/snippets/csharp/System/String/Compare/compare02.cs
+++ b/snippets/csharp/System/String/Compare/compare02.cs
@@ -6,24 +6,19 @@ static void Main()
{
//
// Create upper-case characters from their Unicode code units.
- String stringUpper = "\x0041\x0042\x0043";
+ string stringUpper = "\x0041\x0042\x0043";
// Create lower-case characters from their Unicode code units.
- String stringLower = "\x0061\x0062\x0063";
+ string stringLower = "\x0061\x0062\x0063";
// Display the strings.
- Console.WriteLine("Comparing '{0}' and '{1}':",
- stringUpper, stringLower);
+ Console.WriteLine($"Comparing '{stringUpper}' and '{stringLower}':");
// Compare the uppercased strings; the result is true.
- Console.WriteLine("The Strings are equal when capitalized? {0}",
- String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
- ? "true" : "false");
+ Console.WriteLine($"The Strings are equal when capitalized? {(string.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0 ? "true" : "false")}");
// The previous method call is equivalent to this Compare method, which ignores case.
- Console.WriteLine("The Strings are equal when case is ignored? {0}",
- String.Compare(stringUpper, stringLower, true) == 0
- ? "true" : "false" );
+ Console.WriteLine($"The Strings are equal when case is ignored? {(string.Compare(stringUpper, stringLower, true) == 0 ? "true" : "false")}");
// The example displays the following output:
// Comparing 'ABC' and 'abc':
diff --git a/snippets/csharp/System/String/Compare/compare21.cs b/snippets/csharp/System/String/Compare/compare21.cs
index d121700e920..d98cd894d54 100644
--- a/snippets/csharp/System/String/Compare/compare21.cs
+++ b/snippets/csharp/System/String/Compare/compare21.cs
@@ -8,8 +8,7 @@ public static void Main()
string s1 = "ani\u00ADmal";
string s2 = "animal";
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, s2, String.Compare(s1, s2));
+ Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2)}");
// The example displays the following output:
// Comparison of 'ani-mal' and 'animal': 0
diff --git a/snippets/csharp/System/String/Compare/compare22.cs b/snippets/csharp/System/String/Compare/compare22.cs
index f13a647852a..7151355a03e 100644
--- a/snippets/csharp/System/String/Compare/compare22.cs
+++ b/snippets/csharp/System/String/Compare/compare22.cs
@@ -8,8 +8,7 @@ public static void Main()
string s1 = "Ani\u00ADmal";
string s2 = "animal";
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, s2, String.Compare(s1, s2, true));
+ Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2, true)}");
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
diff --git a/snippets/csharp/System/String/Compare/compare23.cs b/snippets/csharp/System/String/Compare/compare23.cs
index 43f6d172e58..f110fe34f96 100644
--- a/snippets/csharp/System/String/Compare/compare23.cs
+++ b/snippets/csharp/System/String/Compare/compare23.cs
@@ -8,10 +8,8 @@ public static void Main()
//
string s1 = "Ani\u00ADmal";
string s2 = "animal";
-
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, s2, String.Compare(s1, s2, true,
- CultureInfo.InvariantCulture));
+
+ Console.WriteLine($"Comparison of '{s1}' and '{s2}': {string.Compare(s1, s2, true, CultureInfo.InvariantCulture)}");
// The example displays the following output:
// Comparison of 'Ani-mal' and 'animal': 0
diff --git a/snippets/csharp/System/String/Compare/remarks.cs b/snippets/csharp/System/String/Compare/remarks.cs
index 54a9ce78435..4ecab74e919 100644
--- a/snippets/csharp/System/String/Compare/remarks.cs
+++ b/snippets/csharp/System/String/Compare/remarks.cs
@@ -1,22 +1,16 @@
using System;
-using System.Globalization;
+
public class Remarks
{
- public static void Main()
- {
- Console.WriteLine("Hi!");
- }
+ public static void Main() => Console.WriteLine("Hi!");
}
// System.String.Compare(System.String,System.Int32,System.String,System.Int32,System.Int32)
public class CompareSample1_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -24,10 +18,7 @@ static bool IsFileURI(String path)
public class CompareSample1_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -35,10 +26,7 @@ static bool IsFileURI(String path)
public class CompareSample2_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -46,10 +34,7 @@ static bool IsFileURI(String path)
public class CompareSample2_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -58,10 +43,7 @@ static bool IsFileURI(String path)
public class CompareSample3_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -70,10 +52,7 @@ static bool IsFileURI(String path)
public class CompareSample3_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -82,10 +61,7 @@ static bool IsFileURI(String path)
public class CompareSample4_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -94,10 +70,7 @@ static bool IsFileURI(String path)
public class CompareSample4_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -105,10 +78,7 @@ static bool IsFileURI(String path)
public class CompareSample5_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -116,10 +86,7 @@ static bool IsFileURI(String path)
public class CompareSample5_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -127,10 +94,7 @@ static bool IsFileURI(String path)
public class CompareSample6_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -138,10 +102,7 @@ static bool IsFileURI(String path)
public class CompareSample6_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -149,10 +110,7 @@ static bool IsFileURI(String path)
public class CompareSample7_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -160,10 +118,7 @@ static bool IsFileURI(String path)
public class CompareSample7_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
@@ -171,10 +126,7 @@ static bool IsFileURI(String path)
public class CompareSample8_1
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, true) == 0);
//
}
@@ -182,9 +134,6 @@ static bool IsFileURI(String path)
public class CompareSample8_2
{
//
- static bool IsFileURI(String path)
- {
- return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
- }
+ static bool IsFileURI(string path) => (string.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
//
}
diff --git a/snippets/csharp/System/String/Compare/string.comp4.cs b/snippets/csharp/System/String/Compare/string.comp4.cs
index 27c263c562f..1715fdc11a6 100644
--- a/snippets/csharp/System/String/Compare/string.comp4.cs
+++ b/snippets/csharp/System/String/Compare/string.comp4.cs
@@ -6,20 +6,20 @@ class Sample0
//
public static void Main()
{
- String str1 = "change";
- String str2 = "dollar";
- String relation;
+ string str1 = "change";
+ string str2 = "dollar";
+ string relation;
- relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US")));
- Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2);
+ relation = symbol(string.Compare(str1, str2, false, new CultureInfo("en-US")));
+ Console.WriteLine($"For en-US: {str1} {relation} {str2}");
- relation = symbol(String.Compare(str1, str2, false, new CultureInfo("cs-CZ")));
- Console.WriteLine("For cs-CZ: {0} {1} {2}", str1, relation, str2);
+ relation = symbol(string.Compare(str1, str2, false, new CultureInfo("cs-CZ")));
+ Console.WriteLine($"For cs-CZ: {str1} {relation} {str2}");
}
- private static String symbol(int r)
+ private static string symbol(int r)
{
- String s = "=";
+ string s = "=";
if (r < 0) s = "<";
else if (r > 0) s = ">";
return s;
diff --git a/snippets/csharp/System/String/CompareOrdinal/comp0.cs b/snippets/csharp/System/String/CompareOrdinal/comp0.cs
index b0aa972322a..e7355ed29c1 100644
--- a/snippets/csharp/System/String/CompareOrdinal/comp0.cs
+++ b/snippets/csharp/System/String/CompareOrdinal/comp0.cs
@@ -2,21 +2,23 @@
// Sample for String.CompareOrdinal(String, String)
using System;
-class Sample {
- public static void Main() {
- String str1 = "ABCD";
- String str2 = "abcd";
- String str;
- int result;
+class Sample
+{
+ public static void Main()
+ {
+ string str1 = "ABCD";
+ string str2 = "abcd";
+ string str;
+ int result;
- Console.WriteLine();
- Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string.");
- Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
- result = String.CompareOrdinal(str1, str2);
- str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
- Console.Write("String '{0}' is ", str1);
- Console.Write("{0} ", str);
- Console.WriteLine("String '{0}'.", str2);
+ Console.WriteLine();
+ Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string.");
+ Console.WriteLine($"str1 = '{str1}', str2 = '{str2}'");
+ result = string.CompareOrdinal(str1, str2);
+ str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
+ Console.Write($"String '{str1}' is ");
+ Console.Write($"{str} ");
+ Console.WriteLine($"String '{str2}'.");
}
}
/*
@@ -26,4 +28,4 @@ Compare the numeric values of the corresponding Char objects in each string.
str1 = 'ABCD', str2 = 'abcd'
String 'ABCD' is less than String 'abcd'.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs b/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs
index 4f7777b9761..beee0b53fc2 100644
--- a/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs
+++ b/snippets/csharp/System/String/CompareOrdinal/stringcompareordinal.cs
@@ -4,27 +4,27 @@
class Test
{
- public static void Main(String[] args)
- {
- String strLow = "abc";
- String strCap = "ABC";
- String result = "equal to ";
- int x = 0;
- int pos = 1;
+ public static void Main(string[] args)
+ {
+ string strLow = "abc";
+ string strCap = "ABC";
+ string result = "equal to ";
+ int x = 0;
+ int pos = 1;
-// The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
- x = String.CompareOrdinal(strLow, pos, strCap, pos, 1);
- if (x < 0) result = "less than";
- if (x > 0) result = "greater than";
- Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
- Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
+ // The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
+ x = string.CompareOrdinal(strLow, pos, strCap, pos, 1);
+ if (x < 0) result = "less than";
+ if (x > 0) result = "greater than";
+ Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
+ Console.WriteLine($" '{strLow[pos]}' is {result} '{strCap[pos]}'");
-// In U.S. English culture, 'b' is linguistically less than 'B'.
- x = String.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US"));
- if (x < 0) result = "less than";
- else if (x > 0) result = "greater than";
- Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
- Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
- }
+ // In U.S. English culture, 'b' is linguistically less than 'B'.
+ x = string.Compare(strLow, pos, strCap, pos, 1, false, new CultureInfo("en-US"));
+ if (x < 0) result = "less than";
+ else if (x > 0) result = "greater than";
+ Console.WriteLine("Compare(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
+ Console.WriteLine($" '{strLow[pos]}' is {result} '{strCap[pos]}'");
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/CompareTo/Program.cs b/snippets/csharp/System/String/CompareTo/Program.cs
new file mode 100644
index 00000000000..93f10cb2416
--- /dev/null
+++ b/snippets/csharp/System/String/CompareTo/Program.cs
@@ -0,0 +1,4 @@
+Example.Run();
+CompareToStringExample.Run();
+CompareToObjectExample.Run();
+CompareStringsExample.Run();
diff --git a/snippets/csharp/System/String/CompareTo/Project.csproj b/snippets/csharp/System/String/CompareTo/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/CompareTo/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/CompareTo/compareto1.cs b/snippets/csharp/System/String/CompareTo/compareto1.cs
index 31bd2bce666..1100bd72a7c 100644
--- a/snippets/csharp/System/String/CompareTo/compareto1.cs
+++ b/snippets/csharp/System/String/CompareTo/compareto1.cs
@@ -3,14 +3,13 @@
public class Example
{
- public static void Main()
- {
- string s1 = "ani\u00ADmal";
- object o1 = "animal";
-
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, o1, s1.CompareTo(o1));
- }
+ public static void Run()
+ {
+ string s1 = "ani\u00ADmal";
+ object o1 = "animal";
+
+ Console.WriteLine($"Comparison of '{s1}' and '{o1}': {s1.CompareTo(o1)}");
+ }
}
// The example displays the following output:
// Comparison of 'ani-mal' and 'animal': 0
diff --git a/snippets/csharp/System/String/CompareTo/compareto2.cs b/snippets/csharp/System/String/CompareTo/compareto2.cs
index e45f43f1359..85e8a397519 100644
--- a/snippets/csharp/System/String/CompareTo/compareto2.cs
+++ b/snippets/csharp/System/String/CompareTo/compareto2.cs
@@ -1,16 +1,15 @@
//
using System;
-public class Example
+public class CompareToStringExample
{
- public static void Main()
- {
- string s1 = "ani\u00ADmal";
- string s2 = "animal";
-
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, s2, s1.CompareTo(s2));
- }
+ public static void Run()
+ {
+ string s1 = "ani\u00ADmal";
+ string s2 = "animal";
+
+ Console.WriteLine($"Comparison of '{s1}' and '{s2}': {s1.CompareTo(s2)}");
+ }
}
// The example displays the following output:
// Comparison of 'ani-mal' and 'animal': 0
diff --git a/snippets/csharp/System/String/CompareTo/extostring.cs b/snippets/csharp/System/String/CompareTo/extostring.cs
index 625e49d9362..4fa5ee468fc 100644
--- a/snippets/csharp/System/String/CompareTo/extostring.cs
+++ b/snippets/csharp/System/String/CompareTo/extostring.cs
@@ -2,30 +2,30 @@
using System;
public class TestClass
-{}
+{ }
-public class Example
+public class CompareToObjectExample
{
- public static void Main()
- {
- var test = new TestClass();
- Object[] objectsToCompare = { test, test.ToString(), 123,
+ public static void Run()
+ {
+ var test = new TestClass();
+ object[] objectsToCompare = [ test, test.ToString(), 123,
123.ToString(), "some text",
- "Some Text" };
- string s = "some text";
- foreach (var objectToCompare in objectsToCompare) {
- try {
- int i = s.CompareTo(objectToCompare);
- Console.WriteLine("Comparing '{0}' with '{1}': {2}",
- s, objectToCompare, i);
- }
- catch (ArgumentException) {
- Console.WriteLine("Bad argument: {0} (type {1})",
- objectToCompare,
- objectToCompare.GetType().Name);
- }
- }
- }
+ "Some Text" ];
+ string s = "some text";
+ foreach (object objectToCompare in objectsToCompare)
+ {
+ try
+ {
+ int i = s.CompareTo(objectToCompare);
+ Console.WriteLine($"Comparing '{s}' with '{objectToCompare}': {i}");
+ }
+ catch (ArgumentException)
+ {
+ Console.WriteLine($"Bad argument: {objectToCompare} (type {objectToCompare.GetType().Name})");
+ }
+ }
+ }
}
// The example displays the following output:
// Bad argument: TestClass (type TestClass)
@@ -34,4 +34,4 @@ public static void Main()
// Comparing 'some text' with '123': 1
// Comparing 'some text' with 'some text': 0
// Comparing 'some text' with 'Some Text': -1
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/CompareTo/stringcompareto.cs b/snippets/csharp/System/String/CompareTo/stringcompareto.cs
index 2bce361d198..a03dc7fb675 100644
--- a/snippets/csharp/System/String/CompareTo/stringcompareto.cs
+++ b/snippets/csharp/System/String/CompareTo/stringcompareto.cs
@@ -1,37 +1,37 @@
//
using System;
-public class Example
+public class CompareStringsExample
{
- public static void Main()
- {
- string strFirst = "Goodbye";
- string strSecond = "Hello";
- string strThird = "a small string";
- string strFourth = "goodbye";
+ public static void Run()
+ {
+ string strFirst = "Goodbye";
+ string strSecond = "Hello";
+ string strThird = "a small string";
+ string strFourth = "goodbye";
- // Compare a string to itself.
- Console.WriteLine(CompareStrings(strFirst, strFirst));
+ // Compare a string to itself.
+ Console.WriteLine(CompareStrings(strFirst, strFirst));
- Console.WriteLine(CompareStrings(strFirst, strSecond));
- Console.WriteLine(CompareStrings(strFirst, strThird));
+ Console.WriteLine(CompareStrings(strFirst, strSecond));
+ Console.WriteLine(CompareStrings(strFirst, strThird));
- // Compare a string to another string that varies only by case.
- Console.WriteLine(CompareStrings(strFirst, strFourth));
- Console.WriteLine(CompareStrings(strFourth, strFirst));
- }
+ // Compare a string to another string that varies only by case.
+ Console.WriteLine(CompareStrings(strFirst, strFourth));
+ Console.WriteLine(CompareStrings(strFourth, strFirst));
+ }
- private static string CompareStrings( string str1, string str2 )
- {
- // Compare the values, using the CompareTo method on the first string.
- int cmpVal = str1.CompareTo(str2);
+ private static string CompareStrings(string str1, string str2)
+ {
+ // Compare the values, using the CompareTo method on the first string.
+ int cmpVal = str1.CompareTo(str2);
- if (cmpVal == 0) // The strings are the same.
- return "The strings occur in the same position in the sort order.";
- else if (cmpVal < 0)
- return "The first string precedes the second in the sort order.";
- else
- return "The first string follows the second in the sort order.";
+ if (cmpVal == 0) // The strings are the same.
+ return "The strings occur in the same position in the sort order.";
+ else if (cmpVal < 0)
+ return "The first string precedes the second in the sort order.";
+ else
+ return "The first string follows the second in the sort order.";
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/String/Concat/Concat6.cs b/snippets/csharp/System/String/Concat/Concat6.cs
index b8a0afb05fb..921272ddc85 100644
--- a/snippets/csharp/System/String/Concat/Concat6.cs
+++ b/snippets/csharp/System/String/Concat/Concat6.cs
@@ -1,18 +1,18 @@
//
using System;
-public class Example
+public class ConcatThreeStringsExample
{
- public static void Main()
- {
- String s1 = "We went to a bookstore, ";
- String s2 = "a movie, ";
- String s3 = "and a restaurant.";
+ public static void Run()
+ {
+ string s1 = "We went to a bookstore, ";
+ string s2 = "a movie, ";
+ string s3 = "and a restaurant.";
- var s = String.Concat(s1, s2, s3);
- Console.WriteLine(s);
- }
+ string s = string.Concat(s1, s2, s3);
+ Console.WriteLine(s);
+ }
}
// The example displays the following output:
-// We went to a bookstore, a movie, and a restaurant.
+// We went to a bookstore, a movie, and a restaurant.
//
diff --git a/snippets/csharp/System/String/Concat/Program.cs b/snippets/csharp/System/String/Concat/Program.cs
new file mode 100644
index 00000000000..fed8c0cab85
--- /dev/null
+++ b/snippets/csharp/System/String/Concat/Program.cs
@@ -0,0 +1,9 @@
+Example.Run();
+ConcatAlphabetExample.Run();
+ConcatAnimalsExample.Run();
+ConcatScrambleExample.Run();
+ConcatThreeStringsExample.Run();
+stringConcat5.Run();
+ConcatTest.Run();
+ConcatArrayExample.Run();
+ConcatNamesTest.Run();
diff --git a/snippets/csharp/System/String/Concat/Project.csproj b/snippets/csharp/System/String/Concat/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/Concat/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/Concat/concat1.cs b/snippets/csharp/System/String/Concat/concat1.cs
index ef899ccee4f..930347b105b 100644
--- a/snippets/csharp/System/String/Concat/concat1.cs
+++ b/snippets/csharp/System/String/Concat/concat1.cs
@@ -4,35 +4,35 @@
public class Example
{
- public static void Main()
- {
- int maxPrime = 100;
- IEnumerable primeList = GetPrimes(maxPrime);
- Console.WriteLine("Primes less than {0}:", maxPrime);
- Console.WriteLine(" {0}", String.Concat(primeList));
- }
+ public static void Run()
+ {
+ int maxPrime = 100;
+ IEnumerable primeList = GetPrimes(maxPrime);
+ Console.WriteLine($"Primes less than {maxPrime}:");
+ Console.WriteLine($" {string.Concat(primeList)}");
+ }
- private static IEnumerable GetPrimes(int maxPrime)
- {
- Array values = Array.CreateInstance(typeof(int),
- new int[] { maxPrime - 1}, new int[] { 2 });
- // Use Sieve of Erathsthenes to determine prime numbers.
- for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
- {
-
- if ((int) values.GetValue(ctr) == 1) continue;
-
- for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
- if (ctr * multiplier <= maxPrime)
- values.SetValue(1, ctr * multiplier);
- }
-
- List primes = new List();
- for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
- if ((int) values.GetValue(ctr) == 0)
- primes.Add(ctr.ToString() + " ");
- return primes;
- }
+ private static IEnumerable GetPrimes(int maxPrime)
+ {
+ Array values = Array.CreateInstance(typeof(int),
+ [maxPrime - 1], [2]);
+ // Use Sieve of Erathsthenes to determine prime numbers.
+ for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
+ {
+
+ if ((int)values.GetValue(ctr) == 1) continue;
+
+ for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
+ if (ctr * multiplier <= maxPrime)
+ values.SetValue(1, ctr * multiplier);
+ }
+
+ List primes = new();
+ for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
+ if ((int)values.GetValue(ctr) == 0)
+ primes.Add($"{ctr} ");
+ return primes;
+ }
}
// The example displays the following output:
// Primes less than 100:
diff --git a/snippets/csharp/System/String/Concat/concat2.cs b/snippets/csharp/System/String/Concat/concat2.cs
index 98be0070119..8cc4c92c82b 100644
--- a/snippets/csharp/System/String/Concat/concat2.cs
+++ b/snippets/csharp/System/String/Concat/concat2.cs
@@ -3,23 +3,23 @@
using System.Collections.Generic;
using System.Linq;
-public class Example
+public class ConcatAlphabetExample
{
- public static void Main()
- {
- string output = String.Concat( GetAlphabet(true).Where( letter =>
- letter.CompareTo("M") >= 0));
- Console.WriteLine(output);
- }
+ public static void Run()
+ {
+ string output = string.Concat(GetAlphabet(true).Where(letter =>
+ letter.CompareTo("M") >= 0));
+ Console.WriteLine(output);
+ }
- private static List GetAlphabet(bool upper)
- {
- List alphabet = new List();
- int charValue = upper ? 65 : 97;
- for (int ctr = 0; ctr <= 25; ctr++)
- alphabet.Add(((char)(charValue + ctr)).ToString());
- return alphabet;
- }
+ private static List GetAlphabet(bool upper)
+ {
+ List alphabet = new();
+ int charValue = upper ? 65 : 97;
+ for (int ctr = 0; ctr <= 25; ctr++)
+ alphabet.Add(((char)(charValue + ctr)).ToString());
+ return alphabet;
+ }
}
// The example displays the following output:
// MNOPQRSTUVWXYZ
diff --git a/snippets/csharp/System/String/Concat/concat3.cs b/snippets/csharp/System/String/Concat/concat3.cs
index f190c57005c..f856ef97a5a 100644
--- a/snippets/csharp/System/String/Concat/concat3.cs
+++ b/snippets/csharp/System/String/Concat/concat3.cs
@@ -5,33 +5,32 @@
public class Animal
{
- public string Kind;
- public string Order;
-
- public Animal(string kind, string order)
- {
- this.Kind = kind;
- this.Order = order;
- }
-
- public override string ToString()
- {
- return this.Kind;
- }
+ public string Kind;
+ public string Order;
+
+ public Animal(string kind, string order)
+ {
+ this.Kind = kind;
+ this.Order = order;
+ }
+
+ public override string ToString() => this.Kind;
}
-public class Example
+public class ConcatAnimalsExample
{
- public static void Main()
- {
- List animals = new List();
- animals.Add(new Animal("Squirrel", "Rodent"));
- animals.Add(new Animal("Gray Wolf", "Carnivora"));
- animals.Add(new Animal("Capybara", "Rodent"));
- string output = String.Concat(animals.Where( animal =>
- (animal.Order == "Rodent")));
- Console.WriteLine(output);
- }
+ public static void Run()
+ {
+ List animals = new()
+ {
+ new Animal("Squirrel", "Rodent"),
+ new Animal("Gray Wolf", "Carnivora"),
+ new Animal("Capybara", "Rodent")
+ };
+ string output = string.Concat(animals.Where(animal =>
+ (animal.Order == "Rodent")));
+ Console.WriteLine(output);
+ }
}
// The example displays the following output:
// SquirrelCapybara
diff --git a/snippets/csharp/System/String/Concat/concat4.cs b/snippets/csharp/System/String/Concat/concat4.cs
index c2ddee888f6..d5bdeca7159 100644
--- a/snippets/csharp/System/String/Concat/concat4.cs
+++ b/snippets/csharp/System/String/Concat/concat4.cs
@@ -2,42 +2,42 @@
using System;
using System.Collections;
-public class Example
+public class ConcatScrambleExample
{
- public static void Main()
- {
- const int WORD_SIZE = 4;
-
- // Define some 4-letter words to be scrambled.
- string[] words = { "home", "food", "game", "rest" };
- // Define two arrays equal to the number of letters in each word.
- double[] keys = new double[WORD_SIZE];
- string[] letters = new string[WORD_SIZE];
- // Initialize the random number generator.
- Random rnd = new Random();
-
- // Scramble each word.
- foreach (string word in words)
- {
- for (int ctr = 0; ctr < word.Length; ctr++)
- {
- // Populate the array of keys with random numbers.
- keys[ctr] = rnd.NextDouble();
- // Assign a letter to the array of letters.
- letters[ctr] = word[ctr].ToString();
- }
- // Sort the array.
- Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default);
- // Display the scrambled word.
- string scrambledWord = String.Concat(letters[0], letters[1],
- letters[2], letters[3]);
- Console.WriteLine("{0} --> {1}", word, scrambledWord);
- }
- }
+ public static void Run()
+ {
+ const int WORD_SIZE = 4;
+
+ // Define some 4-letter words to be scrambled.
+ string[] words = ["home", "food", "game", "rest"];
+ // Define two arrays equal to the number of letters in each word.
+ double[] keys = new double[WORD_SIZE];
+ string[] letters = new string[WORD_SIZE];
+ // Initialize the random number generator.
+ Random rnd = new();
+
+ // Scramble each word.
+ foreach (string word in words)
+ {
+ for (int ctr = 0; ctr < word.Length; ctr++)
+ {
+ // Populate the array of keys with random numbers.
+ keys[ctr] = rnd.NextDouble();
+ // Assign a letter to the array of letters.
+ letters[ctr] = word[ctr].ToString();
+ }
+ // Sort the array.
+ Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default);
+ // Display the scrambled word.
+ string scrambledWord = string.Concat(letters[0], letters[1],
+ letters[2], letters[3]);
+ Console.WriteLine($"{word} --> {scrambledWord}");
+ }
+ }
}
// The example displays output like the following:
// home --> mheo
// food --> oodf
// game --> aemg
// rest --> trse
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Concat/string.concat5.cs b/snippets/csharp/System/String/Concat/string.concat5.cs
index 7f2f7ac1123..ae056927f44 100644
--- a/snippets/csharp/System/String/Concat/string.concat5.cs
+++ b/snippets/csharp/System/String/Concat/string.concat5.cs
@@ -1,23 +1,25 @@
//
using System;
-class stringConcat5 {
- public static void Main() {
- int i = -123;
- Object o = i;
- Object[] objs = new Object[] {-123, -456, -789};
+class stringConcat5
+{
+ public static void Run()
+ {
+ int i = -123;
+ object o = i;
+ object[] objs = [-123, -456, -789];
- Console.WriteLine("Concatenate 1, 2, and 3 objects:");
- Console.WriteLine("1) {0}", String.Concat(o));
- Console.WriteLine("2) {0}", String.Concat(o, o));
- Console.WriteLine("3) {0}", String.Concat(o, o, o));
+ Console.WriteLine("Concatenate 1, 2, and 3 objects:");
+ Console.WriteLine($"1) {string.Concat(o)}");
+ Console.WriteLine($"2) {string.Concat(o, o)}");
+ Console.WriteLine($"3) {string.Concat(o, o, o)}");
- Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:");
- Console.WriteLine("4) {0}", String.Concat(o, o, o, o));
- Console.WriteLine("5) {0}", String.Concat(o, o, o, o, o));
+ Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:");
+ Console.WriteLine($"4) {string.Concat(o, o, o, o)}");
+ Console.WriteLine($"5) {string.Concat(o, o, o, o, o)}");
- Console.WriteLine("\nConcatenate a 3-element object array:");
- Console.WriteLine("6) {0}", String.Concat(objs));
+ Console.WriteLine("\nConcatenate a 3-element object array:");
+ Console.WriteLine($"6) {string.Concat(objs)}");
}
}
// The example displays the following output:
@@ -32,4 +34,4 @@ public static void Main() {
//
// Concatenate a 3-element object array:
// 6) -123-456-789
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Concat/stringconcat1.cs b/snippets/csharp/System/String/Concat/stringconcat1.cs
index 3f9b60503d1..f7024531cc7 100644
--- a/snippets/csharp/System/String/Concat/stringconcat1.cs
+++ b/snippets/csharp/System/String/Concat/stringconcat1.cs
@@ -1,16 +1,18 @@
//
using System;
-public class ConcatTest {
- public static void Main() {
+public class ConcatTest
+{
+ public static void Run()
+ {
// Create a group of objects.
- Test1 t1 = new Test1();
- Test2 t2 = new Test2();
+ Test1 t1 = new();
+ Test2 t2 = new();
int i = 16;
string s = "Demonstration";
// Place the objects in an array.
- object [] o = { t1, i, t2, s };
+ object[] o = [t1, i, t2, s];
// Concatenate the objects together as a string. To do this,
// the ToString method of each of the objects is called.
@@ -19,10 +21,12 @@ public static void Main() {
}
// Create two empty test classes.
-class Test1 {
+class Test1
+{
}
-class Test2 {
+class Test2
+{
}
// The example displays the following output:
// Test116Test2Demonstration
diff --git a/snippets/csharp/System/String/Concat/stringconcat3.cs b/snippets/csharp/System/String/Concat/stringconcat3.cs
index 1bde39eb10b..7ae186d130d 100644
--- a/snippets/csharp/System/String/Concat/stringconcat3.cs
+++ b/snippets/csharp/System/String/Concat/stringconcat3.cs
@@ -1,13 +1,13 @@
//
using System;
-public class Example
+public class ConcatArrayExample
{
- public static void Main()
+ public static void Run()
{
// Make an array of strings. Note that we have included spaces.
- string [] s = { "hello ", "and ", "welcome ", "to ",
- "this ", "demo! " };
+ string[] s = [ "hello ", "and ", "welcome ", "to ",
+ "this ", "demo! " ];
// Put all the strings together.
Console.WriteLine(string.Concat(s));
diff --git a/snippets/csharp/System/String/Concat/stringconcat4.cs b/snippets/csharp/System/String/Concat/stringconcat4.cs
index 3f740f83532..dc51856e25a 100644
--- a/snippets/csharp/System/String/Concat/stringconcat4.cs
+++ b/snippets/csharp/System/String/Concat/stringconcat4.cs
@@ -1,8 +1,10 @@
//
using System;
-public class ConcatTest {
- public static void Main() {
+public class ConcatNamesTest
+{
+ public static void Run()
+ {
// we want to simply quickly add this person's name together
string fName = "Simon";
@@ -16,9 +18,9 @@ public static void Main() {
lName = " " + lName.Trim();
// this line simply concatenates the two strings
- Console.WriteLine("Welcome to this page, '{0}'!", string.Concat( string.Concat(fName, mName), lName ) );
+ Console.WriteLine($"Welcome to this page, '{string.Concat(string.Concat(fName, mName), lName)}'!");
}
}
// The example displays the following output:
// Welcome to this page, 'Simon Jake Harrows'!
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Contains/ContainsExt1.cs b/snippets/csharp/System/String/Contains/ContainsExt1.cs
index 7b68c95e12e..c9f4425d353 100644
--- a/snippets/csharp/System/String/Contains/ContainsExt1.cs
+++ b/snippets/csharp/System/String/Contains/ContainsExt1.cs
@@ -3,44 +3,44 @@
public static class StringExtensions
{
- public static bool Contains(this String str, String substring,
- StringComparison comp)
- {
+ public static bool Contains(this string str, string substring,
+ StringComparison comp)
+ {
if (substring == null)
- throw new ArgumentNullException("substring",
+ throw new ArgumentNullException("substring",
"substring cannot be null.");
else if (!Enum.IsDefined(typeof(StringComparison), comp))
throw new ArgumentException("comp is not a member of StringComparison",
"comp");
- return str.IndexOf(substring, comp) >= 0;
- }
+ return str.IndexOf(substring, comp) >= 0;
+ }
}
//
namespace App
{
-using System;
+ using System;
-public class Example
-{
- public static void Main()
+ public class Example
{
- //
- String s = "This is a string.";
- String sub1 = "this";
- Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1);
- StringComparison comp = StringComparison.Ordinal;
- Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp));
+ public static void Main()
+ {
+ //
+ string s = "This is a string.";
+ string sub1 = "this";
+ Console.WriteLine($"Does '{s}' contain '{sub1}'?");
+ StringComparison comp = StringComparison.Ordinal;
+ Console.WriteLine($" {comp:G}: {s.Contains(sub1, comp)}");
- comp = StringComparison.OrdinalIgnoreCase;
- Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp));
+ comp = StringComparison.OrdinalIgnoreCase;
+ Console.WriteLine($" {comp:G}: {s.Contains(sub1, comp)}");
- // The example displays the following output:
- // Does 'This is a string.' contain 'this'?
- // Ordinal: False
- // OrdinalIgnoreCase: True
- //
+ // The example displays the following output:
+ // Does 'This is a string.' contain 'this'?
+ // Ordinal: False
+ // OrdinalIgnoreCase: True
+ //
+ }
}
}
-}
diff --git a/snippets/csharp/System/String/Contains/cont.cs b/snippets/csharp/System/String/Contains/cont.cs
index fa2396b7b2e..3b6b5cace3f 100644
--- a/snippets/csharp/System/String/Contains/cont.cs
+++ b/snippets/csharp/System/String/Contains/cont.cs
@@ -8,13 +8,12 @@ public static void Main()
string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b = s1.Contains(s2);
- Console.WriteLine("'{0}' is in the string '{1}': {2}",
- s2, s1, b);
- if (b) {
+ Console.WriteLine($"'{s2}' is in the string '{s1}': {b}");
+ if (b)
+ {
int index = s1.IndexOf(s2);
if (index >= 0)
- Console.WriteLine("'{0} begins at character position {1}",
- s2, index + 1);
+ Console.WriteLine($"'{s2} begins at character position {index + 1}");
}
// This example displays the following output:
// 'fox' is in the string 'The quick brown fox jumps over the lazy dog': True
diff --git a/snippets/csharp/System/String/CopyTo/stringcopyto.cs b/snippets/csharp/System/String/CopyTo/stringcopyto.cs
index ed39c240864..37b57ea6415 100644
--- a/snippets/csharp/System/String/CopyTo/stringcopyto.cs
+++ b/snippets/csharp/System/String/CopyTo/stringcopyto.cs
@@ -1,30 +1,32 @@
//
using System;
-public class CopyToTest {
- public static void Main() {
+public class CopyToTest
+{
+ public static void Main()
+ {
// Embed an array of characters in a string
string strSource = "changed";
- char [] destination = { 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ',
- 'a', 'r', 'r', 'a', 'y' };
+ char[] destination = [ 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ',
+ 'a', 'r', 'r', 'a', 'y' ];
// Print the char array
- Console.WriteLine( destination );
+ Console.WriteLine(destination);
// Embed the source string in the destination string
- strSource.CopyTo ( 0, destination, 4, strSource.Length );
+ strSource.CopyTo(0, destination, 4, strSource.Length);
// Print the resulting array
- Console.WriteLine( destination );
+ Console.WriteLine(destination);
strSource = "A different string";
// Embed only a section of the source string in the destination
- strSource.CopyTo ( 2, destination, 3, 9 );
+ strSource.CopyTo(2, destination, 3, 9);
// Print the resulting array
- Console.WriteLine( destination );
+ Console.WriteLine(destination);
}
}
// The example displays the following output:
diff --git a/snippets/csharp/System/String/EndsWith/EndsWith1.cs b/snippets/csharp/System/String/EndsWith/EndsWith1.cs
index 5b188cc45d9..ad3510bb02f 100644
--- a/snippets/csharp/System/String/EndsWith/EndsWith1.cs
+++ b/snippets/csharp/System/String/EndsWith/EndsWith1.cs
@@ -3,16 +3,16 @@
public class Example
{
- public static void Main()
- {
- String[] strings = { "This is a string.", "Hello!", "Nothing.",
- "Yes.", "randomize" };
- foreach (var value in strings) {
- bool endsInPeriod = value.EndsWith(".");
- Console.WriteLine("'{0}' ends in a period: {1}",
- value, endsInPeriod);
- }
- }
+ public static void Run()
+ {
+ string[] strings = [ "This is a string.", "Hello!", "Nothing.",
+ "Yes.", "randomize" ];
+ foreach (string value in strings)
+ {
+ bool endsInPeriod = value.EndsWith(".");
+ Console.WriteLine($"'{value}' ends in a period: {endsInPeriod}");
+ }
+ }
}
// The example displays the following output:
// 'This is a string.' ends in a period: True
diff --git a/snippets/csharp/System/String/EndsWith/Program.cs b/snippets/csharp/System/String/EndsWith/Program.cs
new file mode 100644
index 00000000000..5a20e5f7321
--- /dev/null
+++ b/snippets/csharp/System/String/EndsWith/Program.cs
@@ -0,0 +1,4 @@
+Example.Run();
+EndsWithCultureSample.Run();
+EndsWithComparisonSample.Run();
+EndsWithTest.Run();
diff --git a/snippets/csharp/System/String/EndsWith/Project.csproj b/snippets/csharp/System/String/EndsWith/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/EndsWith/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/EndsWith/ewci.cs b/snippets/csharp/System/String/EndsWith/ewci.cs
index d6b248fc191..c0e192e0dc0 100644
--- a/snippets/csharp/System/String/EndsWith/ewci.cs
+++ b/snippets/csharp/System/String/EndsWith/ewci.cs
@@ -1,14 +1,14 @@
//
-// This code example demonstrates the
+// This code example demonstrates the
// System.String.EndsWith(String, ..., CultureInfo) method.
using System;
-using System.Threading;
+
using System.Globalization;
-class Sample
+class EndsWithCultureSample
{
- public static void Main()
+ public static void Run()
{
string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
string msg2 = "Using the {0} - \"{1}\" culture:";
@@ -20,9 +20,9 @@ public static void Main()
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string capitalARing = "\u00c5";
- // Define a string to search.
- // The result of combining the characters LATIN SMALL LETTER A and COMBINING
- // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
+ // Define a string to search.
+ // The result of combining the characters LATIN SMALL LETTER A and COMBINING
+ // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string xyzARing = "xyz" + "\u0061\u030a";
@@ -30,7 +30,7 @@ public static void Main()
Console.WriteLine(msg1, capitalARing, xyzARing);
// Search using English-United States culture.
- ci = new CultureInfo("en-US");
+ ci = new("en-US");
Console.WriteLine(msg2, ci.DisplayName, ci.Name);
Console.WriteLine("Case sensitive:");
@@ -43,7 +43,7 @@ public static void Main()
Console.WriteLine();
// Search using Swedish-Sweden culture.
- ci = new CultureInfo("sv-SE");
+ ci = new("sv-SE");
Console.WriteLine(msg2, ci.DisplayName, ci.Name);
Console.WriteLine("Case sensitive:");
diff --git a/snippets/csharp/System/String/EndsWith/ewcmp.cs b/snippets/csharp/System/String/EndsWith/ewcmp.cs
index f3e592bcd1d..56a1945198c 100644
--- a/snippets/csharp/System/String/EndsWith/ewcmp.cs
+++ b/snippets/csharp/System/String/EndsWith/ewcmp.cs
@@ -1,36 +1,35 @@
//
-// This example demonstrates the
+// This example demonstrates the
// System.String.EndsWith(String, StringComparison) method.
using System;
using System.Threading;
-class Sample
+class EndsWithComparisonSample
{
- public static void Main()
+ public static void Run()
{
string intro = "Determine whether a string ends with another string, " +
"using\n different values of StringComparison.";
- StringComparison[] scValues = {
+ StringComparison[] scValues = [
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
- StringComparison.OrdinalIgnoreCase };
+ StringComparison.OrdinalIgnoreCase ];
Console.WriteLine(intro);
// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
- Console.WriteLine("The current culture is {0}.\n",
- Thread.CurrentThread.CurrentCulture.Name);
-
- // Determine whether three versions of the letter I are equal to each other.
+ Console.WriteLine($"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n");
+
+ // Determine whether three versions of the letter I are equal to each other.
foreach (StringComparison sc in scValues)
{
- Console.WriteLine("StringComparison.{0}:", sc);
+ Console.WriteLine($"StringComparison.{sc}:");
Test("abcXYZ", "XYZ", sc);
Test("abcXYZ", "xyz", sc);
Console.WriteLine();
diff --git a/snippets/csharp/System/String/EndsWith/stringendswith.cs b/snippets/csharp/System/String/EndsWith/stringendswith.cs
index 9fb10ebeefe..0649ce366c8 100644
--- a/snippets/csharp/System/String/EndsWith/stringendswith.cs
+++ b/snippets/csharp/System/String/EndsWith/stringendswith.cs
@@ -1,25 +1,27 @@
//
using System;
-public class EndsWithTest {
- public static void Main() {
+public class EndsWithTest
+{
+ public static void Run()
+ {
// process an input file that contains html tags.
// this sample checks for multiple tags at the end of the line, rather than simply
// removing the last one.
// note: HTML markup tags always end in a greater than symbol (>).
- string [] strSource = { "This is bold text", "This is large Text
",
+ string[] strSource = [ "This is bold text", "This is large Text
",
"This has multiple tags",
"This has embedded tags.",
- "This line simply ends with a greater than symbol, it should not be modified>" };
+ "This line simply ends with a greater than symbol, it should not be modified>" ];
Console.WriteLine("The following lists the items before the ends have been stripped:");
Console.WriteLine("-----------------------------------------------------------------");
// print out the initial array of strings
- foreach ( string s in strSource )
- Console.WriteLine( s );
+ foreach (string s in strSource)
+ Console.WriteLine(s);
Console.WriteLine();
@@ -27,29 +29,32 @@ public static void Main() {
Console.WriteLine("----------------------------------------------------------------");
// print out the array of strings
- foreach (var s in strSource)
+ foreach (string s in strSource)
Console.WriteLine(StripEndTags(s));
}
- private static string StripEndTags( string item ) {
+ private static string StripEndTags(string item)
+ {
bool found = false;
// try to find a tag at the end of the line using EndsWith
- if (item.Trim().EndsWith(">")) {
+ if (item.Trim().EndsWith(">"))
+ {
// now search for the opening tag...
- int lastLocation = item.LastIndexOf( "" );
+ int lastLocation = item.LastIndexOf("");
// remove the identified section, if it is a valid region
- if ( lastLocation >= 0 ) {
+ if (lastLocation >= 0)
+ {
found = true;
- item = item.Substring( 0, lastLocation );
+ item = item.Substring(0, lastLocation);
}
}
if (found)
- item = StripEndTags(item);
+ item = StripEndTags(item);
return item;
}
@@ -70,4 +75,4 @@ private static string StripEndTags( string item ) {
// This has multiple tags
// This has embedded tags.
// This line simply ends with a greater than symbol, it should not be modified>
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Equals/eqcmp.cs b/snippets/csharp/System/String/Equals/eqcmp.cs
index e17f0f0d072..c59ffb10497 100644
--- a/snippets/csharp/System/String/Equals/eqcmp.cs
+++ b/snippets/csharp/System/String/Equals/eqcmp.cs
@@ -1,79 +1,75 @@
//
using System;
-class Sample
+class Sample
{
- public static void Main()
- {
- // Define a string array with the following three "I" characters:
- // U+0069, U+0131, and U+0049.
- string[] threeIs = { "i", "ı", "I" };
- // Define Type object representing StringComparison type.
- Type scType = typeof(StringComparison);
-
- // Show the current culture (for culture-sensitive string comparisons).
- Console.WriteLine("The current culture is {0}.\n",
- System.Globalization.CultureInfo.CurrentCulture.Name);
-
- // Perform comparisons using each StringComparison member.
- foreach (string scName in Enum.GetNames(scType))
- {
- StringComparison sc = (StringComparison) Enum.Parse(scType, scName);
- Console.WriteLine("Comparisons using {0}:", sc);
- // Compare each character in character array.
- for (int ctr = 0; ctr <= 1; ctr++)
- {
- string instanceChar = threeIs[ctr];
- for (int innerCtr = ctr + 1; innerCtr <= threeIs.GetUpperBound(0); innerCtr++)
+ public static void Main()
+ {
+ // Define a string array with the following three "I" characters:
+ // U+0069, U+0131, and U+0049.
+ string[] threeIs = ["i", "ı", "I"];
+ // Define Type object representing StringComparison type.
+ Type scType = typeof(StringComparison);
+
+ // Show the current culture (for culture-sensitive string comparisons).
+ Console.WriteLine($"The current culture is {System.Globalization.CultureInfo.CurrentCulture.Name}.\n");
+
+ // Perform comparisons using each StringComparison member.
+ foreach (string scName in Enum.GetNames(scType))
+ {
+ StringComparison sc = (StringComparison)Enum.Parse(scType, scName);
+ Console.WriteLine($"Comparisons using {sc}:");
+ // Compare each character in character array.
+ for (int ctr = 0; ctr <= 1; ctr++)
{
- string otherChar = threeIs[innerCtr];
- Console.WriteLine("{0} (U+{1}) = {2} (U+{3}): {4}",
- instanceChar, Convert.ToInt16(Char.Parse(instanceChar)).ToString("X4"),
- otherChar, Convert.ToInt16(Char.Parse(otherChar)).ToString("X4"),
- instanceChar.Equals(otherChar, sc));
+ string instanceChar = threeIs[ctr];
+ for (int innerCtr = ctr + 1; innerCtr <= threeIs.GetUpperBound(0); innerCtr++)
+ {
+ string otherChar = threeIs[innerCtr];
+ Console.WriteLine($"{instanceChar} (U+{Convert.ToInt16(char.Parse(instanceChar)):X4}) = {otherChar} (U+{Convert.ToInt16(char.Parse(otherChar)):X4}): {instanceChar.Equals(otherChar, sc)}");
+ }
+ Console.WriteLine();
}
- Console.WriteLine();
- }
- }
- }
+ }
+ }
}
// The example displays the following output:
// The current culture is en-US.
-//
+//
// Comparisons using CurrentCulture:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): False
-//
+//
// ı (U+0131) = I (U+0049): False
-//
+//
// Comparisons using CurrentCultureIgnoreCase:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): True
-//
+//
// ı (U+0131) = I (U+0049): False
-//
+//
// Comparisons using InvariantCulture:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): False
-//
+//
// ı (U+0131) = I (U+0049): False
-//
+//
// Comparisons using InvariantCultureIgnoreCase:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): True
-//
+//
// ı (U+0131) = I (U+0049): False
-//
+//
// Comparisons using Ordinal:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): False
-//
+//
// ı (U+0131) = I (U+0049): False
-//
+//
// Comparisons using OrdinalIgnoreCase:
// i (U+0069) = ı (U+0131): False
// i (U+0069) = I (U+0049): True
-//
+//
// ı (U+0131) = I (U+0049): False
//
// 119 lines
diff --git a/snippets/csharp/System/String/Equals/equals.cs b/snippets/csharp/System/String/Equals/equals.cs
index b243c862fe2..bb63520f4ed 100644
--- a/snippets/csharp/System/String/Equals/equals.cs
+++ b/snippets/csharp/System/String/Equals/equals.cs
@@ -9,34 +9,34 @@ class Sample1
{
public static void Main()
{
- StringBuilder sb = new StringBuilder("abcd");
- String str1 = "abcd";
- String str2 = null;
- Object o2 = null;
+ StringBuilder sb = new("abcd");
+ string str1 = "abcd";
+ string str2 = null;
+ object o2 = null;
Console.WriteLine();
- Console.WriteLine(" * The value of String str1 is '{0}'.", str1);
- Console.WriteLine(" * The value of StringBuilder sb is '{0}'.", sb.ToString());
+ Console.WriteLine($" * The value of String str1 is '{str1}'.");
+ Console.WriteLine($" * The value of StringBuilder sb is '{sb}'.");
Console.WriteLine();
Console.WriteLine("1a) String.Equals(Object). Object is a StringBuilder, not a String.");
- Console.WriteLine(" Is str1 equal to sb?: {0}", str1.Equals(sb));
+ Console.WriteLine($" Is str1 equal to sb?: {str1.Equals(sb)}");
Console.WriteLine();
Console.WriteLine("1b) String.Equals(Object). Object is a String.");
str2 = sb.ToString();
o2 = str2;
- Console.WriteLine(" * The value of Object o2 is '{0}'.", o2);
- Console.WriteLine(" Is str1 equal to o2?: {0}", str1.Equals(o2));
+ Console.WriteLine($" * The value of Object o2 is '{o2}'.");
+ Console.WriteLine($" Is str1 equal to o2?: {str1.Equals(o2)}");
Console.WriteLine();
Console.WriteLine(" 2) String.Equals(String)");
- Console.WriteLine(" * The value of String str2 is '{0}'.", str2);
- Console.WriteLine(" Is str1 equal to str2?: {0}", str1.Equals(str2));
+ Console.WriteLine($" * The value of String str2 is '{str2}'.");
+ Console.WriteLine($" Is str1 equal to str2?: {str1.Equals(str2)}");
Console.WriteLine();
Console.WriteLine(" 3) String.Equals(String, String)");
- Console.WriteLine(" Is str1 equal to str2?: {0}", String.Equals(str1, str2));
+ Console.WriteLine($" Is str1 equal to str2?: {string.Equals(str1, str2)}");
}
}
/*
diff --git a/snippets/csharp/System/String/Equals/equals_ex3.cs b/snippets/csharp/System/String/Equals/equals_ex3.cs
index a9ddb4936fa..8bbacdd1ad4 100644
--- a/snippets/csharp/System/String/Equals/equals_ex3.cs
+++ b/snippets/csharp/System/String/Equals/equals_ex3.cs
@@ -7,21 +7,19 @@ public class Example3
{
public static void Main()
{
- String[] cultureNames = { "en-US", "th-TH", "tr-TR" };
- String[] strings1 = { "a", "i", "case", };
- String[] strings2 = { "a-", "\u0130", "Case" };
+ string[] cultureNames = ["en-US", "th-TH", "tr-TR"];
+ string[] strings1 = ["a", "i", "case",];
+ string[] strings2 = ["a-", "\u0130", "Case"];
StringComparison[] comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
- foreach (var cultureName in cultureNames)
+ foreach (string cultureName in cultureNames)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
- Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.Name);
+ Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}");
for (int ctr = 0; ctr <= strings1.GetUpperBound(0); ctr++)
{
foreach (var comparison in comparisons)
- Console.WriteLine(" {0} = {1} ({2}): {3}", strings1[ctr],
- strings2[ctr], comparison,
- String.Equals(strings1[ctr], strings2[ctr], comparison));
+ Console.WriteLine($" {strings1[ctr]} = {strings2[ctr]} ({comparison}): {string.Equals(strings1[ctr], strings2[ctr], comparison)}");
Console.WriteLine();
}
diff --git a/snippets/csharp/System/String/Equals/equalsex1.cs b/snippets/csharp/System/String/Equals/equalsex1.cs
index 32d31457361..4aa4470fa6d 100644
--- a/snippets/csharp/System/String/Equals/equalsex1.cs
+++ b/snippets/csharp/System/String/Equals/equalsex1.cs
@@ -7,13 +7,13 @@ public static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
string word = "File";
- string[] others = { word.ToLower(), word, word.ToUpper(), "Fıle" };
+ string[] others = [word.ToLower(), word, word.ToUpper(), "Fıle"];
foreach (string other in others)
{
if (word.Equals(other))
- Console.WriteLine("{0} = {1}", word, other);
+ Console.WriteLine($"{word} = {other}");
else
- Console.WriteLine("{0} {1} {2}", word, '\u2260', other);
+ Console.WriteLine($"{word} {'\u2260'} {other}");
}
}
}
diff --git a/snippets/csharp/System/String/Format/Example1.cs b/snippets/csharp/System/String/Format/Example1.cs
index 1040735cbf8..3bc3b2a042f 100644
--- a/snippets/csharp/System/String/Format/Example1.cs
+++ b/snippets/csharp/System/String/Format/Example1.cs
@@ -2,24 +2,24 @@
public class Example1
{
- public static void Main()
- {
- //
- short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
- Console.WriteLine("{0,10} {1,10}\n", "Decimal", "Hex");
- foreach (short value in values)
- {
- string formatString = String.Format("{0,10:G}: {0,10:X}", value);
- Console.WriteLine(formatString);
- }
- // The example displays the following output:
- // Decimal Hex
- //
- // -32768: 8000
- // -27: FFE5
- // 0: 0
- // 1042: 412
- // 32767: 7FFF
- //
- }
+ public static void Main()
+ {
+ //
+ short[] values = [short.MinValue, -27, 0, 1042, short.MaxValue];
+ Console.WriteLine($"{"Decimal",10} {"Hex",10}\n");
+ foreach (short value in values)
+ {
+ string formatString = string.Format("{0,10:G}: {0,10:X}", value);
+ Console.WriteLine(formatString);
+ }
+ // The example displays the following output:
+ // Decimal Hex
+ //
+ // -32768: 8000
+ // -27: FFE5
+ // 0: 0
+ // 1042: 412
+ // 32767: 7FFF
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Format/Example2.cs b/snippets/csharp/System/String/Format/Example2.cs
index b33a5f30d9e..1f6eccf8ff3 100644
--- a/snippets/csharp/System/String/Format/Example2.cs
+++ b/snippets/csharp/System/String/Format/Example2.cs
@@ -1,31 +1,31 @@
using System;
-using System.Globalization;
+
public class Example2
{
- public static void Main()
- {
- //
- string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };
+ public static void Main()
+ {
+ //
+ string[] cultureNames = ["en-US", "fr-FR", "de-DE", "es-ES"];
- DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
- double value = 9164.32;
+ DateTime dateToDisplay = new(2009, 9, 1, 18, 32, 0);
+ double value = 9164.32;
- Console.WriteLine("Culture Date Value\n");
- foreach (string cultureName in cultureNames)
- {
- System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
- string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}",
- culture.Name, dateToDisplay, value);
- Console.WriteLine(output);
- }
- // The example displays the following output:
- // Culture Date Value
- //
- // en-US Tuesday, September 01, 2009 9,164.32
- // fr-FR mardi 1 septembre 2009 9 164,32
- // de-DE Dienstag, 1. September 2009 9.164,32
- // es-ES martes, 01 de septiembre de 2009 9.164,32
- //
- }
+ Console.WriteLine("Culture Date Value\n");
+ foreach (string cultureName in cultureNames)
+ {
+ System.Globalization.CultureInfo culture = new(cultureName);
+ string output = string.Format(culture, "{0,-11} {1,-35:D} {2:N}",
+ culture.Name, dateToDisplay, value);
+ Console.WriteLine(output);
+ }
+ // The example displays the following output:
+ // Culture Date Value
+ //
+ // en-US Tuesday, September 01, 2009 9,164.32
+ // fr-FR mardi 1 septembre 2009 9 164,32
+ // de-DE Dienstag, 1. September 2009 9.164,32
+ // es-ES martes, 01 de septiembre de 2009 9.164,32
+ //
+ }
}
diff --git a/snippets/csharp/System/String/GetEnumerator/getenumerator.cs b/snippets/csharp/System/String/GetEnumerator/getenumerator.cs
index 8c75ca9dd1b..384fdeee234 100644
--- a/snippets/csharp/System/String/GetEnumerator/getenumerator.cs
+++ b/snippets/csharp/System/String/GetEnumerator/getenumerator.cs
@@ -3,41 +3,41 @@
class Example
{
- public static void Main()
- {
- EnumerateAndDisplay("Test Case");
- EnumerateAndDisplay("This is a sentence.");
- EnumerateAndDisplay("Has\ttwo\ttabs" );
- EnumerateAndDisplay("Two\nnew\nlines");
- }
+ public static void Main()
+ {
+ EnumerateAndDisplay("Test Case");
+ EnumerateAndDisplay("This is a sentence.");
+ EnumerateAndDisplay("Has\ttwo\ttabs");
+ EnumerateAndDisplay("Two\nnew\nlines");
+ }
- static void EnumerateAndDisplay(String phrase)
- {
- Console.WriteLine("The characters in the string \"{0}\" are:",
- phrase);
+ static void EnumerateAndDisplay(string phrase)
+ {
+ Console.WriteLine($"The characters in the string \"{phrase}\" are:");
- int CharCount = 0;
- int controlChars = 0;
- int alphanumeric = 0;
- int punctuation = 0;
+ int CharCount = 0;
+ int controlChars = 0;
+ int alphanumeric = 0;
+ int punctuation = 0;
- foreach (var ch in phrase) {
- Console.Write(Char.IsControl(ch) ? $"{ch}" : $"0x{(ushort)ch:X4}");
+ foreach (char ch in phrase)
+ {
+ Console.Write(char.IsControl(ch) ? $"{ch}" : $"0x{(ushort)ch:X4}");
- if (Char.IsLetterOrDigit(ch))
- alphanumeric++;
- else if (Char.IsControl(ch))
- controlChars++;
- else if (Char.IsPunctuation(ch))
- punctuation++;
- CharCount++;
- }
+ if (char.IsLetterOrDigit(ch))
+ alphanumeric++;
+ else if (char.IsControl(ch))
+ controlChars++;
+ else if (char.IsPunctuation(ch))
+ punctuation++;
+ CharCount++;
+ }
- Console.WriteLine("\n Total characters: {0,3}", CharCount);
- Console.WriteLine(" Alphanumeric characters: {0,3}", alphanumeric);
- Console.WriteLine(" Punctuation characters: {0,3}", punctuation);
- Console.WriteLine(" Control Characters: {0,3}\n", controlChars);
- }
+ Console.WriteLine($"\n Total characters: {CharCount,3}");
+ Console.WriteLine($" Alphanumeric characters: {alphanumeric,3}");
+ Console.WriteLine($" Punctuation characters: {punctuation,3}");
+ Console.WriteLine($" Control Characters: {controlChars,3}\n");
+ }
}
// The example displays the following output:
// The characters in the string "Test Case" are:
@@ -46,21 +46,21 @@ static void EnumerateAndDisplay(String phrase)
// Alphanumeric characters: 8
// Punctuation characters: 0
// Control Characters: 0
-//
+//
// The characters in the string "This is a sentence." are:
// 'T' 'h' 'i' 's' ' ' 'i' 's' ' ' 'a' ' ' 's' 'e' 'n' 't' 'e' 'n' 'c' 'e' '.'
// Total characters: 19
// Alphanumeric characters: 15
// Punctuation characters: 1
// Control Characters: 0
-//
+//
// The characters in the string "Has two tabs" are:
// 'H' 'a' 's' '0x0009' 't' 'w' 'o' '0x0009' 't' 'a' 'b' 's'
// Total characters: 12
// Alphanumeric characters: 10
// Punctuation characters: 0
// Control Characters: 2
-//
+//
// The characters in the string "Two
// new
// lines" are:
diff --git a/snippets/csharp/System/String/GetHashCode/gethashcode.cs b/snippets/csharp/System/String/GetHashCode/gethashcode.cs
index be0146f6d53..d63cdb3fe0b 100644
--- a/snippets/csharp/System/String/GetHashCode/gethashcode.cs
+++ b/snippets/csharp/System/String/GetHashCode/gethashcode.cs
@@ -1,30 +1,30 @@
//
using System;
-class GetHashCode
+class GetHashCode
{
- public static void Main()
+ public static void Main()
{
- DisplayHashCode( "" );
- DisplayHashCode( "a" );
- DisplayHashCode( "ab" );
- DisplayHashCode( "abc" );
- DisplayHashCode( "abd" );
- DisplayHashCode( "abe" );
- DisplayHashCode( "abcdef" );
- DisplayHashCode( "abcdeg" );
- DisplayHashCode( "abcdeh" );
- DisplayHashCode( "abcdei" );
- DisplayHashCode( "Abcdeg" );
- DisplayHashCode( "Abcdeh" );
- DisplayHashCode( "Abcdei" );
+ DisplayHashCode("");
+ DisplayHashCode("a");
+ DisplayHashCode("ab");
+ DisplayHashCode("abc");
+ DisplayHashCode("abd");
+ DisplayHashCode("abe");
+ DisplayHashCode("abcdef");
+ DisplayHashCode("abcdeg");
+ DisplayHashCode("abcdeh");
+ DisplayHashCode("abcdei");
+ DisplayHashCode("Abcdeg");
+ DisplayHashCode("Abcdeh");
+ DisplayHashCode("Abcdei");
}
- static void DisplayHashCode( String Operand )
+ static void DisplayHashCode(string Operand)
{
- int HashCode = Operand.GetHashCode( );
+ int HashCode = Operand.GetHashCode();
Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}",
- Operand, HashCode );
+ Operand, HashCode);
}
}
/*
diff --git a/snippets/csharp/System/String/GetHashCode/perdomain.cs b/snippets/csharp/System/String/GetHashCode/perdomain.cs
index ab65986cc17..cdf6cd6fef7 100644
--- a/snippets/csharp/System/String/GetHashCode/perdomain.cs
+++ b/snippets/csharp/System/String/GetHashCode/perdomain.cs
@@ -3,53 +3,39 @@
public class Example
{
- public static void Main()
- {
- // Show hash code in current domain.
- DisplayString display = new DisplayString();
- display.ShowStringHashCode();
-
- // Create a new app domain and show string hash code.
- AppDomain domain = AppDomain.CreateDomain("NewDomain");
- var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName,
- "DisplayString");
- display2.ShowStringHashCode();
- }
+ public static void Main()
+ {
+ // Show hash code in current domain.
+ DisplayString display = new();
+ display.ShowStringHashCode();
+
+ // Create a new app domain and show string hash code.
+ AppDomain domain = AppDomain.CreateDomain("NewDomain");
+ var display2 = (DisplayString)domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName,
+ "DisplayString");
+ display2.ShowStringHashCode();
+ }
}
public class DisplayString : MarshalByRefObject
{
- private String s = "This is a string.";
-
- public override bool Equals(Object obj)
- {
- String s2 = obj as String;
- if (s2 == null)
- return false;
- else
- return s == s2;
- }
-
- public bool Equals(String str)
- {
- return s == str;
- }
-
- public override int GetHashCode()
- {
- return s.GetHashCode();
- }
-
- public override String ToString()
- {
- return s;
- }
-
- public void ShowStringHashCode()
- {
- Console.WriteLine("String '{0}' in domain '{1}': {2:X8}",
- s, AppDomain.CurrentDomain.FriendlyName,
- s.GetHashCode());
- }
+ private string s = "This is a string.";
+
+ public override bool Equals(object obj)
+ {
+ string s2 = obj as string;
+ if (s2 == null)
+ return false;
+ else
+ return s == s2;
+ }
+
+ public bool Equals(string str) => s == str;
+
+ public override int GetHashCode() => s.GetHashCode();
+
+ public override string ToString() => s;
+
+ public void ShowStringHashCode() => Console.WriteLine($"String '{s}' in domain '{AppDomain.CurrentDomain.FriendlyName}': {s.GetHashCode():X8}");
}
//
diff --git a/snippets/csharp/System/String/GetTypeCode/gtc.cs b/snippets/csharp/System/String/GetTypeCode/gtc.cs
index c5356ddf9a5..2d70716b99e 100644
--- a/snippets/csharp/System/String/GetTypeCode/gtc.cs
+++ b/snippets/csharp/System/String/GetTypeCode/gtc.cs
@@ -6,14 +6,13 @@ class Sample
{
public static void Main()
{
- String str = "abc";
- TypeCode tc = str.GetTypeCode();
- Console.WriteLine("The type code for '{0}' is {1}, which represents {2}.",
- str, tc.ToString("D"), tc.ToString("F"));
+ string str = "abc";
+ TypeCode tc = str.GetTypeCode();
+ Console.WriteLine($"The type code for '{str}' is {tc:D}, which represents {tc:F}.");
}
}
/*
This example produces the following results:
The type code for 'abc' is 18, which represents String.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/IndexOf/Program.cs b/snippets/csharp/System/String/IndexOf/Program.cs
new file mode 100644
index 00000000000..b505b064718
--- /dev/null
+++ b/snippets/csharp/System/String/IndexOf/Program.cs
@@ -0,0 +1,14 @@
+IndexOfIgnorable21Example.Run();
+IndexOfIgnorable22Example.Run();
+IndexOfIgnorable23Example.Run();
+IndexOfIgnorable24Example.Run();
+IndexOfIgnorable25Example.Run();
+IndexOfIgnorable26Example.Run();
+IndexOfCharExample.Run();
+IndexOfCII.Run();
+IndexOfComparisonSample.Run();
+IndexOfCharStartSample.Run();
+IndexOfStringRangeSample.Run();
+IndexOfSimpleExample.Run();
+IndexOfTest.Run();
+IndexOfInsertExample.Run();
diff --git a/snippets/csharp/System/String/IndexOf/Project.csproj b/snippets/csharp/System/String/IndexOf/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/IndexOf/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/IndexOf/ignorable21.cs b/snippets/csharp/System/String/IndexOf/ignorable21.cs
index 29b182f331b..b0d6f02fb2d 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable21.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable21.cs
@@ -1,9 +1,9 @@
//
using System;
-public class Example
+public class IndexOfIgnorable21Example
{
- public static void Main()
+ public static void Run()
{
string s1 = "ani\u00ADmal";
string s2 = "animal";
diff --git a/snippets/csharp/System/String/IndexOf/ignorable22.cs b/snippets/csharp/System/String/IndexOf/ignorable22.cs
index e1180339da9..309de8e989d 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable22.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable22.cs
@@ -1,12 +1,12 @@
//
using System;
-public class Example
+public class IndexOfIgnorable22Example
{
- public static void Main()
+ public static void Run()
{
string searchString = "\u00ADm";
- string s1 = "ani\u00ADmal" ;
+ string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2));
diff --git a/snippets/csharp/System/String/IndexOf/ignorable23.cs b/snippets/csharp/System/String/IndexOf/ignorable23.cs
index be4b57bf6f2..ab2ad572ff7 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable23.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable23.cs
@@ -1,12 +1,12 @@
//
using System;
-public class Example
+public class IndexOfIgnorable23Example
{
- public static void Main()
+ public static void Run()
{
string searchString = "\u00ADm";
- string s1 = "ani\u00ADmal" ;
+ string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2, 4));
diff --git a/snippets/csharp/System/String/IndexOf/ignorable24.cs b/snippets/csharp/System/String/IndexOf/ignorable24.cs
index c63cb7df854..b3ccc5efb99 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable24.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable24.cs
@@ -1,13 +1,13 @@
//
using System;
-public class Example
+public class IndexOfIgnorable24Example
{
- public static void Main()
+ public static void Run()
{
string searchString = "\u00ADm";
- string s1 = "ani\u00ADmal" ;
+ string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
diff --git a/snippets/csharp/System/String/IndexOf/ignorable25.cs b/snippets/csharp/System/String/IndexOf/ignorable25.cs
index b5d9fafe11a..4113d5dec59 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable25.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable25.cs
@@ -1,13 +1,13 @@
//
using System;
-public class Example
+public class IndexOfIgnorable25Example
{
- public static void Main()
+ public static void Run()
{
-
+
string searchString = "\u00ADm";
- string s1 = "ani\u00ADmal" ;
+ string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.CurrentCulture));
diff --git a/snippets/csharp/System/String/IndexOf/ignorable26.cs b/snippets/csharp/System/String/IndexOf/ignorable26.cs
index 61944637145..5c39f7f5943 100644
--- a/snippets/csharp/System/String/IndexOf/ignorable26.cs
+++ b/snippets/csharp/System/String/IndexOf/ignorable26.cs
@@ -1,35 +1,35 @@
//
using System;
-public class Example
+public class IndexOfIgnorable26Example
{
- public static void Main()
+ public static void Run()
{
string s1 = "ani\u00ADmal";
string s2 = "animal";
-
+
Console.WriteLine("Culture-sensitive comparison:");
// Use culture-sensitive comparison to find the soft hyphen.
Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.CurrentCulture));
Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.CurrentCulture));
-
+
// Use culture-sensitive comparison to find the soft hyphen followed by "n".
Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.CurrentCulture));
Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.CurrentCulture));
-
+
// Use culture-sensitive comparison to find the soft hyphen followed by "m".
Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.CurrentCulture));
-
+
Console.WriteLine("Ordinal comparison:");
// Use ordinal comparison to find the soft hyphen.
Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.Ordinal));
Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.Ordinal));
-
+
// Use ordinal comparison to find the soft hyphen followed by "n".
Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.Ordinal));
Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.Ordinal));
-
+
// Use ordinal comparison to find the soft hyphen followed by "m".
Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.Ordinal));
Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.Ordinal));
diff --git a/snippets/csharp/System/String/IndexOf/indexof_c.cs b/snippets/csharp/System/String/IndexOf/indexof_c.cs
index 2b7c273d005..9151244d7a7 100644
--- a/snippets/csharp/System/String/IndexOf/indexof_c.cs
+++ b/snippets/csharp/System/String/IndexOf/indexof_c.cs
@@ -1,31 +1,29 @@
using System;
-class Example
+class IndexOfCharExample
{
- static void Main()
+ public static void Run()
{
//
// Create a Unicode string with 5 Greek Alpha characters.
- String szGreekAlpha = new String('\u0391',5);
+ string szGreekAlpha = new('\u0391', 5);
// Create a Unicode string with 3 Greek Omega characters.
- String szGreekOmega = "\u03A9\u03A9\u03A9";
+ string szGreekOmega = "\u03A9\u03A9\u03A9";
- String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha,
+ string szGreekLetters = string.Concat(szGreekOmega, szGreekAlpha,
szGreekOmega.Clone());
// Display the entire string.
- Console.WriteLine("The string: {0}", szGreekLetters);
+ Console.WriteLine($"The string: {szGreekLetters}");
// The first index of Alpha.
int ialpha = szGreekLetters.IndexOf('\u0391');
// The first index of Omega.
int iomega = szGreekLetters.IndexOf('\u03A9');
- Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}",
- ialpha);
- Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}",
- iomega);
+ Console.WriteLine($"First occurrence of the Greek letter Alpha: Index {ialpha}");
+ Console.WriteLine($"First occurrence of the Greek letter Omega: Index {iomega}");
// The example displays the following output:
// The string: ΩΩΩΑΑΑΑΑΩΩΩ
diff --git a/snippets/csharp/System/String/IndexOf/indexofcii.cs b/snippets/csharp/System/String/IndexOf/indexofcii.cs
index ae361791095..3d254bb5853 100644
--- a/snippets/csharp/System/String/IndexOf/indexofcii.cs
+++ b/snippets/csharp/System/String/IndexOf/indexofcii.cs
@@ -2,60 +2,58 @@
// Example for the String.IndexOf( char, int, int ) method.
using System;
-class IndexOfCII
+class IndexOfCII
{
- public static void Main()
+ public static void Run()
{
- string br1 =
+ string br1 =
"0----+----1----+----2----+----3----+----" +
"4----+----5----+----6----+----7";
- string br2 =
+ string br2 =
"0123456789012345678901234567890123456789" +
"0123456789012345678901234567890";
- string str =
+ string str =
"ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " +
"ABCDEFGHI abcdefghi ABCDEFGHI";
- Console.WriteLine(
+ Console.WriteLine(
"This example of String.IndexOf( char, int, int )\n" +
- "generates the following output." );
- Console.WriteLine(
- "{0}{1}{0}{2}{0}{3}{0}",
- Environment.NewLine, br1, br2, str );
+ "generates the following output.");
+ Console.WriteLine(
+ "{0}{1}{0}{2}{0}{3}{0}",
+ Environment.NewLine, br1, br2, str);
- FindAllChar( 'A', str );
- FindAllChar( 'a', str );
- FindAllChar( 'I', str );
- FindAllChar( 'i', str );
- FindAllChar( '@', str );
- FindAllChar( ' ', str );
+ FindAllChar('A', str);
+ FindAllChar('a', str);
+ FindAllChar('I', str);
+ FindAllChar('i', str);
+ FindAllChar('@', str);
+ FindAllChar(' ', str);
}
- static void FindAllChar( Char target, String searched )
+ static void FindAllChar(char target, string searched)
{
- Console.Write(
- "The character '{0}' occurs at position(s): ",
- target );
+ Console.Write($"The character '{target}' occurs at position(s): ");
- int startIndex = -1;
- int hitCount = 0;
+ int startIndex = -1;
+ int hitCount = 0;
// Search for all occurrences of the target.
- while( true )
+ while (true)
{
- startIndex = searched.IndexOf(
- target, startIndex + 1,
- searched.Length - startIndex - 1 );
+ startIndex = searched.IndexOf(
+ target, startIndex + 1,
+ searched.Length - startIndex - 1);
// Exit the loop if the target is not found.
- if( startIndex < 0 )
+ if (startIndex < 0)
break;
- Console.Write( "{0}, ", startIndex );
+ Console.Write($"{startIndex}, ");
hitCount++;
}
- Console.WriteLine( "occurrences: {0}", hitCount );
+ Console.WriteLine($"occurrences: {hitCount}");
}
}
diff --git a/snippets/csharp/System/String/IndexOf/iocmp.cs b/snippets/csharp/System/String/IndexOf/iocmp.cs
index 27b599505ff..cd332b3dcb0 100644
--- a/snippets/csharp/System/String/IndexOf/iocmp.cs
+++ b/snippets/csharp/System/String/IndexOf/iocmp.cs
@@ -1,90 +1,87 @@
//
-// This code example demonstrates the
+// This code example demonstrates the
// System.String.IndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
-using System.Globalization;
-class Sample
+
+class IndexOfComparisonSample
{
- public static void Main()
+ public static void Run()
{
- string intro = "Find the first occurrence of a character using different " +
- "values of StringComparison.";
- string resultFmt = "Comparison: {0,-28} Location: {1,3}";
-
-// Define a string to search for.
-// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
- string CapitalAWithRing = "\u00c5";
-
-// Define a string to search.
-// The result of combining the characters LATIN SMALL LETTER A and COMBINING
-// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
-// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
- string cat = "A Cheshire c" + "\u0061\u030a" + "t";
-
- int loc = 0;
- StringComparison[] scValues = {
+ string intro = "Find the first occurrence of a character using different " +
+ "values of StringComparison.";
+ string resultFmt = "Comparison: {0,-28} Location: {1,3}";
+
+ // Define a string to search for.
+ // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
+ string CapitalAWithRing = "\u00c5";
+
+ // Define a string to search.
+ // The result of combining the characters LATIN SMALL LETTER A and COMBINING
+ // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
+ // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
+ string cat = "A Cheshire c" + "\u0061\u030a" + "t";
+
+ int loc = 0;
+ StringComparison[] scValues = [
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
- StringComparison.OrdinalIgnoreCase };
-
-// Clear the screen and display an introduction.
- Console.Clear();
- Console.WriteLine(intro);
-
-// Display the current culture because culture affects the result. For example,
-// try this code example with the "sv-SE" (Swedish-Sweden) culture.
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
- Console.WriteLine("The current culture is \"{0}\" - {1}.",
- Thread.CurrentThread.CurrentCulture.Name,
- Thread.CurrentThread.CurrentCulture.DisplayName);
-
-// Display the string to search for and the string to search.
- Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
- CapitalAWithRing, cat);
- Console.WriteLine();
-
-// Note that in each of the following searches, we look for
-// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
-// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
-// the string was not found.
-// Search using different values of StringComparison. Specify the start
-// index and count.
-
- Console.WriteLine("Part 1: Start index and count are specified.");
- foreach (StringComparison sc in scValues)
+ StringComparison.OrdinalIgnoreCase ];
+
+ // Clear the screen and display an introduction.
+ Console.Clear();
+ Console.WriteLine(intro);
+
+ // Display the current culture because culture affects the result. For example,
+ // try this code example with the "sv-SE" (Swedish-Sweden) culture.
+
+ Thread.CurrentThread.CurrentCulture = new("en-US");
+ Console.WriteLine($"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}.");
+
+ // Display the string to search for and the string to search.
+ Console.WriteLine($"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"");
+ Console.WriteLine();
+
+ // Note that in each of the following searches, we look for
+ // LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
+ // LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
+ // the string was not found.
+ // Search using different values of StringComparison. Specify the start
+ // index and count.
+
+ Console.WriteLine("Part 1: Start index and count are specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
-// Search using different values of StringComparison. Specify the
-// start index.
- Console.WriteLine("\nPart 2: Start index is specified.");
- foreach (StringComparison sc in scValues)
+ // Search using different values of StringComparison. Specify the
+ // start index.
+ Console.WriteLine("\nPart 2: Start index is specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.IndexOf(CapitalAWithRing, 0, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.IndexOf(CapitalAWithRing, 0, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
-// Search using different values of StringComparison.
- Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
- foreach (StringComparison sc in scValues)
+ // Search using different values of StringComparison.
+ Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.IndexOf(CapitalAWithRing, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.IndexOf(CapitalAWithRing, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
-Note: This code example was executed on a console whose user interface
+Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
@@ -118,4 +115,4 @@ public static void Main()
Comparison: OrdinalIgnoreCase Location: -1
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/IndexOf/ixof1.cs b/snippets/csharp/System/String/IndexOf/ixof1.cs
index 9433fe653c9..5a2a7decd3e 100644
--- a/snippets/csharp/System/String/IndexOf/ixof1.cs
+++ b/snippets/csharp/System/String/IndexOf/ixof1.cs
@@ -1,9 +1,9 @@
-// Sample for String.IndexOf(Char, Int32)
+// Sample for String.IndexOf(Char, Int32)
using System;
-class Sample
+class IndexOfCharStartSample
{
- public static void Main()
+ public static void Run()
{
//
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
@@ -13,18 +13,18 @@ public static void Main()
int at;
Console.WriteLine();
- Console.WriteLine("All occurrences of 't' from position 0 to {0}.", str.Length-1);
+ Console.WriteLine($"All occurrences of 't' from position 0 to {str.Length - 1}.");
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
at = 0;
start = 0;
- while((start < str.Length) && (at > -1))
+ while ((start < str.Length) && (at > -1))
{
at = str.IndexOf('t', start);
if (at == -1) break;
- Console.Write("{0} ", at);
- start = at+1;
+ Console.Write($"{at} ");
+ start = at + 1;
}
Console.WriteLine();
diff --git a/snippets/csharp/System/String/IndexOf/ixof8.cs b/snippets/csharp/System/String/IndexOf/ixof8.cs
index cbc10380838..b8ac12b99b8 100644
--- a/snippets/csharp/System/String/IndexOf/ixof8.cs
+++ b/snippets/csharp/System/String/IndexOf/ixof8.cs
@@ -1,9 +1,9 @@
-// Sample for String.IndexOf(String, Int32, Int32)
+// Sample for String.IndexOf(String, Int32, Int32)
using System;
-class Sample
+class IndexOfStringRangeSample
{
- public static void Main()
+ public static void Run()
{
//
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
@@ -15,22 +15,22 @@ public static void Main()
int count;
end = str.Length;
- start = end/2;
+ start = end / 2;
Console.WriteLine();
- Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end-1);
+ Console.WriteLine($"All occurrences of 'he' from position {start} to {end - 1}.");
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
count = 0;
at = 0;
- while((start <= end) && (at > -1))
+ while ((start <= end) && (at > -1))
{
// start+count must be a position within -str-.
count = end - start;
at = str.IndexOf("he", start, count);
if (at == -1) break;
- Console.Write("{0} ", at);
- start = at+1;
+ Console.Write($"{at} ");
+ start = at + 1;
}
Console.WriteLine();
diff --git a/snippets/csharp/System/String/IndexOf/simple1.cs b/snippets/csharp/System/String/IndexOf/simple1.cs
index f95f43a3db8..e6b7f7695b6 100644
--- a/snippets/csharp/System/String/IndexOf/simple1.cs
+++ b/snippets/csharp/System/String/IndexOf/simple1.cs
@@ -1,15 +1,14 @@
using System;
-public class Example
+public class IndexOfSimpleExample
{
- public static void Main()
+ public static void Run()
{
//
- String str = "animal";
- String toFind = "n";
+ string str = "animal";
+ string toFind = "n";
int index = str.IndexOf("n");
- Console.WriteLine("Found '{0}' in '{1}' at position {2}",
- toFind, str, index);
+ Console.WriteLine($"Found '{toFind}' in '{str}' at position {index}");
// The example displays the following output:
// Found 'n' in 'animal' at position 1
diff --git a/snippets/csharp/System/String/IndexOf/stringindexof4.cs b/snippets/csharp/System/String/IndexOf/stringindexof4.cs
index 041de8858d8..8bac7e8766f 100644
--- a/snippets/csharp/System/String/IndexOf/stringindexof4.cs
+++ b/snippets/csharp/System/String/IndexOf/stringindexof4.cs
@@ -1,8 +1,10 @@
//
using System;
-public class IndexOfTest {
- public static void Main() {
+public class IndexOfTest
+{
+ public static void Run()
+ {
string strSource = "This is the string which we will perform the search on";
@@ -12,18 +14,22 @@ public static void Main() {
int found = 0;
int totFinds = 0;
- do {
+ do
+ {
Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> ");
strTarget = Console.ReadLine();
- if (strTarget != "") {
+ if (strTarget != "")
+ {
- for (int i = 0; i < strSource.Length; i++) {
+ for (int i = 0; i < strSource.Length; i++)
+ {
found = strSource.IndexOf(strTarget, i);
- if (found >= 0) {
+ if (found >= 0)
+ {
totFinds++;
i = found;
}
@@ -42,7 +48,7 @@ public static void Main() {
Environment.NewLine, strTarget, totFinds);
totFinds = 0;
- } while ( true );
+ } while (true);
}
}
//
diff --git a/snippets/csharp/System/String/IndexOf/stringinsert.cs b/snippets/csharp/System/String/IndexOf/stringinsert.cs
index 9fb39e92607..1b99e5b4c99 100644
--- a/snippets/csharp/System/String/IndexOf/stringinsert.cs
+++ b/snippets/csharp/System/String/IndexOf/stringinsert.cs
@@ -1,14 +1,14 @@
//
using System;
-public class Example {
- public static void Main()
+public class IndexOfInsertExample
+{
+ public static void Run()
{
string animal1 = "fox";
string animal2 = "dog";
- string strTarget = String.Format("The {0} jumps over the {1}.",
- animal1, animal2);
+ string strTarget = $"The {animal1} jumps over the {animal2}.";
Console.WriteLine("The original string is:{0}{1}{0}",
Environment.NewLine, strTarget);
diff --git a/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs b/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs
index 7e46888284c..1c167ef5e5c 100644
--- a/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs
+++ b/snippets/csharp/System/String/IndexOfAny/IndexOfAny1.cs
@@ -2,22 +2,22 @@
public class Example1
{
- public static void Run()
- {
- //
- char[] chars = { 'a', 'e', 'i', 'o', 'u', 'y',
- 'A', 'E', 'I', 'O', 'U', 'Y' };
- String s = "The long and winding road...";
- Console.WriteLine($"""
+ public static void Run()
+ {
+ //
+ char[] chars = [ 'a', 'e', 'i', 'o', 'u', 'y',
+ 'A', 'E', 'I', 'O', 'U', 'Y' ];
+ string s = "The long and winding road...";
+ Console.WriteLine($"""
The first vowel in
'{s}'
is found at index {s.IndexOfAny(chars)}
""");
- // The example displays the following output:
- // The first vowel in
- // 'The long and winding road...'
- // is found at index 2
- //
- }
+ // The example displays the following output:
+ // The first vowel in
+ // 'The long and winding road...'
+ // is found at index 2
+ //
+ }
}
diff --git a/snippets/csharp/System/String/IndexOfAny/Program.cs b/snippets/csharp/System/String/IndexOfAny/Program.cs
index 510edb4cb58..c84db44d8fb 100644
--- a/snippets/csharp/System/String/IndexOfAny/Program.cs
+++ b/snippets/csharp/System/String/IndexOfAny/Program.cs
@@ -1,8 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+
+
+
+
+
namespace Project
{
diff --git a/snippets/csharp/System/String/Insert/Insert1.cs b/snippets/csharp/System/String/Insert/Insert1.cs
index 033b12127ad..d888d8bca49 100644
--- a/snippets/csharp/System/String/Insert/Insert1.cs
+++ b/snippets/csharp/System/String/Insert/Insert1.cs
@@ -3,13 +3,13 @@
public class Example
{
- public static void Main()
- {
- String original = "aaabbb";
- Console.WriteLine("The original string: '{0}'", original);
- String modified = original.Insert(3, " ");
- Console.WriteLine("The modified string: '{0}'", modified);
- }
+ public static void Main()
+ {
+ string original = "aaabbb";
+ Console.WriteLine($"The original string: '{original}'");
+ string modified = original.Insert(3, " ");
+ Console.WriteLine($"The modified string: '{modified}'");
+ }
}
// The example displays the following output:
// The original string: 'aaabbb'
diff --git a/snippets/csharp/System/String/Intern/Intern1.cs b/snippets/csharp/System/String/Intern/Intern1.cs
index fa3a57ae33a..685a2fa10e9 100644
--- a/snippets/csharp/System/String/Intern/Intern1.cs
+++ b/snippets/csharp/System/String/Intern/Intern1.cs
@@ -4,14 +4,14 @@
[assembly: CLSCompliant(true)]
public class Class1
{
- public static void Main()
- {
- //
- string s1 = "MyTest";
- string s2 = new StringBuilder().Append("My").Append("Test").ToString();
- string s3 = String.Intern(s2);
- Console.WriteLine((Object)s2==(Object)s1); // Different references.
- Console.WriteLine((Object)s3==(Object)s1); // The same reference.
- //
- }
+ public static void Main()
+ {
+ //
+ string s1 = "MyTest";
+ string s2 = new StringBuilder().Append("My").Append("Test").ToString();
+ string s3 = string.Intern(s2);
+ Console.WriteLine((object)s2 == (object)s1); // Different references.
+ Console.WriteLine((object)s3 == (object)s1); // The same reference.
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Intern/string_intern.cs b/snippets/csharp/System/String/Intern/string_intern.cs
index 8f14ccb26f7..d177d745c93 100644
--- a/snippets/csharp/System/String/Intern/string_intern.cs
+++ b/snippets/csharp/System/String/Intern/string_intern.cs
@@ -12,13 +12,13 @@ public static void Main()
Console.WriteLine($"s1 == {s1}");
Console.WriteLine($"s2 == {s2}");
Console.WriteLine($"Are s1 and s2 equal in value? {s1 == s2}");
- Console.WriteLine($"Are s1 and s2 the same reference? {Object.ReferenceEquals(s1, s2)}");
+ Console.WriteLine($"Are s1 and s2 the same reference? {object.ReferenceEquals(s1, s2)}");
- string i1 = String.Intern(s1);
- string i2 = String.Intern(s2);
+ string i1 = string.Intern(s1);
+ string i2 = string.Intern(s2);
Console.WriteLine($"After interning:");
Console.WriteLine($" Are i1 and i2 equal in value? {i1 == i2}");
- Console.WriteLine($" Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}");
+ Console.WriteLine($" Are i1 and i2 the same reference? {object.ReferenceEquals(i1, i2)}");
}
}
/*
diff --git a/snippets/csharp/System/String/IsInterned/isin.cs b/snippets/csharp/System/String/IsInterned/isin.cs
index e7dc8a16d93..7077f417841 100644
--- a/snippets/csharp/System/String/IsInterned/isin.cs
+++ b/snippets/csharp/System/String/IsInterned/isin.cs
@@ -12,17 +12,17 @@ public static void Main()
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
// Neither string is in the intern pool yet.
- Console.WriteLine($"Is s1 interned? {String.IsInterned(s1) != null}");
- Console.WriteLine($"Is s2 interned? {String.IsInterned(s2) != null}");
+ Console.WriteLine($"Is s1 interned? {string.IsInterned(s1) != null}");
+ Console.WriteLine($"Is s2 interned? {string.IsInterned(s2) != null}");
// Intern s1 explicitly.
- string i1 = String.Intern(s1);
+ string i1 = string.Intern(s1);
// Now s2 can be found in the intern pool.
- string i2 = String.IsInterned(s2);
+ string i2 = string.IsInterned(s2);
Console.WriteLine($"Is s2 interned after interning s1? {i2 != null}");
- Console.WriteLine($"Are i1 and i2 the same reference? {Object.ReferenceEquals(i1, i2)}");
+ Console.WriteLine($"Are i1 and i2 the same reference? {object.ReferenceEquals(i1, i2)}");
}
}
@@ -33,4 +33,4 @@ public static void Main()
// Is s2 interned after interning s1? True
// Are i1 and i2 the same reference? True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/IsInterned/isinternedex1.cs b/snippets/csharp/System/String/IsInterned/isinternedex1.cs
index 71b73869dde..fcc54c72ac7 100644
--- a/snippets/csharp/System/String/IsInterned/isinternedex1.cs
+++ b/snippets/csharp/System/String/IsInterned/isinternedex1.cs
@@ -3,29 +3,28 @@
public class Example
{
- public static void Main()
- {
- string str1 = "a";
- string str2 = str1 + "b";
- string str3 = str2 + "c";
- string[] strings = { "value", "part1" + "_" + "part2", str3,
- String.Empty, null };
- foreach (var value in strings) {
- if (value == null) continue;
-
- bool interned = String.IsInterned(value) != null;
- if (interned)
- Console.WriteLine("'{0}' is in the string intern pool.",
- value);
- else
- Console.WriteLine("'{0}' is not in the string intern pool.",
- value);
- }
- }
+ public static void Main()
+ {
+ string str1 = "a";
+ string str2 = str1 + "b";
+ string str3 = str2 + "c";
+ string[] strings = [ "value", "part1" + "_" + "part2", str3,
+ string.Empty, null ];
+ foreach (string value in strings)
+ {
+ if (value == null) continue;
+
+ bool interned = string.IsInterned(value) != null;
+ if (interned)
+ Console.WriteLine($"'{value}' is in the string intern pool.");
+ else
+ Console.WriteLine($"'{value}' is not in the string intern pool.");
+ }
+ }
}
// The example displays the following output:
// 'value' is in the string intern pool.
// 'part1_part2' is in the string intern pool.
// 'abc' is not in the string intern pool.
// '' is in the string intern pool.
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/IsNormalized/norm.cs b/snippets/csharp/System/String/IsNormalized/norm.cs
index a675445da1b..b8a80b7e51b 100644
--- a/snippets/csharp/System/String/IsNormalized/norm.cs
+++ b/snippets/csharp/System/String/IsNormalized/norm.cs
@@ -6,79 +6,75 @@ class Example
{
public static void Main()
{
- // Character c; combining characters acute and cedilla; character 3/4
- string s1 = new String( new char[] {'\u0063', '\u0301', '\u0327', '\u00BE'});
- string s2 = null;
- string divider = new String('-', 80);
- divider = String.Concat(Environment.NewLine, divider, Environment.NewLine);
-
- Show("s1", s1);
- Console.WriteLine();
- Console.WriteLine("U+0063 = LATIN SMALL LETTER C");
- Console.WriteLine("U+0301 = COMBINING ACUTE ACCENT");
- Console.WriteLine("U+0327 = COMBINING CEDILLA");
- Console.WriteLine("U+00BE = VULGAR FRACTION THREE QUARTERS");
- Console.WriteLine(divider);
-
- Console.WriteLine("A1) Is s1 normalized to the default form (Form C)?: {0}",
- s1.IsNormalized());
- Console.WriteLine("A2) Is s1 normalized to Form C?: {0}",
- s1.IsNormalized(NormalizationForm.FormC));
- Console.WriteLine("A3) Is s1 normalized to Form D?: {0}",
- s1.IsNormalized(NormalizationForm.FormD));
- Console.WriteLine("A4) Is s1 normalized to Form KC?: {0}",
- s1.IsNormalized(NormalizationForm.FormKC));
- Console.WriteLine("A5) Is s1 normalized to Form KD?: {0}",
- s1.IsNormalized(NormalizationForm.FormKD));
-
- Console.WriteLine(divider);
-
- Console.WriteLine("Set string s2 to each normalized form of string s1.");
- Console.WriteLine();
- Console.WriteLine("U+1E09 = LATIN SMALL LETTER C WITH CEDILLA AND ACUTE");
- Console.WriteLine("U+0033 = DIGIT THREE");
- Console.WriteLine("U+2044 = FRACTION SLASH");
- Console.WriteLine("U+0034 = DIGIT FOUR");
- Console.WriteLine(divider);
-
- s2 = s1.Normalize();
- Console.Write("B1) Is s2 normalized to the default form (Form C)?: ");
- Console.WriteLine(s2.IsNormalized());
- Show("s2", s2);
- Console.WriteLine();
-
- s2 = s1.Normalize(NormalizationForm.FormC);
- Console.Write("B2) Is s2 normalized to Form C?: ");
- Console.WriteLine(s2.IsNormalized(NormalizationForm.FormC));
- Show("s2", s2);
- Console.WriteLine();
-
- s2 = s1.Normalize(NormalizationForm.FormD);
- Console.Write("B3) Is s2 normalized to Form D?: ");
- Console.WriteLine(s2.IsNormalized(NormalizationForm.FormD));
- Show("s2", s2);
- Console.WriteLine();
-
- s2 = s1.Normalize(NormalizationForm.FormKC);
- Console.Write("B4) Is s2 normalized to Form KC?: ");
- Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKC));
- Show("s2", s2);
- Console.WriteLine();
-
- s2 = s1.Normalize(NormalizationForm.FormKD);
- Console.Write("B5) Is s2 normalized to Form KD?: ");
- Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKD));
- Show("s2", s2);
- Console.WriteLine();
+ // Character c; combining characters acute and cedilla; character 3/4
+ string s1 = new(['\u0063', '\u0301', '\u0327', '\u00BE']);
+ string s2 = null;
+ string divider = new('-', 80);
+ divider = string.Concat(Environment.NewLine, divider, Environment.NewLine);
+
+ Show("s1", s1);
+ Console.WriteLine();
+ Console.WriteLine("U+0063 = LATIN SMALL LETTER C");
+ Console.WriteLine("U+0301 = COMBINING ACUTE ACCENT");
+ Console.WriteLine("U+0327 = COMBINING CEDILLA");
+ Console.WriteLine("U+00BE = VULGAR FRACTION THREE QUARTERS");
+ Console.WriteLine(divider);
+
+ Console.WriteLine($"A1) Is s1 normalized to the default form (Form C)?: {s1.IsNormalized()}");
+ Console.WriteLine($"A2) Is s1 normalized to Form C?: {s1.IsNormalized(NormalizationForm.FormC)}");
+ Console.WriteLine($"A3) Is s1 normalized to Form D?: {s1.IsNormalized(NormalizationForm.FormD)}");
+ Console.WriteLine($"A4) Is s1 normalized to Form KC?: {s1.IsNormalized(NormalizationForm.FormKC)}");
+ Console.WriteLine($"A5) Is s1 normalized to Form KD?: {s1.IsNormalized(NormalizationForm.FormKD)}");
+
+ Console.WriteLine(divider);
+
+ Console.WriteLine("Set string s2 to each normalized form of string s1.");
+ Console.WriteLine();
+ Console.WriteLine("U+1E09 = LATIN SMALL LETTER C WITH CEDILLA AND ACUTE");
+ Console.WriteLine("U+0033 = DIGIT THREE");
+ Console.WriteLine("U+2044 = FRACTION SLASH");
+ Console.WriteLine("U+0034 = DIGIT FOUR");
+ Console.WriteLine(divider);
+
+ s2 = s1.Normalize();
+ Console.Write("B1) Is s2 normalized to the default form (Form C)?: ");
+ Console.WriteLine(s2.IsNormalized());
+ Show("s2", s2);
+ Console.WriteLine();
+
+ s2 = s1.Normalize(NormalizationForm.FormC);
+ Console.Write("B2) Is s2 normalized to Form C?: ");
+ Console.WriteLine(s2.IsNormalized(NormalizationForm.FormC));
+ Show("s2", s2);
+ Console.WriteLine();
+
+ s2 = s1.Normalize(NormalizationForm.FormD);
+ Console.Write("B3) Is s2 normalized to Form D?: ");
+ Console.WriteLine(s2.IsNormalized(NormalizationForm.FormD));
+ Show("s2", s2);
+ Console.WriteLine();
+
+ s2 = s1.Normalize(NormalizationForm.FormKC);
+ Console.Write("B4) Is s2 normalized to Form KC?: ");
+ Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKC));
+ Show("s2", s2);
+ Console.WriteLine();
+
+ s2 = s1.Normalize(NormalizationForm.FormKD);
+ Console.Write("B5) Is s2 normalized to Form KD?: ");
+ Console.WriteLine(s2.IsNormalized(NormalizationForm.FormKD));
+ Show("s2", s2);
+ Console.WriteLine();
}
private static void Show(string title, string s)
{
- Console.Write("Characters in string {0} = ", title);
- foreach(short x in s) {
- Console.Write("{0:X4} ", x);
- }
- Console.WriteLine();
+ Console.Write($"Characters in string {title} = ");
+ foreach (short x in s)
+ {
+ Console.Write($"{x:X4} ");
+ }
+ Console.WriteLine();
}
}
/*
@@ -126,4 +122,4 @@ Set string s2 to each normalized form of string s1.
Characters in string s2 = 0063 0327 0301 0033 2044 0034
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs b/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs
index c9da93895ba..76c0dafd51d 100644
--- a/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs
+++ b/snippets/csharp/System/String/IsNullOrEmpty/NullString1.cs
@@ -1,19 +1,19 @@
-using System;
+using System;
public class Example
{
public static void Main()
{
//
- String s = null;
-
+ string s = null;
+
Console.WriteLine($"The value of the string is '{s}'");
- try
+ try
{
Console.WriteLine($"String length is {s.Length}");
}
- catch (NullReferenceException e)
+ catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
@@ -30,11 +30,11 @@ public class Empty
public void Test()
{
//
- String s = "";
+ string s = "";
Console.WriteLine($"The length of '{s}' is {s.Length}.");
// The example displays the following output:
- // The length of '' is 0.
+ // The length of '' is 0.
//
}
}
diff --git a/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs b/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs
index 004791df431..68c224af75a 100644
--- a/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs
+++ b/snippets/csharp/System/String/IsNullOrEmpty/inoe.cs
@@ -4,27 +4,27 @@ class Sample
{
public static void Main()
{
- //
- string s1 = "abcd";
- string s2 = "";
- string s3 = null;
+ //
+ string s1 = "abcd";
+ string s2 = "";
+ string s3 = null;
- Console.WriteLine("String s1 {0}.", Test(s1));
- Console.WriteLine("String s2 {0}.", Test(s2));
- Console.WriteLine("String s3 {0}.", Test(s3));
+ Console.WriteLine($"String s1 {Test(s1)}.");
+ Console.WriteLine($"String s2 {Test(s2)}.");
+ Console.WriteLine($"String s3 {Test(s3)}.");
- String Test(string s)
- {
- if (String.IsNullOrEmpty(s))
- return "is null or empty";
- else
- return String.Format("(\"{0}\") is neither null nor empty", s);
- }
+ string Test(string s)
+ {
+ if (string.IsNullOrEmpty(s))
+ return "is null or empty";
+ else
+ return $"(\"{s}\") is neither null nor empty";
+ }
- // The example displays the following output:
- // String s1 ("abcd") is neither null nor empty.
- // String s2 is null or empty.
- // String s3 is null or empty.
- //
+ // The example displays the following output:
+ // String s1 ("abcd") is neither null nor empty.
+ // String s2 is null or empty.
+ // String s3 is null or empty.
+ //
}
}
diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs
new file mode 100644
index 00000000000..a6cb7b07baa
--- /dev/null
+++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/Program.cs
@@ -0,0 +1,2 @@
+IsNullOrWhiteSpaceEquivalentExample.Run();
+IsNullOrWhiteSpaceExample.Run();
diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj b/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs
index 0cd03284113..80a4ace4701 100644
--- a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs
+++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace.cs
@@ -1,17 +1,14 @@
using System;
-public class Example
+public class IsNullOrWhiteSpaceEquivalentExample
{
- public static void Main()
- {
- Console.WriteLine(ShowCode());
- }
+ public static void Run() => Console.WriteLine(ShowCode());
- private static bool ShowCode()
- {
- string value = null;
- //
- return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
- //
- }
+ private static bool ShowCode()
+ {
+ string value = null;
+ //
+ return string.IsNullOrEmpty(value) || value.Trim().Length == 0;
+ //
+ }
}
diff --git a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs
index 48a2dde44c3..7763fdcb924 100644
--- a/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs
+++ b/snippets/csharp/System/String/IsNullOrWhiteSpace/isnullorwhitespace1.cs
@@ -1,16 +1,16 @@
//
using System;
-public class Example
+public class IsNullOrWhiteSpaceExample
{
- public static void Main()
- {
- string[] values = { null, String.Empty, "ABCDE",
- new String(' ', 20), " \t ",
- new String('\u2000', 10) };
- foreach (string value in values)
- Console.WriteLine(String.IsNullOrWhiteSpace(value));
- }
+ public static void Run()
+ {
+ string[] values = [ null, string.Empty, "ABCDE",
+ new string(' ', 20), " \t ",
+ new string('\u2000', 10) ];
+ foreach (string value in values)
+ Console.WriteLine(string.IsNullOrWhiteSpace(value));
+ }
}
// The example displays the following output:
// True
@@ -19,4 +19,4 @@ public static void Main()
// True
// True
// True
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Join/Program.cs b/snippets/csharp/System/String/Join/Program.cs
new file mode 100644
index 00000000000..44d79eafae7
--- /dev/null
+++ b/snippets/csharp/System/String/Join/Program.cs
@@ -0,0 +1,7 @@
+JoinArrayExample.Run();
+Sample.Run();
+JoinListExample.Run();
+JoinAlphabetExample.Run();
+JoinAnimalsExample.Run();
+JoinEnumerableExample.Run();
+JoinTest.Run();
diff --git a/snippets/csharp/System/String/Join/Project.csproj b/snippets/csharp/System/String/Join/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/Join/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/Join/join1.cs b/snippets/csharp/System/String/Join/join1.cs
index 618d055e2bb..12549ff897e 100644
--- a/snippets/csharp/System/String/Join/join1.cs
+++ b/snippets/csharp/System/String/Join/join1.cs
@@ -2,39 +2,39 @@
using System;
using System.Collections.Generic;
-public class Example
+public class JoinArrayExample
{
- public static void Main()
- {
- int maxPrime = 100;
- int[] primes = GetPrimes(maxPrime);
- Console.WriteLine("Primes less than {0}:", maxPrime);
- Console.WriteLine(" {0}", String.Join(" ", primes));
- }
+ public static void Run()
+ {
+ int maxPrime = 100;
+ int[] primes = GetPrimes(maxPrime);
+ Console.WriteLine($"Primes less than {maxPrime}:");
+ Console.WriteLine($" {string.Join(" ", primes)}");
+ }
- private static int[] GetPrimes(int maxPrime)
- {
- Array values = Array.CreateInstance(typeof(int),
- new int[] { maxPrime - 1}, new int[] { 2 });
- // Use Sieve of Eratosthenes to determine prime numbers.
- for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
- {
-
- if ((int) values.GetValue(ctr) == 1) continue;
-
- for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
- if (ctr * multiplier <= maxPrime)
- values.SetValue(1, ctr * multiplier);
- }
-
- List primes = new List();
- for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
- if ((int) values.GetValue(ctr) == 0)
- primes.Add(ctr);
- return primes.ToArray();
- }
+ private static int[] GetPrimes(int maxPrime)
+ {
+ Array values = Array.CreateInstance(typeof(int),
+ [maxPrime - 1], [2]);
+ // Use Sieve of Eratosthenes to determine prime numbers.
+ for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
+ {
+
+ if ((int)values.GetValue(ctr) == 1) continue;
+
+ for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
+ if (ctr * multiplier <= maxPrime)
+ values.SetValue(1, ctr * multiplier);
+ }
+
+ List primes = new();
+ for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
+ if ((int)values.GetValue(ctr) == 0)
+ primes.Add(ctr);
+ return [.. primes];
+ }
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Join/join2.cs b/snippets/csharp/System/String/Join/join2.cs
index 5b2912b9190..92dd8ce00a4 100644
--- a/snippets/csharp/System/String/Join/join2.cs
+++ b/snippets/csharp/System/String/Join/join2.cs
@@ -3,17 +3,17 @@
class Sample
{
- public static void Main()
+ public static void Run()
{
//
- String[] val = {"apple", "orange", "grape", "pear"};
- String sep = ", ";
- String result;
+ string[] val = ["apple", "orange", "grape", "pear"];
+ string sep = ", ";
+ string result;
- Console.WriteLine("sep = '{0}'", sep);
- Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
- result = String.Join(sep, val, 1, 2);
- Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
+ Console.WriteLine($"sep = '{sep}'");
+ Console.WriteLine($"val[] = {{'{val[0]}' '{val[1]}' '{val[2]}' '{val[3]}'}}");
+ result = string.Join(sep, val, 1, 2);
+ Console.WriteLine($"String.Join(sep, val, 1, 2) = '{result}'");
// This example produces the following results:
// sep = ', '
diff --git a/snippets/csharp/System/String/Join/join3.cs b/snippets/csharp/System/String/Join/join3.cs
index b9fee22660b..5e9a2146b9f 100644
--- a/snippets/csharp/System/String/Join/join3.cs
+++ b/snippets/csharp/System/String/Join/join3.cs
@@ -2,39 +2,39 @@
using System;
using System.Collections.Generic;
-public class Example
+public class JoinListExample
{
- public static void Main()
- {
- int maxPrime = 100;
- List primes = GetPrimes(maxPrime);
- Console.WriteLine("Primes less than {0}:", maxPrime);
- Console.WriteLine(" {0}", String.Join(" ", primes));
- }
+ public static void Run()
+ {
+ int maxPrime = 100;
+ List primes = GetPrimes(maxPrime);
+ Console.WriteLine($"Primes less than {maxPrime}:");
+ Console.WriteLine($" {string.Join(" ", primes)}");
+ }
- private static List GetPrimes(int maxPrime)
- {
- Array values = Array.CreateInstance(typeof(int),
- new int[] { maxPrime - 1}, new int[] { 2 });
- // Use Sieve of Eratosthenes to determine prime numbers.
- for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
- {
-
- if ((int) values.GetValue(ctr) == 1) continue;
-
- for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
- if (ctr * multiplier <= maxPrime)
- values.SetValue(1, ctr * multiplier);
- }
-
- List primes = new List();
- for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
- if ((int) values.GetValue(ctr) == 0)
- primes.Add(ctr);
- return primes;
- }
+ private static List GetPrimes(int maxPrime)
+ {
+ Array values = Array.CreateInstance(typeof(int),
+ [maxPrime - 1], [2]);
+ // Use Sieve of Eratosthenes to determine prime numbers.
+ for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
+ {
+
+ if ((int)values.GetValue(ctr) == 1) continue;
+
+ for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
+ if (ctr * multiplier <= maxPrime)
+ values.SetValue(1, ctr * multiplier);
+ }
+
+ List primes = new();
+ for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
+ if ((int)values.GetValue(ctr) == 0)
+ primes.Add(ctr);
+ return primes;
+ }
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Join/join4.cs b/snippets/csharp/System/String/Join/join4.cs
index 1eaea09860d..2e9b986dd1b 100644
--- a/snippets/csharp/System/String/Join/join4.cs
+++ b/snippets/csharp/System/String/Join/join4.cs
@@ -3,24 +3,24 @@
using System.Collections.Generic;
using System.Linq;
-public class Example
+public class JoinAlphabetExample
{
- public static void Main()
- {
- string output = String.Join(" ", GetAlphabet(true).Where( letter =>
- letter.CompareTo("M") >= 0));
- Console.WriteLine(output);
- }
+ public static void Run()
+ {
+ string output = string.Join(" ", GetAlphabet(true).Where(letter =>
+ letter.CompareTo("M") >= 0));
+ Console.WriteLine(output);
+ }
- private static List GetAlphabet(bool upper)
- {
- List alphabet = new List();
- int charValue = upper ? 65 : 97;
- for (int ctr = 0; ctr <= 25; ctr++)
- alphabet.Add(((char)(charValue + ctr)).ToString());
- return alphabet;
- }
+ private static List GetAlphabet(bool upper)
+ {
+ List alphabet = new();
+ int charValue = upper ? 65 : 97;
+ for (int ctr = 0; ctr <= 25; ctr++)
+ alphabet.Add(((char)(charValue + ctr)).ToString());
+ return alphabet;
+ }
}
// The example displays the following output:
// M N O P Q R S T U V W X Y Z
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Join/join5.cs b/snippets/csharp/System/String/Join/join5.cs
index 240ee2c40f9..1b4995aca74 100644
--- a/snippets/csharp/System/String/Join/join5.cs
+++ b/snippets/csharp/System/String/Join/join5.cs
@@ -5,33 +5,32 @@
public class Animal
{
- public string Kind;
- public string Order;
-
- public Animal(string kind, string order)
- {
- this.Kind = kind;
- this.Order = order;
- }
-
- public override string ToString()
- {
- return this.Kind;
- }
+ public string Kind;
+ public string Order;
+
+ public Animal(string kind, string order)
+ {
+ this.Kind = kind;
+ this.Order = order;
+ }
+
+ public override string ToString() => this.Kind;
}
-public class Example
+public class JoinAnimalsExample
{
- public static void Main()
- {
- List animals = new List();
- animals.Add(new Animal("Squirrel", "Rodent"));
- animals.Add(new Animal("Gray Wolf", "Carnivora"));
- animals.Add(new Animal("Capybara", "Rodent"));
- string output = String.Join(" ", animals.Where( animal =>
- (animal.Order == "Rodent")));
- Console.WriteLine(output);
- }
+ public static void Run()
+ {
+ List animals = new()
+ {
+ new Animal("Squirrel", "Rodent"),
+ new Animal("Gray Wolf", "Carnivora"),
+ new Animal("Capybara", "Rodent")
+ };
+ string output = string.Join(" ", animals.Where(animal =>
+ (animal.Order == "Rodent")));
+ Console.WriteLine(output);
+ }
}
// The example displays the following output:
// Squirrel Capybara
diff --git a/snippets/csharp/System/String/Join/join6.cs b/snippets/csharp/System/String/Join/join6.cs
index 1e98285e8ba..6f8e34a338a 100644
--- a/snippets/csharp/System/String/Join/join6.cs
+++ b/snippets/csharp/System/String/Join/join6.cs
@@ -2,39 +2,39 @@
using System;
using System.Collections.Generic;
-public class Example
+public class JoinEnumerableExample
{
- public static void Main()
- {
- int maxPrime = 100;
- List primes = GetPrimes(maxPrime);
- Console.WriteLine("Primes less than {0}:", maxPrime);
- Console.WriteLine(" {0}", String.Join(" ", primes));
- }
+ public static void Run()
+ {
+ int maxPrime = 100;
+ List primes = GetPrimes(maxPrime);
+ Console.WriteLine($"Primes less than {maxPrime}:");
+ Console.WriteLine($" {string.Join(" ", primes)}");
+ }
- private static List GetPrimes(int maxPrime)
- {
- Array values = Array.CreateInstance(typeof(int),
- new int[] { maxPrime - 1}, new int[] { 2 });
- // Use Sieve of Eratosthenes to determine prime numbers.
- for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
- {
-
- if ((int) values.GetValue(ctr) == 1) continue;
-
- for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
- if (ctr * multiplier <= maxPrime)
- values.SetValue(1, ctr * multiplier);
- }
-
- List primes = new List();
- for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
- if ((int) values.GetValue(ctr) == 0)
- primes.Add(ctr);
- return primes;
- }
+ private static List GetPrimes(int maxPrime)
+ {
+ Array values = Array.CreateInstance(typeof(int),
+ [maxPrime - 1], [2]);
+ // Use Sieve of Eratosthenes to determine prime numbers.
+ for (int ctr = values.GetLowerBound(0); ctr <= (int)Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
+ {
+
+ if ((int)values.GetValue(ctr) == 1) continue;
+
+ for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
+ if (ctr * multiplier <= maxPrime)
+ values.SetValue(1, ctr * multiplier);
+ }
+
+ List primes = new();
+ for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
+ if ((int)values.GetValue(ctr) == 0)
+ primes.Add(ctr);
+ return primes;
+ }
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Join/stringjoin.cs b/snippets/csharp/System/String/Join/stringjoin.cs
index 1de6bfd4ba8..fc6dfb23fec 100644
--- a/snippets/csharp/System/String/Join/stringjoin.cs
+++ b/snippets/csharp/System/String/Join/stringjoin.cs
@@ -3,7 +3,7 @@
public class JoinTest
{
- public static void Main()
+ public static void Run()
{
Console.WriteLine(MakeLine(0, 5, ", "));
Console.WriteLine(MakeLine(1, 6, " "));
@@ -13,12 +13,12 @@ public static void Main()
private static string MakeLine(int initVal, int multVal, string sep)
{
- string [] sArr = new string [10];
+ string[] sArr = new string[10];
for (int i = initVal; i < initVal + 10; i++)
- sArr[i - initVal] = String.Format("{0,-3}", i * multVal);
+ sArr[i - initVal] = $"{i * multVal,-3}";
- return String.Join(sep, sArr);
+ return string.Join(sep, sArr);
}
}
// The example displays the following output:
@@ -26,4 +26,4 @@ private static string MakeLine(int initVal, int multVal, string sep)
// 6 12 18 24 30 36 42 48 54 60
// 81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162
// 28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs b/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs
index 99fb57f04c5..b4838a6ecb2 100644
--- a/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs
+++ b/snippets/csharp/System/String/LastIndexOf/LastIndexOf_Example.cs
@@ -4,49 +4,49 @@
public class TestLastIndexOf
{
- public static void Main()
- {
- string filename;
-
- filename = ExtractFilename(@"C:\temp\");
- Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename);
-
- filename = ExtractFilename(@"C:\temp\delegate.txt");
- Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename);
+ public static void Run()
+ {
+ string filename;
- filename = ExtractFilename("delegate.txt");
- Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename);
-
- filename = ExtractFilename(@"C:\temp\notafile.txt");
- Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "" : filename);
- }
+ filename = ExtractFilename(@"C:\temp\");
+ Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}");
- public static string ExtractFilename(string filepath)
- {
- // If path ends with a "\", it's a path only so return String.Empty.
- if (filepath.Trim().EndsWith(@"\"))
- return String.Empty;
-
- // Determine where last backslash is.
- int position = filepath.LastIndexOf('\\');
- // If there is no backslash, assume that this is a filename.
- if (position == -1)
- {
- // Determine whether file exists in the current directory.
- if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath))
- return filepath;
- else
- return String.Empty;
- }
- else
- {
- // Determine whether file exists using filepath.
- if (File.Exists(filepath))
- // Return filename without file path.
- return filepath.Substring(position + 1);
- else
- return String.Empty;
- }
- }
+ filename = ExtractFilename(@"C:\temp\delegate.txt");
+ Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}");
+
+ filename = ExtractFilename("delegate.txt");
+ Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}");
+
+ filename = ExtractFilename(@"C:\temp\notafile.txt");
+ Console.WriteLine($"{(string.IsNullOrEmpty(filename) ? "" : filename)}");
+ }
+
+ public static string ExtractFilename(string filepath)
+ {
+ // If path ends with a "\", it's a path only so return String.Empty.
+ if (filepath.Trim().EndsWith(@"\"))
+ return string.Empty;
+
+ // Determine where last backslash is.
+ int position = filepath.LastIndexOf('\\');
+ // If there is no backslash, assume that this is a filename.
+ if (position == -1)
+ {
+ // Determine whether file exists in the current directory.
+ if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath))
+ return filepath;
+ else
+ return string.Empty;
+ }
+ else
+ {
+ // Determine whether file exists using filepath.
+ if (File.Exists(filepath))
+ // Return filename without file path.
+ return filepath.Substring(position + 1);
+ else
+ return string.Empty;
+ }
+ }
}
//
diff --git a/snippets/csharp/System/String/LastIndexOf/Program.cs b/snippets/csharp/System/String/LastIndexOf/Program.cs
new file mode 100644
index 00000000000..4834bb32f7e
--- /dev/null
+++ b/snippets/csharp/System/String/LastIndexOf/Program.cs
@@ -0,0 +1,13 @@
+TestLastIndexOf.Run();
+LastIndexOfTagsExample.Run();
+LastIndexOfIgnorable21Example.Run();
+LastIndexOfIgnorable22Example.Run();
+LastIndexOfIgnorable23Example.Run();
+LastIndexOfIgnorable24Example.Run();
+LastIndexOfIgnorable25Example.Run();
+LastIndexOfIgnorable26Example.Run();
+LastIndexOfCharSample.Run();
+LastIndexOfCharRangeSample.Run();
+LastIndexOfStringSample.Run();
+LastIndexOfStringRangeSample.Run();
+LastIndexOfComparisonSample.Run();
diff --git a/snippets/csharp/System/String/LastIndexOf/Project.csproj b/snippets/csharp/System/String/LastIndexOf/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/LastIndexOf/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs
index 5414e083ae4..0961a734067 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof21.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable21Example
{
- public static void Main()
+ public static void Run()
{
//
string s1 = "ani\u00ADmal";
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs
index 702370a2c0c..8a3ea8868b0 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof22.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable22Example
{
- public static void Main()
+ public static void Run()
{
//
int position = 0;
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs
index 2a8c70c7bf5..b9b084d12fd 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof23.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable23Example
{
- public static void Main()
+ public static void Run()
{
//
int position = 0;
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs
index c16a2a6a53a..189cb7aa75e 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof24.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable24Example
{
- public static void Main()
+ public static void Run()
{
//
string searchString = "\u00ADm";
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs
index 5d5af49ef14..cb81ae29475 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof25.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable25Example
{
- public static void Main()
+ public static void Run()
{
//
string searchString = "\u00ADm";
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs
index a78ec97f8e7..b2d68f94004 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof26.cs
@@ -1,8 +1,8 @@
using System;
-public class Example
+public class LastIndexOfIgnorable26Example
{
- public static void Main()
+ public static void Run()
{
//
string s1 = "ani\u00ADmal";
diff --git a/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs b/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs
index 4a52a79b1dc..61f4299bc15 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastindexof_example2.cs
@@ -1,58 +1,58 @@
//
using System;
-public class Example
+public class LastIndexOfTagsExample
{
- public static void Main()
- {
- string[] strSource = { "This is bold text", "This is large Text
",
+ public static void Run()
+ {
+ string[] strSource = [ "This is bold text", "This is large Text
",
"This has multiple tags",
"This has embedded tags.",
- "This line ends with a greater than symbol and should not be modified>" };
+ "This line ends with a greater than symbol and should not be modified>" ];
- // Strip HTML start and end tags from each string if they are present.
- foreach (string s in strSource)
- {
- Console.WriteLine("Before: " + s);
- string item = s;
- // Use EndsWith to find a tag at the end of the line.
- if (item.Trim().EndsWith(">"))
- {
- // Locate the opening tag.
- int endTagStartPosition = item.LastIndexOf("");
- // Remove the identified section, if it is valid.
- if (endTagStartPosition >= 0 )
- item = item.Substring(0, endTagStartPosition);
-
- // Use StartsWith to find the opening tag.
- if (item.Trim().StartsWith("<"))
+ // Strip HTML start and end tags from each string if they are present.
+ foreach (string s in strSource)
+ {
+ Console.WriteLine("Before: " + s);
+ string item = s;
+ // Use EndsWith to find a tag at the end of the line.
+ if (item.Trim().EndsWith(">"))
{
- // Locate the end of opening tab.
- int openTagEndPosition = item.IndexOf(">");
- // Remove the identified section, if it is valid.
- if (openTagEndPosition >= 0)
- item = item.Substring(openTagEndPosition + 1);
- }
- }
- // Display the trimmed string.
- Console.WriteLine("After: " + item);
- Console.WriteLine();
- }
- }
+ // Locate the opening tag.
+ int endTagStartPosition = item.LastIndexOf("");
+ // Remove the identified section, if it is valid.
+ if (endTagStartPosition >= 0)
+ item = item.Substring(0, endTagStartPosition);
+
+ // Use StartsWith to find the opening tag.
+ if (item.Trim().StartsWith("<"))
+ {
+ // Locate the end of opening tab.
+ int openTagEndPosition = item.IndexOf(">");
+ // Remove the identified section, if it is valid.
+ if (openTagEndPosition >= 0)
+ item = item.Substring(openTagEndPosition + 1);
+ }
+ }
+ // Display the trimmed string.
+ Console.WriteLine("After: " + item);
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Before: This is bold text
// After: This is bold text
-//
+//
// Before: This is large Text
// After: This is large Text
-//
+//
// Before: This has multiple tags
// After: This has multiple tags
-//
+//
// Before: This has embedded tags.
// After: This has embedded tags.
-//
+//
// Before: This line ends with a greater than symbol and should not be modified>
// After: This line ends with a greater than symbol and should not be modified>
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof1.cs b/snippets/csharp/System/String/LastIndexOf/lastixof1.cs
index fc60630d9c4..5e3e7d2ef0a 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastixof1.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastixof1.cs
@@ -2,31 +2,33 @@
// Sample for String.LastIndexOf(Char, Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfCharSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
- start = str.Length-1;
- Console.WriteLine("All occurrences of 't' from position {0} to 0.", start);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("The letter 't' occurs at position(s): ");
+ start = str.Length - 1;
+ Console.WriteLine($"All occurrences of 't' from position {start} to 0.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write("The letter 't' occurs at position(s): ");
- at = 0;
- while((start > -1) && (at > -1))
+ at = 0;
+ while ((start > -1) && (at > -1))
{
- at = str.LastIndexOf('t', start);
- if (at > -1)
+ at = str.LastIndexOf('t', start);
+ if (at > -1)
{
- Console.Write("{0} ", at);
- start = at - 1;
+ Console.Write($"{at} ");
+ start = at - 1;
}
}
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -38,4 +40,4 @@ All occurrences of 't' from position 66 to 0.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof2.cs b/snippets/csharp/System/String/LastIndexOf/lastixof2.cs
index 09a23421cc9..4a92d56d2df 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastixof2.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastixof2.cs
@@ -2,36 +2,38 @@
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfCharRangeSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
- int count;
- int end;
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
+ int count;
+ int end;
- start = str.Length-1;
- end = start/2 - 1;
- Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("The letter 't' occurs at position(s): ");
+ start = str.Length - 1;
+ end = start / 2 - 1;
+ Console.WriteLine($"All occurrences of 't' from position {start} to {end}.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write("The letter 't' occurs at position(s): ");
- count = 0;
- at = 0;
- while((start > -1) && (at > -1))
+ count = 0;
+ at = 0;
+ while ((start > -1) && (at > -1))
{
- count = start - end; //Count must be within the substring.
- at = str.LastIndexOf('t', start, count);
- if (at > -1)
+ count = start - end; //Count must be within the substring.
+ at = str.LastIndexOf('t', start, count);
+ if (at > -1)
{
- Console.Write("{0} ", at);
- start = at - 1;
+ Console.Write($"{at} ");
+ start = at - 1;
}
}
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -45,4 +47,4 @@ All occurrences of 't' from position 66 to 32.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof7.cs b/snippets/csharp/System/String/LastIndexOf/lastixof7.cs
index 8f6333c2009..024ec87be7e 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastixof7.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastixof7.cs
@@ -2,31 +2,33 @@
// Sample for String.LastIndexOf(String, Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfStringSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
- start = str.Length-1;
- Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("The string 'he' occurs at position(s): ");
+ start = str.Length - 1;
+ Console.WriteLine($"All occurrences of 'he' from position {start} to 0.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write("The string 'he' occurs at position(s): ");
- at = 0;
- while((start > -1) && (at > -1))
+ at = 0;
+ while ((start > -1) && (at > -1))
{
- at = str.LastIndexOf("he", start);
- if (at > -1)
+ at = str.LastIndexOf("he", start);
+ if (at > -1)
{
- Console.Write("{0} ", at);
- start = at - 1;
+ Console.Write($"{at} ");
+ start = at - 1;
}
}
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -40,4 +42,4 @@ All occurrences of 'he' from position 66 to 0.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/lastixof8.cs b/snippets/csharp/System/String/LastIndexOf/lastixof8.cs
index 5870a79733d..f5740de3531 100644
--- a/snippets/csharp/System/String/LastIndexOf/lastixof8.cs
+++ b/snippets/csharp/System/String/LastIndexOf/lastixof8.cs
@@ -2,36 +2,38 @@
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfStringRangeSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
- int count;
- int end;
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
+ int count;
+ int end;
- start = str.Length-1;
- end = start/2 - 1;
- Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("The string 'he' occurs at position(s): ");
+ start = str.Length - 1;
+ end = start / 2 - 1;
+ Console.WriteLine($"All occurrences of 'he' from position {start} to {end}.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write("The string 'he' occurs at position(s): ");
- count = 0;
- at = 0;
- while((start > -1) && (at > -1))
+ count = 0;
+ at = 0;
+ while ((start > -1) && (at > -1))
{
- count = start - end; //Count must be within the substring.
- at = str.LastIndexOf("he", start, count);
- if (at > -1)
+ count = start - end; //Count must be within the substring.
+ at = str.LastIndexOf("he", start, count);
+ if (at > -1)
{
- Console.Write("{0} ", at);
- start = at - 1;
+ Console.Write($"{at} ");
+ start = at - 1;
}
}
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -43,4 +45,4 @@ All occurrences of 'he' from position 66 to 32.
The string 'he' occurs at position(s): 56 45
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOf/liocmp.cs b/snippets/csharp/System/String/LastIndexOf/liocmp.cs
index 39a9cc84947..8228ecdb874 100644
--- a/snippets/csharp/System/String/LastIndexOf/liocmp.cs
+++ b/snippets/csharp/System/String/LastIndexOf/liocmp.cs
@@ -1,89 +1,86 @@
//
-// This code example demonstrates the
+// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
-using System.Globalization;
-class Sample
+
+class LastIndexOfComparisonSample
{
- public static void Main()
+ public static void Run()
{
- string intro = "Find the last occurrence of a character using different " +
- "values of StringComparison.";
- string resultFmt = "Comparison: {0,-28} Location: {1,3}";
-
-// Define a string to search for.
-// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
- string CapitalAWithRing = "\u00c5";
-
-// Define a string to search.
-// The result of combining the characters LATIN SMALL LETTER A and COMBINING
-// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
-// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
- string cat = "A Cheshire c" + "\u0061\u030a" + "t";
- int loc = 0;
- StringComparison[] scValues = {
+ string intro = "Find the last occurrence of a character using different " +
+ "values of StringComparison.";
+ string resultFmt = "Comparison: {0,-28} Location: {1,3}";
+
+ // Define a string to search for.
+ // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
+ string CapitalAWithRing = "\u00c5";
+
+ // Define a string to search.
+ // The result of combining the characters LATIN SMALL LETTER A and COMBINING
+ // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
+ // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
+ string cat = "A Cheshire c" + "\u0061\u030a" + "t";
+ int loc = 0;
+ StringComparison[] scValues = [
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
- StringComparison.OrdinalIgnoreCase };
-
-// Clear the screen and display an introduction.
- Console.Clear();
- Console.WriteLine(intro);
-
-// Display the current culture because culture affects the result. For example,
-// try this code example with the "sv-SE" (Swedish-Sweden) culture.
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
- Console.WriteLine("The current culture is \"{0}\" - {1}.",
- Thread.CurrentThread.CurrentCulture.Name,
- Thread.CurrentThread.CurrentCulture.DisplayName);
-
-// Display the string to search for and the string to search.
- Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
- CapitalAWithRing, cat);
- Console.WriteLine();
-
-// Note that in each of the following searches, we look for
-// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
-// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
-// the string was not found.
-// Search using different values of StringComparsion. Specify the start
-// index and count.
-
- Console.WriteLine("Part 1: Start index and count are specified.");
- foreach (StringComparison sc in scValues)
+ StringComparison.OrdinalIgnoreCase ];
+
+ // Clear the screen and display an introduction.
+ Console.Clear();
+ Console.WriteLine(intro);
+
+ // Display the current culture because culture affects the result. For example,
+ // try this code example with the "sv-SE" (Swedish-Sweden) culture.
+
+ Thread.CurrentThread.CurrentCulture = new("en-US");
+ Console.WriteLine($"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}.");
+
+ // Display the string to search for and the string to search.
+ Console.WriteLine($"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"");
+ Console.WriteLine();
+
+ // Note that in each of the following searches, we look for
+ // LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
+ // LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
+ // the string was not found.
+ // Search using different values of StringComparsion. Specify the start
+ // index and count.
+
+ Console.WriteLine("Part 1: Start index and count are specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
-// Search using different values of StringComparsion. Specify the
-// start index.
- Console.WriteLine("\nPart 2: Start index is specified.");
- foreach (StringComparison sc in scValues)
+ // Search using different values of StringComparsion. Specify the
+ // start index.
+ Console.WriteLine("\nPart 2: Start index is specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
-// Search using different values of StringComparsion.
- Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
- foreach (StringComparison sc in scValues)
+ // Search using different values of StringComparsion.
+ Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
+ foreach (StringComparison sc in scValues)
{
- loc = cat.LastIndexOf(CapitalAWithRing, sc);
- Console.WriteLine(resultFmt, sc, loc);
+ loc = cat.LastIndexOf(CapitalAWithRing, sc);
+ Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
-Note: This code example was executed on a console whose user interface
+Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
@@ -117,4 +114,4 @@ public static void Main()
Comparison: OrdinalIgnoreCase Location: -1
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOfAny/Program.cs b/snippets/csharp/System/String/LastIndexOfAny/Program.cs
new file mode 100644
index 00000000000..0ed1a250cee
--- /dev/null
+++ b/snippets/csharp/System/String/LastIndexOfAny/Program.cs
@@ -0,0 +1,3 @@
+LastIndexOfAnySample.Run();
+LastIndexOfAnyStartSample.Run();
+LastIndexOfAnyRangeSample.Run();
diff --git a/snippets/csharp/System/String/LastIndexOfAny/Project.csproj b/snippets/csharp/System/String/LastIndexOfAny/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/LastIndexOfAny/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs
index 2a7cf5a248c..837d91f059f 100644
--- a/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs
+++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany1.cs
@@ -2,28 +2,30 @@
// Sample for String.LastIndexOfAny(Char[])
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfAnySample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
- string target = "is";
- char[] anyOf = target.ToCharArray();
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
+ string target = "is";
+ char[] anyOf = target.ToCharArray();
- start = str.Length-1;
- Console.WriteLine("The last character occurrence from position {0} to 0.", start);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("A character in '{0}' occurs at position: ", target);
+ start = str.Length - 1;
+ Console.WriteLine($"The last character occurrence from position {start} to 0.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write($"A character in '{target}' occurs at position: ");
- at = str.LastIndexOfAny(anyOf);
- if (at > -1)
- Console.Write(at);
- else
- Console.Write("(not found)");
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ at = str.LastIndexOfAny(anyOf);
+ if (at > -1)
+ Console.Write(at);
+ else
+ Console.Write("(not found)");
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -37,4 +39,4 @@ The last character occurrence from position 66 to 0.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs
index 9dc667f3f92..d3365e029ab 100644
--- a/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs
+++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany2.cs
@@ -2,28 +2,30 @@
// Sample for String.LastIndexOfAny(Char[], Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfAnyStartSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
- string target = "is";
- char[] anyOf = target.ToCharArray();
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
+ string target = "is";
+ char[] anyOf = target.ToCharArray();
- start = (str.Length-1)/2;
- Console.WriteLine("The last character occurrence from position {0} to 0.", start);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("A character in '{0}' occurs at position: ", target);
+ start = (str.Length - 1) / 2;
+ Console.WriteLine($"The last character occurrence from position {start} to 0.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write($"A character in '{target}' occurs at position: ");
- at = str.LastIndexOfAny(anyOf, start);
- if (at > -1)
- Console.Write(at);
- else
- Console.Write("(not found)");
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ at = str.LastIndexOfAny(anyOf, start);
+ if (at > -1)
+ Console.Write(at);
+ else
+ Console.Write("(not found)");
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -37,4 +39,4 @@ The last character occurrence from position 33 to 0.
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs b/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs
index 6d469b914b0..693f05ef2d4 100644
--- a/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs
+++ b/snippets/csharp/System/String/LastIndexOfAny/lastixany3.cs
@@ -2,30 +2,32 @@
// Sample for String.LastIndexOfAny(Char[], Int32, Int32)
using System;
-class Sample {
- public static void Main() {
+class LastIndexOfAnyRangeSample
+{
+ public static void Run()
+ {
- string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
- string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
- string str = "Now is the time for all good men to come to the aid of their party.";
- int start;
- int at;
- int count;
- string target = "aid";
- char[] anyOf = target.ToCharArray();
+ string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
+ string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
+ string str = "Now is the time for all good men to come to the aid of their party.";
+ int start;
+ int at;
+ int count;
+ string target = "aid";
+ char[] anyOf = target.ToCharArray();
- start = ((str.Length-1)*2)/3;
- count = (str.Length-1)/3;
- Console.WriteLine("The last character occurrence from position {0} for {1} characters.", start, count);
- Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
- Console.Write("A character in '{0}' occurs at position: ", target);
+ start = ((str.Length - 1) * 2) / 3;
+ count = (str.Length - 1) / 3;
+ Console.WriteLine($"The last character occurrence from position {start} for {count} characters.");
+ Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
+ Console.Write($"A character in '{target}' occurs at position: ");
- at = str.LastIndexOfAny(anyOf, start, count);
- if (at > -1)
- Console.Write(at);
- else
- Console.Write("(not found)");
- Console.Write("{0}{0}{0}", Environment.NewLine);
+ at = str.LastIndexOfAny(anyOf, start, count);
+ if (at > -1)
+ Console.Write(at);
+ else
+ Console.Write("(not found)");
+ Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
@@ -37,4 +39,4 @@ public static void Main() {
A character in 'aid' occurs at position: 27
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Length/length.cs b/snippets/csharp/System/String/Length/length.cs
index 943ec2dc761..f5b68edd556 100644
--- a/snippets/csharp/System/String/Length/length.cs
+++ b/snippets/csharp/System/String/Length/length.cs
@@ -6,11 +6,11 @@ public static void Main()
{
//
string str = "abcdefg";
- Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length);
- Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length);
+ Console.WriteLine($"1) The length of '{str}' is {str.Length}");
+ Console.WriteLine($"2) The length of '{"xyz"}' is {"xyz".Length}");
int length = str.Length;
- Console.WriteLine("3) The length of '{0}' is {1}", str, length);
+ Console.WriteLine($"3) The length of '{str}' is {length}");
// This example displays the following output:
// 1) The length of 'abcdefg' is 7
diff --git a/snippets/csharp/System/String/Overview/System.String.Class.cs b/snippets/csharp/System/String/Overview/System.String.Class.cs
index d45e146c43a..6b311953a7d 100644
--- a/snippets/csharp/System/String/Overview/System.String.Class.cs
+++ b/snippets/csharp/System/String/Overview/System.String.Class.cs
@@ -1,13 +1,13 @@
using System;
-using System.Text;
+
public class StringClassTest
{
- public static void Main()
- {
- //
- string characters = "abc\u0000def";
- Console.WriteLine(characters.Length); // Displays 7
- //
- }
+ public static void Main()
+ {
+ //
+ string characters = "abc\u0000def";
+ Console.WriteLine(characters.Length); // Displays 7
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Overview/case1.cs b/snippets/csharp/System/String/Overview/case1.cs
index 7bf03f61dbf..2e4209c1a86 100644
--- a/snippets/csharp/System/String/Overview/case1.cs
+++ b/snippets/csharp/System/String/Overview/case1.cs
@@ -5,51 +5,53 @@
public class Example
{
- public static void Main()
- {
- StreamWriter sw = new StreamWriter(@".\case.txt");
- string[] words = { "file", "sıfır", "Dženana" };
- CultureInfo[] cultures = { CultureInfo.InvariantCulture,
- new CultureInfo("en-US"),
- new CultureInfo("tr-TR") };
+ public static void Main()
+ {
+ StreamWriter sw = new(@".\case.txt");
+ string[] words = ["file", "sıfır", "Dženana"];
+ CultureInfo[] cultures = [CultureInfo.InvariantCulture,
+ new CultureInfo("en-US"),
+ new CultureInfo("tr-TR")];
- foreach (var word in words) {
- sw.WriteLine("{0}:", word);
- foreach (var culture in cultures) {
- string name = String.IsNullOrEmpty(culture.Name) ?
- "Invariant" : culture.Name;
- string upperWord = word.ToUpper(culture);
- sw.WriteLine(" {0,10}: {1,7} {2, 38}", name,
- upperWord, ShowHexValue(upperWord));
- }
- sw.WriteLine();
- }
- sw.Close();
- }
+ foreach (string word in words)
+ {
+ sw.WriteLine($"{word}:");
+ foreach (var culture in cultures)
+ {
+ string name = string.IsNullOrEmpty(culture.Name) ?
+ "Invariant" : culture.Name;
+ string upperWord = word.ToUpper(culture);
+ sw.WriteLine($" {name,10}: {upperWord,7} {ShowHexValue(upperWord),38}");
+ }
+ sw.WriteLine();
+ }
+ sw.Close();
+ }
- private static string ShowHexValue(string s)
- {
- string retval = null;
- foreach (var ch in s) {
- byte[] bytes = BitConverter.GetBytes(ch);
- retval += String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0]);
- }
- return retval;
- }
+ private static string ShowHexValue(string s)
+ {
+ string retval = null;
+ foreach (char ch in s)
+ {
+ byte[] bytes = BitConverter.GetBytes(ch);
+ retval += $"{bytes[1]:X2} {bytes[0]:X2} ";
+ }
+ return retval;
+ }
}
// The example displays the following output:
// file:
-// Invariant: FILE 00 46 00 49 00 4C 00 45
-// en-US: FILE 00 46 00 49 00 4C 00 45
-// tr-TR: FİLE 00 46 01 30 00 4C 00 45
-//
+// Invariant: FILE 00 46 00 49 00 4C 00 45
+// en-US: FILE 00 46 00 49 00 4C 00 45
+// tr-TR: FİLE 00 46 01 30 00 4C 00 45
+//
// sıfır:
-// Invariant: SıFıR 00 53 01 31 00 46 01 31 00 52
-// en-US: SIFIR 00 53 00 49 00 46 00 49 00 52
-// tr-TR: SIFIR 00 53 00 49 00 46 00 49 00 52
-//
+// Invariant: SıFıR 00 53 01 31 00 46 01 31 00 52
+// en-US: SIFIR 00 53 00 49 00 46 00 49 00 52
+// tr-TR: SIFIR 00 53 00 49 00 46 00 49 00 52
+//
// Dženana:
-// Invariant: DžENANA 01 C5 00 45 00 4E 00 41 00 4E 00 41
-// en-US: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41
-// tr-TR: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41
-//
+// Invariant: DžENANA 01 C5 00 45 00 4E 00 41 00 4E 00 41
+// en-US: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41
+// tr-TR: DŽENANA 01 C4 00 45 00 4E 00 41 00 4E 00 41
+//
diff --git a/snippets/csharp/System/String/Overview/case2.cs b/snippets/csharp/System/String/Overview/case2.cs
index 5e76ba4ba2a..a49b104aec7 100644
--- a/snippets/csharp/System/String/Overview/case2.cs
+++ b/snippets/csharp/System/String/Overview/case2.cs
@@ -5,38 +5,35 @@
public class Example
{
- const string disallowed = "file";
-
- public static void Main()
- {
- IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
- }
+ const string disallowed = "file";
- private static void IsAccessAllowed(String resource)
- {
- CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
- CultureInfo.CreateSpecificCulture("tr-TR") };
- String scheme = null;
- int index = resource.IndexOfAny( new Char[] { '\\', '/' } );
- if (index > 0)
- scheme = resource.Substring(0, index - 1);
+ public static void Main() => IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
- // Change the current culture and perform the comparison.
- foreach (var culture in cultures) {
- Thread.CurrentThread.CurrentCulture = culture;
- Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
- Console.WriteLine(resource);
- Console.WriteLine("Access allowed: {0}",
- ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase));
- Console.WriteLine();
- }
- }
+ private static void IsAccessAllowed(string resource)
+ {
+ CultureInfo[] cultures = [CultureInfo.CreateSpecificCulture("en-US"),
+ CultureInfo.CreateSpecificCulture("tr-TR")];
+ string scheme = null;
+ int index = resource.IndexOfAny(['\\', '/']);
+ if (index > 0)
+ scheme = resource.Substring(0, index - 1);
+
+ // Change the current culture and perform the comparison.
+ foreach (var culture in cultures)
+ {
+ Thread.CurrentThread.CurrentCulture = culture;
+ Console.WriteLine($"Culture: {CultureInfo.CurrentCulture.DisplayName}");
+ Console.WriteLine(resource);
+ Console.WriteLine($"Access allowed: {!string.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase)}");
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// Culture: English (United States)
// FILE:\\\c:\users\user001\documents\FinancialInfo.txt
// Access allowed: False
-//
+//
// Culture: Turkish (Turkey)
// FILE:\\\c:\users\user001\documents\FinancialInfo.txt
// Access allowed: True
diff --git a/snippets/csharp/System/String/Overview/compare11.cs b/snippets/csharp/System/String/Overview/compare11.cs
index 6ad8377992b..6408bca1b84 100644
--- a/snippets/csharp/System/String/Overview/compare11.cs
+++ b/snippets/csharp/System/String/Overview/compare11.cs
@@ -5,12 +5,12 @@
public class Example
{
- public static void Main()
- {
- Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
- Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture));
- Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal));
- }
+ public static void Main()
+ {
+ Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
+ Console.WriteLine(string.Compare("A", "a", StringComparison.CurrentCulture));
+ Console.WriteLine(string.Compare("A", "a", StringComparison.Ordinal));
+ }
}
// The example displays the following output:
// 1
diff --git a/snippets/csharp/System/String/Overview/compare2.cs b/snippets/csharp/System/String/Overview/compare2.cs
index 6a622fd7cf3..f224ef9fc8d 100644
--- a/snippets/csharp/System/String/Overview/compare2.cs
+++ b/snippets/csharp/System/String/Overview/compare2.cs
@@ -1,62 +1,55 @@
//
using System;
-using System.Collections;
+
using System.Collections.Generic;
using System.Globalization;
-
+
public class Example
{
- public static void Main()
- {
- string[] strings = { "coop", "co-op", "cooperative",
- "co\u00ADoperative", "cœur", "coeur" };
-
- // Perform a word sort using the current (en-US) culture.
- string[] current = new string[strings.Length];
- strings.CopyTo(current, 0);
- Array.Sort(current, StringComparer.CurrentCulture);
-
- // Perform a word sort using the invariant culture.
- string[] invariant = new string[strings.Length];
- strings.CopyTo(invariant, 0);
- Array.Sort(invariant, StringComparer.InvariantCulture);
-
- // Perform an ordinal sort.
- string[] ordinal = new string[strings.Length];
- strings.CopyTo(ordinal, 0);
- Array.Sort(ordinal, StringComparer.Ordinal);
-
- // Perform a string sort using the current culture.
- string[] stringSort = new string[strings.Length];
- strings.CopyTo(stringSort, 0);
- Array.Sort(stringSort, new SCompare());
-
- // Display array values
- Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n",
- "Original", "Word Sort", "Invariant Word",
- "Ordinal Sort", "String Sort");
- for (int ctr = 0; ctr < strings.Length; ctr++)
- Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}",
- strings[ctr], current[ctr], invariant[ctr],
- ordinal[ctr], stringSort[ctr] );
- }
+ public static void Main()
+ {
+ string[] strings = ["coop", "co-op", "cooperative",
+ "co\u00ADoperative", "cœur", "coeur"];
+
+ // Perform a word sort using the current (en-US) culture.
+ string[] current = new string[strings.Length];
+ strings.CopyTo(current, 0);
+ Array.Sort(current, StringComparer.CurrentCulture);
+
+ // Perform a word sort using the invariant culture.
+ string[] invariant = new string[strings.Length];
+ strings.CopyTo(invariant, 0);
+ Array.Sort(invariant, StringComparer.InvariantCulture);
+
+ // Perform an ordinal sort.
+ string[] ordinal = new string[strings.Length];
+ strings.CopyTo(ordinal, 0);
+ Array.Sort(ordinal, StringComparer.Ordinal);
+
+ // Perform a string sort using the current culture.
+ string[] stringSort = new string[strings.Length];
+ strings.CopyTo(stringSort, 0);
+ Array.Sort(stringSort, new SCompare());
+
+ // Display array values
+ Console.WriteLine($"{"Original",13} {"Word Sort",13} {"Invariant Word",15} {"Ordinal Sort",13} {"String Sort",13}\n");
+ for (int ctr = 0; ctr < strings.Length; ctr++)
+ Console.WriteLine($"{strings[ctr],13} {current[ctr],13} {invariant[ctr],15} {ordinal[ctr],13} {stringSort[ctr],13}");
+ }
}
// IComparer implementation to perform string sort.
-internal class SCompare : IComparer
+internal class SCompare : IComparer
{
- public int Compare(string x, string y)
- {
- return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort);
- }
+ public int Compare(string x, string y) => CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort);
}
// The example displays the following output:
// Original Word Sort Invariant Word Ordinal Sort String Sort
-//
+//
// coop cœur cœur co-op co-op
// co-op coeur coeur coeur cœur
// cooperative coop coop coop coeur
// cooperative co-op co-op cooperative coop
// cœur cooperative cooperative cooperative cooperative
// coeur cooperative cooperative cœur cooperative
-//
+//
diff --git a/snippets/csharp/System/String/Overview/compare3.cs b/snippets/csharp/System/String/Overview/compare3.cs
index f09b00e6399..e8e916ed258 100644
--- a/snippets/csharp/System/String/Overview/compare3.cs
+++ b/snippets/csharp/System/String/Overview/compare3.cs
@@ -3,39 +3,37 @@
public class Example
{
- public static void Main()
- {
- // Search for "oe" and "œu" in "œufs" and "oeufs".
- string s1 = "œufs";
- string s2 = "oeufs";
- FindInString(s1, "oe", StringComparison.CurrentCulture);
- FindInString(s1, "oe", StringComparison.Ordinal);
- FindInString(s2, "œu", StringComparison.CurrentCulture);
- FindInString(s2, "œu", StringComparison.Ordinal);
- Console.WriteLine();
-
- string s3 = "co\u00ADoperative";
- FindInString(s3, "\u00AD", StringComparison.CurrentCulture);
- FindInString(s3, "\u00AD", StringComparison.Ordinal);
- }
+ public static void Main()
+ {
+ // Search for "oe" and "œu" in "œufs" and "oeufs".
+ string s1 = "œufs";
+ string s2 = "oeufs";
+ FindInString(s1, "oe", StringComparison.CurrentCulture);
+ FindInString(s1, "oe", StringComparison.Ordinal);
+ FindInString(s2, "œu", StringComparison.CurrentCulture);
+ FindInString(s2, "œu", StringComparison.Ordinal);
+ Console.WriteLine();
- private static void FindInString(string s, string substring, StringComparison options)
- {
- int result = s.IndexOf(substring, options);
- if (result != -1)
- Console.WriteLine("'{0}' found in {1} at position {2}",
- substring, s, result);
- else
- Console.WriteLine("'{0}' not found in {1}",
- substring, s);
- }
+ string s3 = "co\u00ADoperative";
+ FindInString(s3, "\u00AD", StringComparison.CurrentCulture);
+ FindInString(s3, "\u00AD", StringComparison.Ordinal);
+ }
+
+ private static void FindInString(string s, string substring, StringComparison options)
+ {
+ int result = s.IndexOf(substring, options);
+ if (result != -1)
+ Console.WriteLine($"'{substring}' found in {s} at position {result}");
+ else
+ Console.WriteLine($"'{substring}' not found in {s}");
+ }
}
// The example displays the following output:
// 'oe' found in œufs at position 0
// 'oe' not found in œufs
// 'œu' found in oeufs at position 0
// 'œu' not found in oeufs
-//
+//
// '' found in cooperative at position 0
// '' found in cooperative at position 2
//
diff --git a/snippets/csharp/System/String/Overview/compare4.cs b/snippets/csharp/System/String/Overview/compare4.cs
index eb56bef05bc..56fa038fe9c 100644
--- a/snippets/csharp/System/String/Overview/compare4.cs
+++ b/snippets/csharp/System/String/Overview/compare4.cs
@@ -5,49 +5,39 @@
public class CompareStringSample
{
- public static void Main()
- {
- string str1 = "Apple";
- string str2 = "Æble";
- string str3 = "AEble";
-
- // Set the current culture to Danish in Denmark.
- Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
- Console.WriteLine("Current culture: {0}",
- CultureInfo.CurrentCulture.Name);
- Console.WriteLine("Comparison of {0} with {1}: {2}",
- str1, str2, String.Compare(str1, str2));
- Console.WriteLine("Comparison of {0} with {1}: {2}\n",
- str2, str3, String.Compare(str2, str3));
-
- // Set the current culture to English in the U.S.
- Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
- Console.WriteLine("Current culture: {0}",
- CultureInfo.CurrentCulture.Name);
- Console.WriteLine("Comparison of {0} with {1}: {2}",
- str1, str2, String.Compare(str1, str2));
- Console.WriteLine("Comparison of {0} with {1}: {2}\n",
- str2, str3, String.Compare(str2, str3));
-
- // Perform an ordinal comparison.
- Console.WriteLine("Ordinal comparison");
- Console.WriteLine("Comparison of {0} with {1}: {2}",
- str1, str2,
- String.Compare(str1, str2, StringComparison.Ordinal));
- Console.WriteLine("Comparison of {0} with {1}: {2}",
- str2, str3,
- String.Compare(str2, str3, StringComparison.Ordinal));
- }
+ public static void Main()
+ {
+ string str1 = "Apple";
+ string str2 = "Æble";
+ string str3 = "AEble";
+
+ // Set the current culture to Danish in Denmark.
+ Thread.CurrentThread.CurrentCulture = new("da-DK");
+ Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}");
+ Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2)}");
+ Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3)}\n");
+
+ // Set the current culture to English in the U.S.
+ Thread.CurrentThread.CurrentCulture = new("en-US");
+ Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}");
+ Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2)}");
+ Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3)}\n");
+
+ // Perform an ordinal comparison.
+ Console.WriteLine("Ordinal comparison");
+ Console.WriteLine($"Comparison of {str1} with {str2}: {string.Compare(str1, str2, StringComparison.Ordinal)}");
+ Console.WriteLine($"Comparison of {str2} with {str3}: {string.Compare(str2, str3, StringComparison.Ordinal)}");
+ }
}
// The example displays the following output:
// Current culture: da-DK
// Comparison of Apple with Æble: -1
// Comparison of Æble with AEble: 1
-//
+//
// Current culture: en-US
// Comparison of Apple with Æble: 1
// Comparison of Æble with AEble: 0
-//
+//
// Ordinal comparison
// Comparison of Apple with Æble: -133
// Comparison of Æble with AEble: 133
diff --git a/snippets/csharp/System/String/Overview/equality1.cs b/snippets/csharp/System/String/Overview/equality1.cs
index 7f8cf23fca1..aaa04d4b042 100644
--- a/snippets/csharp/System/String/Overview/equality1.cs
+++ b/snippets/csharp/System/String/Overview/equality1.cs
@@ -5,38 +5,38 @@
public class Example
{
- public static void Main()
- {
- Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
+ public static void Main()
+ {
+ Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
- string filePath = "file://c:/notes.txt";
-
- Console.WriteLine("Culture-sensitive test for equality:");
- if (!TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase))
- Console.WriteLine("Access to {0} is allowed.", filePath);
- else
- Console.WriteLine("Access to {0} is not allowed.", filePath);
-
- Console.WriteLine("\nOrdinal test for equality:");
- if (!TestForEquality(filePath, StringComparison.OrdinalIgnoreCase))
- Console.WriteLine("Access to {0} is allowed.", filePath);
- else
- Console.WriteLine("Access to {0} is not allowed.", filePath);
- }
+ string filePath = "file://c:/notes.txt";
- private static bool TestForEquality(string str, StringComparison cmp)
- {
- int position = str.IndexOf("://");
- if (position < 0) return false;
+ Console.WriteLine("Culture-sensitive test for equality:");
+ if (!TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase))
+ Console.WriteLine($"Access to {filePath} is allowed.");
+ else
+ Console.WriteLine($"Access to {filePath} is not allowed.");
- string substring = str.Substring(0, position);
- return substring.Equals("FILE", cmp);
- }
+ Console.WriteLine("\nOrdinal test for equality:");
+ if (!TestForEquality(filePath, StringComparison.OrdinalIgnoreCase))
+ Console.WriteLine($"Access to {filePath} is allowed.");
+ else
+ Console.WriteLine($"Access to {filePath} is not allowed.");
+ }
+
+ private static bool TestForEquality(string str, StringComparison cmp)
+ {
+ int position = str.IndexOf("://");
+ if (position < 0) return false;
+
+ string substring = str.Substring(0, position);
+ return substring.Equals("FILE", cmp);
+ }
}
// The example displays the following output:
// Culture-sensitive test for equality:
// Access to file://c:/notes.txt is allowed.
-//
+//
// Ordinal test for equality:
// Access to file://c:/notes.txt is not allowed.
//
diff --git a/snippets/csharp/System/String/Overview/format1.cs b/snippets/csharp/System/String/Overview/format1.cs
index ad80b2938da..4c83842befc 100644
--- a/snippets/csharp/System/String/Overview/format1.cs
+++ b/snippets/csharp/System/String/Overview/format1.cs
@@ -4,18 +4,17 @@
public class Example
{
- public static void Main()
- {
- DateTime date = new DateTime(2011, 3, 1);
- CultureInfo[] cultures = { CultureInfo.InvariantCulture,
- new CultureInfo("en-US"),
- new CultureInfo("fr-FR") };
+ public static void Main()
+ {
+ DateTime date = new(2011, 3, 1);
+ CultureInfo[] cultures = [CultureInfo.InvariantCulture,
+ new CultureInfo("en-US"),
+ new CultureInfo("fr-FR")];
- foreach (var culture in cultures)
- Console.WriteLine("{0,-12} {1}", String.IsNullOrEmpty(culture.Name) ?
- "Invariant" : culture.Name,
- date.ToString("d", culture));
- }
+ foreach (var culture in cultures)
+ Console.WriteLine($"{(string.IsNullOrEmpty(culture.Name) ?
+ "Invariant" : culture.Name),-12} {date.ToString("d", culture)}");
+ }
}
// The example displays the following output:
// Invariant 03/01/2011
diff --git a/snippets/csharp/System/String/Overview/grapheme1.cs b/snippets/csharp/System/String/Overview/grapheme1.cs
index a4e04a0b855..75b13221c72 100644
--- a/snippets/csharp/System/String/Overview/grapheme1.cs
+++ b/snippets/csharp/System/String/Overview/grapheme1.cs
@@ -1,31 +1,28 @@
//
using System;
-using System.Globalization;
+
using System.IO;
public class Example
{
- public static void Main()
- {
- StreamWriter sw = new StreamWriter(@".\graphemes.txt");
- string grapheme = "\u0061\u0308";
- sw.WriteLine(grapheme);
-
- string singleChar = "\u00e4";
- sw.WriteLine(singleChar);
-
- sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar,
- String.Equals(grapheme, singleChar,
- StringComparison.CurrentCulture));
- sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar,
- String.Equals(grapheme, singleChar,
- StringComparison.Ordinal));
- sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar,
- String.Equals(grapheme.Normalize(),
- singleChar.Normalize(),
- StringComparison.Ordinal));
- sw.Close();
- }
+ public static void Main()
+ {
+ StreamWriter sw = new(@".\graphemes.txt");
+ string grapheme = "\u0061\u0308";
+ sw.WriteLine(grapheme);
+
+ string singleChar = "\u00e4";
+ sw.WriteLine(singleChar);
+
+ sw.WriteLine($"{grapheme} = {singleChar} (Culture-sensitive): {string.Equals(grapheme, singleChar,
+ StringComparison.CurrentCulture)}");
+ sw.WriteLine($"{grapheme} = {singleChar} (Ordinal): {string.Equals(grapheme, singleChar,
+ StringComparison.Ordinal)}");
+ sw.WriteLine($"{grapheme} = {singleChar} (Normalized Ordinal): {string.Equals(grapheme.Normalize(),
+ singleChar.Normalize(),
+ StringComparison.Ordinal)}");
+ sw.Close();
+ }
}
// The example produces the following output:
// ä
diff --git a/snippets/csharp/System/String/Overview/immutable.cs b/snippets/csharp/System/String/Overview/immutable.cs
index 571d9fd093d..9f99dd02d10 100644
--- a/snippets/csharp/System/String/Overview/immutable.cs
+++ b/snippets/csharp/System/String/Overview/immutable.cs
@@ -5,21 +5,22 @@
public class Example
{
- public static void Main()
- {
- Random rnd = new Random();
-
- string str = String.Empty;
- StreamWriter sw = new StreamWriter(@".\StringFile.txt",
- false, Encoding.Unicode);
+ public static void Main()
+ {
+ Random rnd = new();
- for (int ctr = 0; ctr <= 1000; ctr++) {
- str += (char)rnd.Next(1, 0x0530);
- if (str.Length % 60 == 0)
- str += Environment.NewLine;
- }
- sw.Write(str);
- sw.Close();
- }
+ string str = string.Empty;
+ StreamWriter sw = new(@".\StringFile.txt",
+ false, Encoding.Unicode);
+
+ for (int ctr = 0; ctr <= 1000; ctr++)
+ {
+ str += (char)rnd.Next(1, 0x0530);
+ if (str.Length % 60 == 0)
+ str += Environment.NewLine;
+ }
+ sw.Write(str);
+ sw.Close();
+ }
}
//
diff --git a/snippets/csharp/System/String/Overview/immutable1.cs b/snippets/csharp/System/String/Overview/immutable1.cs
index 7acce8bd779..707334e238e 100644
--- a/snippets/csharp/System/String/Overview/immutable1.cs
+++ b/snippets/csharp/System/String/Overview/immutable1.cs
@@ -5,20 +5,21 @@
public class Example
{
- public static void Main()
- {
- Random rnd = new Random();
- StringBuilder sb = new StringBuilder();
- StreamWriter sw = new StreamWriter(@".\StringFile.txt",
- false, Encoding.Unicode);
+ public static void Main()
+ {
+ Random rnd = new();
+ StringBuilder sb = new();
+ StreamWriter sw = new(@".\StringFile.txt",
+ false, Encoding.Unicode);
- for (int ctr = 0; ctr <= 1000; ctr++) {
- sb.Append((char)rnd.Next(1, 0x0530));
- if (sb.Length % 60 == 0)
- sb.AppendLine();
- }
- sw.Write(sb.ToString());
- sw.Close();
- }
+ for (int ctr = 0; ctr <= 1000; ctr++)
+ {
+ sb.Append((char)rnd.Next(1, 0x0530));
+ if (sb.Length % 60 == 0)
+ sb.AppendLine();
+ }
+ sw.Write(sb);
+ sw.Close();
+ }
}
//
diff --git a/snippets/csharp/System/String/Overview/index11.cs b/snippets/csharp/System/String/Overview/index11.cs
index ef64e09c306..21a336bf445 100644
--- a/snippets/csharp/System/String/Overview/index11.cs
+++ b/snippets/csharp/System/String/Overview/index11.cs
@@ -2,23 +2,23 @@
public class Example
{
- public static void Main()
- {
- //
- string s1 = "This string consists of a single short sentence.";
- int nWords = 0;
+ public static void Main()
+ {
+ //
+ string s1 = "This string consists of a single short sentence.";
+ int nWords = 0;
- s1 = s1.Trim();
- for (int ctr = 0; ctr < s1.Length; ctr++) {
- if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr]))
- nWords++;
- }
- Console.WriteLine("The sentence\n {0}\nhas {1} words.",
- s1, nWords);
- // The example displays the following output:
- // The sentence
- // This string consists of a single short sentence.
- // has 8 words.
- //
- }
+ s1 = s1.Trim();
+ for (int ctr = 0; ctr < s1.Length; ctr++)
+ {
+ if (char.IsPunctuation(s1[ctr]) || char.IsWhiteSpace(s1[ctr]))
+ nWords++;
+ }
+ Console.WriteLine($"The sentence\n {s1}\nhas {nWords} words.");
+ // The example displays the following output:
+ // The sentence
+ // This string consists of a single short sentence.
+ // has 8 words.
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Overview/index2.cs b/snippets/csharp/System/String/Overview/index2.cs
index a34063b02e4..1e5633c01a7 100644
--- a/snippets/csharp/System/String/Overview/index2.cs
+++ b/snippets/csharp/System/String/Overview/index2.cs
@@ -2,23 +2,23 @@
public class Example
{
- public static void Main()
- {
- //
- string s1 = "This string consists of a single short sentence.";
- int nWords = 0;
+ public static void Main()
+ {
+ //
+ string s1 = "This string consists of a single short sentence.";
+ int nWords = 0;
- s1 = s1.Trim();
- foreach (var ch in s1) {
- if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch))
- nWords++;
- }
- Console.WriteLine("The sentence\n {0}\nhas {1} words.",
- s1, nWords);
- // The example displays the following output:
- // The sentence
- // This string consists of a single short sentence.
- // has 8 words.
- //
- }
+ s1 = s1.Trim();
+ foreach (char ch in s1)
+ {
+ if (char.IsPunctuation(ch) || char.IsWhiteSpace(ch))
+ nWords++;
+ }
+ Console.WriteLine($"The sentence\n {s1}\nhas {nWords} words.");
+ // The example displays the following output:
+ // The sentence
+ // This string consists of a single short sentence.
+ // has 8 words.
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Overview/index3.cs b/snippets/csharp/System/String/Overview/index3.cs
index e19fee09d03..dffa7527192 100644
--- a/snippets/csharp/System/String/Overview/index3.cs
+++ b/snippets/csharp/System/String/Overview/index3.cs
@@ -3,74 +3,78 @@
public class Example
{
- public static void Main()
- {
- //
- // First sentence of The Mystery of the Yellow Room, by Leroux.
- string opening = "Ce n'est pas sans une certaine émotion que "+
- "je commence à raconter ici les aventures " +
- "extraordinaires de Joseph Rouletabille.";
- // Character counters.
- int nChars = 0;
- // Objects to store word count.
- List chars = new List();
- List elements = new List();
-
- foreach (var ch in opening) {
- // Skip the ' character.
- if (ch == '\u0027') continue;
-
- if (Char.IsWhiteSpace(ch) | (Char.IsPunctuation(ch))) {
- chars.Add(nChars);
- nChars = 0;
- }
- else {
- nChars++;
- }
- }
+ public static void Main()
+ {
+ //
+ // First sentence of The Mystery of the Yellow Room, by Leroux.
+ string opening = "Ce n'est pas sans une certaine émotion que " +
+ "je commence à raconter ici les aventures " +
+ "extraordinaires de Joseph Rouletabille.";
+ // Character counters.
+ int nChars = 0;
+ // Objects to store word count.
+ List chars = new();
+ List elements = new();
- System.Globalization.TextElementEnumerator te =
- System.Globalization.StringInfo.GetTextElementEnumerator(opening);
- while (te.MoveNext()) {
- string s = te.GetTextElement();
- // Skip the ' character.
- if (s == "\u0027") continue;
- if ( String.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && Char.IsPunctuation(Convert.ToChar(s)))) {
- elements.Add(nChars);
- nChars = 0;
- }
- else {
- nChars++;
- }
- }
+ foreach (char ch in opening)
+ {
+ // Skip the ' character.
+ if (ch == '\u0027') continue;
- // Display character counts.
- Console.WriteLine("{0,6} {1,20} {2,20}",
- "Word #", "Char Objects", "Characters");
- for (int ctr = 0; ctr < chars.Count; ctr++)
- Console.WriteLine("{0,6} {1,20} {2,20}",
- ctr, chars[ctr], elements[ctr]);
- // The example displays the following output:
- // Word # Char Objects Characters
- // 0 2 2
- // 1 4 4
- // 2 3 3
- // 3 4 4
- // 4 3 3
- // 5 8 8
- // 6 8 7
- // 7 3 3
- // 8 2 2
- // 9 8 8
- // 10 2 1
- // 11 8 8
- // 12 3 3
- // 13 3 3
- // 14 9 9
- // 15 15 15
- // 16 2 2
- // 17 6 6
- // 18 12 12
- //
- }
+ if (char.IsWhiteSpace(ch) | (char.IsPunctuation(ch)))
+ {
+ chars.Add(nChars);
+ nChars = 0;
+ }
+ else
+ {
+ nChars++;
+ }
+ }
+
+ System.Globalization.TextElementEnumerator te =
+ System.Globalization.StringInfo.GetTextElementEnumerator(opening);
+ while (te.MoveNext())
+ {
+ string s = te.GetTextElement();
+ // Skip the ' character.
+ if (s == "\u0027") continue;
+ if (string.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && char.IsPunctuation(Convert.ToChar(s))))
+ {
+ elements.Add(nChars);
+ nChars = 0;
+ }
+ else
+ {
+ nChars++;
+ }
+ }
+
+ // Display character counts.
+ Console.WriteLine($"{"Word #",6} {"Char Objects",20} {"Characters",20}");
+ for (int ctr = 0; ctr < chars.Count; ctr++)
+ Console.WriteLine($"{ctr,6} {chars[ctr],20} {elements[ctr],20}");
+ // The example displays the following output:
+ // Word # Char Objects Characters
+ // 0 2 2
+ // 1 4 4
+ // 2 3 3
+ // 3 4 4
+ // 4 3 3
+ // 5 8 8
+ // 6 8 7
+ // 7 3 3
+ // 8 2 2
+ // 9 8 8
+ // 10 2 1
+ // 11 8 8
+ // 12 3 3
+ // 13 3 3
+ // 14 9 9
+ // 15 15 15
+ // 16 2 2
+ // 17 6 6
+ // 18 12 12
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Overview/normalize1.cs b/snippets/csharp/System/String/Overview/normalize1.cs
index 6c17b6d3930..92746c3223f 100644
--- a/snippets/csharp/System/String/Overview/normalize1.cs
+++ b/snippets/csharp/System/String/Overview/normalize1.cs
@@ -1,92 +1,89 @@
//
using System;
-using System.Globalization;
+
using System.IO;
using System.Text;
public class Example
{
- private static StreamWriter sw;
-
- public static void Main()
- {
- sw = new StreamWriter(@".\TestNorm1.txt");
+ private static StreamWriter sw;
+
+ public static void Main()
+ {
+ sw = new(@".\TestNorm1.txt");
+
+ // Define three versions of the same word.
+ string s1 = "sống"; // create word with U+1ED1
+ string s2 = "s\u00F4\u0301ng";
+ string s3 = "so\u0302\u0301ng";
+
+ TestForEquality(s1, s2, s3);
+ sw.WriteLine();
- // Define three versions of the same word.
- string s1 = "sống"; // create word with U+1ED1
- string s2 = "s\u00F4\u0301ng";
- string s3 = "so\u0302\u0301ng";
+ // Normalize and compare strings using each normalization form.
+ foreach (string formName in Enum.GetNames(typeof(NormalizationForm)))
+ {
+ sw.WriteLine($"Normalization {formName}:\n");
+ NormalizationForm nf = (NormalizationForm)Enum.Parse(typeof(NormalizationForm), formName);
+ string[] sn = NormalizeStrings(nf, s1, s2, s3);
+ TestForEquality(sn);
+ sw.WriteLine("\n");
+ }
- TestForEquality(s1, s2, s3);
- sw.WriteLine();
+ sw.Close();
+ }
- // Normalize and compare strings using each normalization form.
- foreach (string formName in Enum.GetNames(typeof(NormalizationForm)))
- {
- sw.WriteLine("Normalization {0}:\n", formName);
- NormalizationForm nf = (NormalizationForm) Enum.Parse(typeof(NormalizationForm), formName);
- string[] sn = NormalizeStrings(nf, s1, s2, s3);
- TestForEquality(sn);
- sw.WriteLine("\n");
- }
-
- sw.Close();
- }
+ private static void TestForEquality(params string[] words)
+ {
+ for (int ctr = 0; ctr <= words.Length - 2; ctr++)
+ for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++)
+ sw.WriteLine($"{words[ctr]} ({ShowBytes(words[ctr])}) = {words[ctr2]} ({ShowBytes(words[ctr2])}): {words[ctr].Equals(words[ctr2], StringComparison.Ordinal)}");
+ }
- private static void TestForEquality(params string[] words)
- {
- for (int ctr = 0; ctr <= words.Length - 2; ctr++)
- for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++)
- sw.WriteLine("{0} ({1}) = {2} ({3}): {4}",
- words[ctr], ShowBytes(words[ctr]),
- words[ctr2], ShowBytes(words[ctr2]),
- words[ctr].Equals(words[ctr2], StringComparison.Ordinal));
- }
+ private static string ShowBytes(string str)
+ {
+ string result = null;
+ foreach (char ch in str)
+ result += $"{(ushort)ch:X4} ";
+ return result.Trim();
+ }
- private static string ShowBytes(string str)
- {
- string result = null;
- foreach (var ch in str)
- result += $"{(ushort)ch:X4} ";
- return result.Trim();
- }
-
- private static string[] NormalizeStrings(NormalizationForm nf, params string[] words)
- {
- for (int ctr = 0; ctr < words.Length; ctr++)
- if (!words[ctr].IsNormalized(nf))
- words[ctr] = words[ctr].Normalize(nf);
- return words;
- }
+ private static string[] NormalizeStrings(NormalizationForm nf, params string[] words)
+ {
+ for (int ctr = 0; ctr < words.Length; ctr++)
+ if (!words[ctr].IsNormalized(nf))
+ words[ctr] = words[ctr].Normalize(nf);
+ return words;
+ }
}
// The example displays the following output:
// sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
// sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
// sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
-//
+//
// Normalization FormC:
-//
+//
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
-//
-//
+//
+//
// Normalization FormD:
-//
+//
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
-//
-//
+//
+//
// Normalization FormKC:
-//
+//
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
// sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
-//
-//
+//
+//
// Normalization FormKD:
-//
+//
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
// sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
diff --git a/snippets/csharp/System/String/Overview/nullorempty1.cs b/snippets/csharp/System/String/Overview/nullorempty1.cs
index 51921237593..d4d5b07dcfb 100644
--- a/snippets/csharp/System/String/Overview/nullorempty1.cs
+++ b/snippets/csharp/System/String/Overview/nullorempty1.cs
@@ -3,78 +3,68 @@
public class Example
{
- public static void Main()
- {
- TestForIsNullOrEmpty();
- Console.WriteLine("-----");
- TestForIsNullOrEmptyOrWhitespaceOnly();
- }
+ public static void Main()
+ {
+ TestForIsNullOrEmpty();
+ Console.WriteLine("-----");
+ TestForIsNullOrEmptyOrWhitespaceOnly();
+ }
- private static void TestForIsNullOrEmpty()
- {
- string str = "";
- //
- if (str == null || str.Equals(String.Empty))
- //
- Console.WriteLine("Bad string!");
- else
- Console.WriteLine("Good string!");
- }
+ private static void TestForIsNullOrEmpty()
+ {
+ string str = "";
+ //
+ if (str == null || str.Equals(string.Empty))
+ //
+ Console.WriteLine("Bad string!");
+ else
+ Console.WriteLine("Good string!");
+ }
- private static void TestForIsNullOrEmptyOrWhitespaceOnly()
- {
- string str = null;
- //
- if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty))
- //
- Console.WriteLine("Bad string!");
- else
- Console.WriteLine("Good string!");
- }
+ private static void TestForIsNullOrEmptyOrWhitespaceOnly()
+ {
+ string str = null;
+ //
+ if (str == null || str.Equals(string.Empty) || str.Trim().Equals(string.Empty))
+ //
+ Console.WriteLine("Bad string!");
+ else
+ Console.WriteLine("Good string!");
+ }
}
-public class Temperature : IFormattable
+public class Temperature : IFormattable
{
- double temp;
-
- public Temperature(double temp)
- {
- this.temp = temp;
- }
-
- public override string ToString()
- {
- return this.ToString("G", CultureInfo.CurrentCulture);
- }
-
- public string ToString(string format)
- {
- return this.ToString(format, CultureInfo.CurrentCulture);
- }
-
- //
- public string ToString(string format, IFormatProvider provider)
- {
- if (String.IsNullOrEmpty(format)) format = "G";
- if (provider == null) provider = CultureInfo.CurrentCulture;
-
- switch (format.ToUpperInvariant())
- {
- // Return degrees in Celsius.
- case "G":
- case "C":
- return temp.ToString("F2", provider) + "°C";
- // Return degrees in Fahrenheit.
- case "F":
- return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F";
- // Return degrees in Kelvin.
- case "K":
- return (temp + 273.15).ToString();
- default:
- throw new FormatException(
- String.Format("The {0} format string is not supported.",
- format));
- }
- }
- //
-}
\ No newline at end of file
+ double temp;
+
+ public Temperature(double temp) => this.temp = temp;
+
+ public override string ToString() => this.ToString("G", CultureInfo.CurrentCulture);
+
+ public string ToString(string format) => this.ToString(format, CultureInfo.CurrentCulture);
+
+ //
+ public string ToString(string format, IFormatProvider provider)
+ {
+ if (string.IsNullOrEmpty(format)) format = "G";
+ if (provider == null) provider = CultureInfo.CurrentCulture;
+
+ switch (format.ToUpperInvariant())
+ {
+ // Return degrees in Celsius.
+ case "G":
+ case "C":
+ return temp.ToString("F2", provider) + "°C";
+ // Return degrees in Fahrenheit.
+ case "F":
+ return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F";
+ // Return degrees in Kelvin.
+ case "K":
+ return (temp + 273.15).ToString();
+ default:
+ throw new FormatException(
+ $"The {format} format string is not supported.");
+ }
+ }
+ //
+}
diff --git a/snippets/csharp/System/String/Overview/parse1.cs b/snippets/csharp/System/String/Overview/parse1.cs
index 064e1283cf7..d82cc4e413d 100644
--- a/snippets/csharp/System/String/Overview/parse1.cs
+++ b/snippets/csharp/System/String/Overview/parse1.cs
@@ -4,26 +4,24 @@
public class Example
{
- public static void Main()
- {
- string dateString = "07/10/2011";
- CultureInfo[] cultures = { CultureInfo.InvariantCulture,
- CultureInfo.CreateSpecificCulture("en-GB"),
- CultureInfo.CreateSpecificCulture("en-US") };
- Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture",
- "Month", "Day");
- foreach (var culture in cultures) {
- DateTime date = DateTime.Parse(dateString, culture);
- Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString,
- String.IsNullOrEmpty(culture.Name) ?
- "Invariant" : culture.Name,
- date.Month, date.Day);
- }
- }
+ public static void Main()
+ {
+ string dateString = "07/10/2011";
+ CultureInfo[] cultures = [CultureInfo.InvariantCulture,
+ CultureInfo.CreateSpecificCulture("en-GB"),
+ CultureInfo.CreateSpecificCulture("en-US")];
+ Console.WriteLine($"{"Date String",-12} {"Culture",10} {"Month",8} {"Day",8}\n");
+ foreach (var culture in cultures)
+ {
+ DateTime date = DateTime.Parse(dateString, culture);
+ Console.WriteLine($"{dateString,-12} {(string.IsNullOrEmpty(culture.Name) ?
+ "Invariant" : culture.Name),10} {date.Month,8} {date.Day,8}");
+ }
+ }
}
// The example displays the following output:
// Date String Culture Month Day
-//
+//
// 07/10/2011 Invariant 7 10
// 07/10/2011 en-GB 10 7
// 07/10/2011 en-US 7 10
diff --git a/snippets/csharp/System/String/Overview/program.cs b/snippets/csharp/System/String/Overview/program.cs
index 57ca343b1e4..d8339b3eda1 100644
--- a/snippets/csharp/System/String/Overview/program.cs
+++ b/snippets/csharp/System/String/Overview/program.cs
@@ -2,113 +2,113 @@
public class Example
{
- public static void Main()
- {
- InstantiateByAssignment();
- Console.WriteLine("-----");
- CallConstructors();
- Console.WriteLine("-----");
- Concatenate();
- Console.WriteLine("-----");
- ExtractString();
- Console.WriteLine("-----");
- Formatting();
- }
+ public static void Main()
+ {
+ InstantiateByAssignment();
+ Console.WriteLine("-----");
+ CallConstructors();
+ Console.WriteLine("-----");
+ Concatenate();
+ Console.WriteLine("-----");
+ ExtractString();
+ Console.WriteLine("-----");
+ Formatting();
+ }
- private static void InstantiateByAssignment()
- {
- //
- string string1 = "This is a string created by assignment.";
- Console.WriteLine(string1);
- string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
- Console.WriteLine(string2a);
- string string2b = @"The path is C:\PublicDocuments\Report1.doc";
- Console.WriteLine(string2b);
- // The example displays the following output:
- // This is a string created by assignment.
- // The path is C:\PublicDocuments\Report1.doc
- // The path is C:\PublicDocuments\Report1.doc
- //
- }
+ private static void InstantiateByAssignment()
+ {
+ //
+ string string1 = "This is a string created by assignment.";
+ Console.WriteLine(string1);
+ string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
+ Console.WriteLine(string2a);
+ string string2b = @"The path is C:\PublicDocuments\Report1.doc";
+ Console.WriteLine(string2b);
+ // The example displays the following output:
+ // This is a string created by assignment.
+ // The path is C:\PublicDocuments\Report1.doc
+ // The path is C:\PublicDocuments\Report1.doc
+ //
+ }
- private static void CallConstructors()
- {
- //
- char[] chars = { 'w', 'o', 'r', 'd' };
- sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
+ private static void CallConstructors()
+ {
+ //
+ char[] chars = ['w', 'o', 'r', 'd'];
+ sbyte[] bytes = [0x41, 0x42, 0x43, 0x44, 0x45, 0x00];
- // Create a string from a character array.
- string string1 = new string(chars);
- Console.WriteLine(string1);
+ // Create a string from a character array.
+ string string1 = new(chars);
+ Console.WriteLine(string1);
- // Create a string that consists of a character repeated 20 times.
- string string2 = new string('c', 20);
- Console.WriteLine(string2);
+ // Create a string that consists of a character repeated 20 times.
+ string string2 = new('c', 20);
+ Console.WriteLine(string2);
- string stringFromBytes = null;
- string stringFromChars = null;
- unsafe
- {
- fixed (sbyte* pbytes = bytes)
- {
- // Create a string from a pointer to a signed byte array.
- stringFromBytes = new string(pbytes);
- }
- fixed (char* pchars = chars)
- {
- // Create a string from a pointer to a character array.
- stringFromChars = new string(pchars);
- }
- }
- Console.WriteLine(stringFromBytes);
- Console.WriteLine(stringFromChars);
- // The example displays the following output:
- // word
- // cccccccccccccccccccc
- // ABCDE
- // word
- //
- }
+ string stringFromBytes = null;
+ string stringFromChars = null;
+ unsafe
+ {
+ fixed (sbyte* pbytes = bytes)
+ {
+ // Create a string from a pointer to a signed byte array.
+ stringFromBytes = new(pbytes);
+ }
+ fixed (char* pchars = chars)
+ {
+ // Create a string from a pointer to a character array.
+ stringFromChars = new(pchars);
+ }
+ }
+ Console.WriteLine(stringFromBytes);
+ Console.WriteLine(stringFromChars);
+ // The example displays the following output:
+ // word
+ // cccccccccccccccccccc
+ // ABCDE
+ // word
+ //
+ }
- private static void Concatenate()
- {
- //
- string string1 = "Today is " + DateTime.Now.ToString("D") + ".";
- Console.WriteLine(string1);
+ private static void Concatenate()
+ {
+ //
+ string string1 = $"Today is {DateTime.Now:D}.";
+ Console.WriteLine(string1);
- string string2 = "This is one sentence. " + "This is a second. ";
- string2 += "This is a third sentence.";
- Console.WriteLine(string2);
- // The example displays output like the following:
- // Today is Tuesday, July 06, 2011.
- // This is one sentence. This is a second. This is a third sentence.
- //
- }
+ string string2 = "This is one sentence. " + "This is a second. ";
+ string2 += "This is a third sentence.";
+ Console.WriteLine(string2);
+ // The example displays output like the following:
+ // Today is Tuesday, July 06, 2011.
+ // This is one sentence. This is a second. This is a third sentence.
+ //
+ }
- private static void ExtractString()
- {
- //
- string sentence = "This sentence has five words.";
- // Extract the second word.
- int startPosition = sentence.IndexOf(" ") + 1;
- string word2 = sentence.Substring(startPosition,
- sentence.IndexOf(" ", startPosition) - startPosition);
- Console.WriteLine("Second word: " + word2);
- // The example displays the following output:
- // Second word: sentence
- //
- }
+ private static void ExtractString()
+ {
+ //
+ string sentence = "This sentence has five words.";
+ // Extract the second word.
+ int startPosition = sentence.IndexOf(" ") + 1;
+ string word2 = sentence.Substring(startPosition,
+ sentence.IndexOf(" ", startPosition) - startPosition);
+ Console.WriteLine("Second word: " + word2);
+ // The example displays the following output:
+ // Second word: sentence
+ //
+ }
- private static void Formatting()
- {
- //
- DateTime dateAndTime = new DateTime(2011, 7, 6, 7, 32, 0);
- double temperature = 68.3;
- string result = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
- dateAndTime, temperature);
- Console.WriteLine(result);
- // The example displays the following output:
- // At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.
- //
- }
+ private static void Formatting()
+ {
+ //
+ DateTime dateAndTime = new(2011, 7, 6, 7, 32, 0);
+ double temperature = 68.3;
+ string result = string.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
+ dateAndTime, temperature);
+ Console.WriteLine(result);
+ // The example displays the following output:
+ // At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Overview/search1.cs b/snippets/csharp/System/String/Overview/search1.cs
index f49f123d156..12585300030 100644
--- a/snippets/csharp/System/String/Overview/search1.cs
+++ b/snippets/csharp/System/String/Overview/search1.cs
@@ -4,24 +4,23 @@
public class Example
{
- public static void Main()
- {
- String[] cultureNames = { "da-DK", "en-US" };
- CompareInfo ci;
- String str = "aerial";
- Char ch = 'æ'; // U+00E6
-
- Console.Write("Ordinal comparison -- ");
- Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
- str.IndexOf(ch));
-
- foreach (var cultureName in cultureNames) {
- ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo;
- Console.Write("{0} cultural comparison -- ", cultureName);
- Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
- ci.IndexOf(str, ch));
- }
- }
+ public static void Main()
+ {
+ string[] cultureNames = ["da-DK", "en-US"];
+ CompareInfo ci;
+ string str = "aerial";
+ char ch = 'æ'; // U+00E6
+
+ Console.Write("Ordinal comparison -- ");
+ Console.WriteLine($"Position of '{ch}' in {str}: {str.IndexOf(ch)}");
+
+ foreach (string cultureName in cultureNames)
+ {
+ ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo;
+ Console.Write($"{cultureName} cultural comparison -- ");
+ Console.WriteLine($"Position of '{ch}' in {str}: {ci.IndexOf(str, ch)}");
+ }
+ }
}
// The example displays the following output:
// Ordinal comparison -- Position of 'æ' in aerial: -1
diff --git a/snippets/csharp/System/String/Overview/sort1.cs b/snippets/csharp/System/String/Overview/sort1.cs
index d982852d438..1cd30508b14 100644
--- a/snippets/csharp/System/String/Overview/sort1.cs
+++ b/snippets/csharp/System/String/Overview/sort1.cs
@@ -1,44 +1,44 @@
//
using System;
-using System.Globalization;
+
using System.Threading;
public class ArraySort
{
- public static void Main(String[] args)
- {
- // Create and initialize a new array to store the strings.
- string[] stringArray = { "Apple", "Æble", "Zebra"};
+ public static void Main(string[] args)
+ {
+ // Create and initialize a new array to store the strings.
+ string[] stringArray = ["Apple", "Æble", "Zebra"];
- // Display the values of the array.
- Console.WriteLine( "The original string array:");
- PrintIndexAndValues(stringArray);
+ // Display the values of the array.
+ Console.WriteLine("The original string array:");
+ PrintIndexAndValues(stringArray);
- // Set the CurrentCulture to "en-US".
- Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
- // Sort the values of the array.
- Array.Sort(stringArray);
+ // Set the CurrentCulture to "en-US".
+ Thread.CurrentThread.CurrentCulture = new("en-US");
+ // Sort the values of the array.
+ Array.Sort(stringArray);
- // Display the values of the array.
- Console.WriteLine("After sorting for the culture \"en-US\":");
- PrintIndexAndValues(stringArray);
+ // Display the values of the array.
+ Console.WriteLine("After sorting for the culture \"en-US\":");
+ PrintIndexAndValues(stringArray);
- // Set the CurrentCulture to "da-DK".
- Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
- // Sort the values of the Array.
- Array.Sort(stringArray);
+ // Set the CurrentCulture to "da-DK".
+ Thread.CurrentThread.CurrentCulture = new("da-DK");
+ // Sort the values of the Array.
+ Array.Sort(stringArray);
- // Display the values of the array.
- Console.WriteLine("After sorting for the culture \"da-DK\":");
- PrintIndexAndValues(stringArray);
- }
- public static void PrintIndexAndValues(string[] myArray)
- {
- for (int i = myArray.GetLowerBound(0); i <=
- myArray.GetUpperBound(0); i++ )
- Console.WriteLine("[{0}]: {1}", i, myArray[i]);
- Console.WriteLine();
- }
+ // Display the values of the array.
+ Console.WriteLine("After sorting for the culture \"da-DK\":");
+ PrintIndexAndValues(stringArray);
+ }
+ public static void PrintIndexAndValues(string[] myArray)
+ {
+ for (int i = myArray.GetLowerBound(0); i <=
+ myArray.GetUpperBound(0); i++)
+ Console.WriteLine($"[{i}]: {myArray[i]}");
+ Console.WriteLine();
+ }
}
// The example displays the following output:
// The original string array:
@@ -55,4 +55,4 @@ public static void PrintIndexAndValues(string[] myArray)
// [0]: Apple
// [1]: Zebra
// [2]: Æble
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Overview/surrogate1.cs b/snippets/csharp/System/String/Overview/surrogate1.cs
index 923b60e8845..87d973c2774 100644
--- a/snippets/csharp/System/String/Overview/surrogate1.cs
+++ b/snippets/csharp/System/String/Overview/surrogate1.cs
@@ -2,19 +2,18 @@
public class Example
{
- public static void Main()
- {
- //
- string surrogate = "\uD800\uDC03";
- for (int ctr = 0; ctr < surrogate.Length; ctr++)
- Console.Write($"U+{(ushort)surrogate[ctr]:X2} ");
+ public static void Main()
+ {
+ //
+ string surrogate = "\uD800\uDC03";
+ for (int ctr = 0; ctr < surrogate.Length; ctr++)
+ Console.Write($"U+{(ushort)surrogate[ctr]:X2} ");
- Console.WriteLine();
- Console.WriteLine(" Is Surrogate Pair: {0}",
- Char.IsSurrogatePair(surrogate[0], surrogate[1]));
- // The example displays the following output:
- // U+D800 U+DC03
- // Is Surrogate Pair: True
- //
- }
+ Console.WriteLine();
+ Console.WriteLine($" Is Surrogate Pair: {char.IsSurrogatePair(surrogate[0], surrogate[1])}");
+ // The example displays the following output:
+ // U+D800 U+DC03
+ // Is Surrogate Pair: True
+ //
+ }
}
diff --git a/snippets/csharp/System/String/PadLeft/Program.cs b/snippets/csharp/System/String/PadLeft/Program.cs
new file mode 100644
index 00000000000..a95d98f8dd5
--- /dev/null
+++ b/snippets/csharp/System/String/PadLeft/Program.cs
@@ -0,0 +1,2 @@
+PadLeftWidthSample.Run();
+PadLeftCharacterSample.Run();
diff --git a/snippets/csharp/System/String/PadLeft/Project.csproj b/snippets/csharp/System/String/PadLeft/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/PadLeft/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/PadLeft/source.cs b/snippets/csharp/System/String/PadLeft/source.cs
index 24438db7052..f84af9ba61c 100644
--- a/snippets/csharp/System/String/PadLeft/source.cs
+++ b/snippets/csharp/System/String/PadLeft/source.cs
@@ -1,13 +1,13 @@
using System;
-public class Sample
+public class PadLeftWidthSample
{
- public static void Main()
+ public static void Run()
{
- //
- string str = "BBQ and Slaw";
- Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw".
- Console.WriteLine(str.PadLeft(5)); // Displays "BBQ and Slaw".
- //
+ //
+ string str = "BBQ and Slaw";
+ Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw".
+ Console.WriteLine(str.PadLeft(5)); // Displays "BBQ and Slaw".
+ //
}
}
diff --git a/snippets/csharp/System/String/PadLeft/source1.cs b/snippets/csharp/System/String/PadLeft/source1.cs
index ad388a1e34a..3ccd13369ad 100644
--- a/snippets/csharp/System/String/PadLeft/source1.cs
+++ b/snippets/csharp/System/String/PadLeft/source1.cs
@@ -1,16 +1,16 @@
//
using System;
-class Sample
+class PadLeftCharacterSample
{
- public static void Main()
- {
- string str = "forty-two";
- char pad = '.';
+ public static void Run()
+ {
+ string str = "forty-two";
+ char pad = '.';
- Console.WriteLine(str.PadLeft(15, pad));
- Console.WriteLine(str.PadLeft(2, pad));
- }
+ Console.WriteLine(str.PadLeft(15, pad));
+ Console.WriteLine(str.PadLeft(2, pad));
+ }
}
// The example displays the following output:
// ......forty-two
diff --git a/snippets/csharp/System/String/PadRight/Program.cs b/snippets/csharp/System/String/PadRight/Program.cs
new file mode 100644
index 00000000000..aa9fc72f2f3
--- /dev/null
+++ b/snippets/csharp/System/String/PadRight/Program.cs
@@ -0,0 +1,2 @@
+PadRightWidthSample.Run();
+PadRightCharacterSample.Run();
diff --git a/snippets/csharp/System/String/PadRight/Project.csproj b/snippets/csharp/System/String/PadRight/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/PadRight/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/PadRight/source.cs b/snippets/csharp/System/String/PadRight/source.cs
index 2af784dba15..8c69974086d 100644
--- a/snippets/csharp/System/String/PadRight/source.cs
+++ b/snippets/csharp/System/String/PadRight/source.cs
@@ -1,20 +1,20 @@
using System;
-public class Sample
+public class PadRightWidthSample
{
- public static void Main()
- {
- //
- string str;
- str = "BBQ and Slaw";
+ public static void Run()
+ {
+ //
+ string str;
+ str = "BBQ and Slaw";
- Console.Write("|");
- Console.Write(str.PadRight(15));
- Console.WriteLine("|"); // Displays "|BBQ and Slaw |".
+ Console.Write("|");
+ Console.Write(str.PadRight(15));
+ Console.WriteLine("|"); // Displays "|BBQ and Slaw |".
- Console.Write("|");
- Console.Write(str.PadRight(5));
- Console.WriteLine("|"); // Displays "|BBQ and Slaw|".
- //
- }
+ Console.Write("|");
+ Console.Write(str.PadRight(5));
+ Console.WriteLine("|"); // Displays "|BBQ and Slaw|".
+ //
+ }
}
diff --git a/snippets/csharp/System/String/PadRight/source1.cs b/snippets/csharp/System/String/PadRight/source1.cs
index 5f7e6aea9e3..39bcafdaec1 100644
--- a/snippets/csharp/System/String/PadRight/source1.cs
+++ b/snippets/csharp/System/String/PadRight/source1.cs
@@ -1,15 +1,15 @@
using System;
-public class Sample
+public class PadRightCharacterSample
{
- public static void Main()
- {
- //
- string str = "forty-two";
- char pad = '.';
+ public static void Run()
+ {
+ //
+ string str = "forty-two";
+ char pad = '.';
- Console.WriteLine(str.PadRight(15, pad)); // Displays "forty-two......".
- Console.WriteLine(str.PadRight(2, pad)); // Displays "forty-two".
- //
- }
+ Console.WriteLine(str.PadRight(15, pad)); // Displays "forty-two......".
+ Console.WriteLine(str.PadRight(2, pad)); // Displays "forty-two".
+ //
+ }
}
diff --git a/snippets/csharp/System/String/Remove/r.cs b/snippets/csharp/System/String/Remove/r.cs
index 6d369b951c0..db2a7d0f085 100644
--- a/snippets/csharp/System/String/Remove/r.cs
+++ b/snippets/csharp/System/String/Remove/r.cs
@@ -9,9 +9,9 @@ public static void Main()
string s = "abc---def";
Console.WriteLine("Index: 012345678");
- Console.WriteLine("1) {0}", s);
- Console.WriteLine("2) {0}", s.Remove(3));
- Console.WriteLine("3) {0}", s.Remove(3, 3));
+ Console.WriteLine($"1) {s}");
+ Console.WriteLine($"2) {s.Remove(3)}");
+ Console.WriteLine($"3) {s.Remove(3, 3)}");
}
}
/*
diff --git a/snippets/csharp/System/String/Remove/stringremove.cs b/snippets/csharp/System/String/Remove/stringremove.cs
index 303a5bebb35..fa953c02e32 100644
--- a/snippets/csharp/System/String/Remove/stringremove.cs
+++ b/snippets/csharp/System/String/Remove/stringremove.cs
@@ -8,7 +8,7 @@ public static void Main()
string name = "Michelle Violet Banks";
- Console.WriteLine("The entire name is '{0}'", name);
+ Console.WriteLine($"The entire name is '{name}'");
// Remove the middle name, identified by finding the spaces in the name.
int foundS1 = name.IndexOf(" ");
@@ -18,7 +18,7 @@ public static void Main()
{
name = name.Remove(foundS1 + 1, foundS2 - foundS1);
- Console.WriteLine("After removing the middle name, we are left with '{0}'", name);
+ Console.WriteLine($"After removing the middle name, we are left with '{name}'");
}
}
}
diff --git a/snippets/csharp/System/String/Split/basic.cs b/snippets/csharp/System/String/Split/basic.cs
index 351c75adca9..dc95e3c2c35 100644
--- a/snippets/csharp/System/String/Split/basic.cs
+++ b/snippets/csharp/System/String/Split/basic.cs
@@ -10,7 +10,7 @@ public static void Basic1()
string s = "Today\tI'm going to school";
string[] subs = s.Split(' ', '\t');
- foreach (var sub in subs)
+ foreach (string sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
diff --git a/snippets/csharp/System/String/Split/compiler-resolution.cs b/snippets/csharp/System/String/Split/compiler-resolution.cs
index 8f5ba87d080..2b8497c4800 100644
--- a/snippets/csharp/System/String/Split/compiler-resolution.cs
+++ b/snippets/csharp/System/String/Split/compiler-resolution.cs
@@ -10,7 +10,7 @@ public static void Main6()
string value = "This is a short string.";
char delimiter = 's';
string[] substrings = value.Split(delimiter);
- foreach (var substring in substrings)
+ foreach (string substring in substrings)
Console.WriteLine(substring);
// The example displays the following output:
diff --git a/snippets/csharp/System/String/Split/intro.cs b/snippets/csharp/System/String/Split/intro.cs
index f24bdbcfbd6..b8ad25f46b5 100644
--- a/snippets/csharp/System/String/Split/intro.cs
+++ b/snippets/csharp/System/String/Split/intro.cs
@@ -11,7 +11,7 @@ public static void Intro1()
string[] subs = s.Split(' ');
- foreach (var sub in subs)
+ foreach (string sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
@@ -34,7 +34,7 @@ public static void Intro2()
string[] subs = s.Split(' ', '.');
- foreach (var sub in subs)
+ foreach (string sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
@@ -56,11 +56,11 @@ public static void Intro3()
{
//
string s = "You win some. You lose some.";
- char[] separators = new char[] { ' ', '.' };
+ char[] separators = [' ', '.'];
string[] subs = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
- foreach (var sub in subs)
+ foreach (string sub in subs)
{
Console.WriteLine($"Substring: {sub}");
}
diff --git a/snippets/csharp/System/String/Split/limit.cs b/snippets/csharp/System/String/Split/limit.cs
index cbb0a8ad306..44327120100 100644
--- a/snippets/csharp/System/String/Split/limit.cs
+++ b/snippets/csharp/System/String/Split/limit.cs
@@ -1,4 +1,4 @@
-using System;
+
namespace Split
{
diff --git a/snippets/csharp/System/String/Split/options.cs b/snippets/csharp/System/String/Split/options.cs
index 964ef4a990b..a499088860c 100644
--- a/snippets/csharp/System/String/Split/options.cs
+++ b/snippets/csharp/System/String/Split/options.cs
@@ -14,7 +14,7 @@ public static void Main3()
Console.WriteLine("1) Split a string delimited by characters:\n");
string s1 = ",ONE,, TWO,, , THREE,,";
- char[] charSeparators = new char[] { ',' };
+ char[] charSeparators = [','];
string[] result;
Console.WriteLine($"The original string is: \"{s1}\".");
@@ -69,7 +69,7 @@ public static void Main3()
"ONE[stop] [stop]" +
"TWO [stop][stop] [stop]" +
"THREE[stop][stop] ";
- string[] stringSeparators = new string[] { "[stop]" };
+ string[] stringSeparators = ["[stop]"];
Console.WriteLine($"The original string is: \"{s2}\".");
Console.WriteLine($"The delimiter string is: \"{stringSeparators[0]}\".\n");
@@ -212,7 +212,7 @@ public static void Main4()
{
//
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
- string[] stringSeparators = new string[] { "[stop]" };
+ string[] stringSeparators = ["[stop]"];
string[] result;
// Display the original string and delimiter string.
@@ -227,7 +227,7 @@ public static void Main4()
Console.Write(" ");
foreach (string s in result)
{
- Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
+ Console.Write($"'{(string.IsNullOrEmpty(s) ? "<>" : s)}' ");
}
Console.WriteLine();
Console.WriteLine();
@@ -238,7 +238,7 @@ public static void Main4()
Console.Write(" ");
foreach (string s in result)
{
- Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
+ Console.Write($"'{(string.IsNullOrEmpty(s) ? "<>" : s)}' ");
}
Console.WriteLine();
@@ -260,10 +260,10 @@ public static void Main4()
public static void Main2()
{
//
- string[] separators = { ",", ".", "!", "?", ";", ":", " " };
+ string[] separators = [",", ".", "!", "?", ";", ":", " "];
string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate.";
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
- foreach (var word in words)
+ foreach (string word in words)
Console.WriteLine(word);
// The example displays the following output:
diff --git a/snippets/csharp/System/String/Split/program.cs b/snippets/csharp/System/String/Split/program.cs
index a2a14e1af27..1880d18d1d2 100644
--- a/snippets/csharp/System/String/Split/program.cs
+++ b/snippets/csharp/System/String/Split/program.cs
@@ -1,8 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+
+
+
+
+
namespace Split
{
diff --git a/snippets/csharp/System/String/StartsWith/Program.cs b/snippets/csharp/System/String/StartsWith/Program.cs
new file mode 100644
index 00000000000..5541cff96e7
--- /dev/null
+++ b/snippets/csharp/System/String/StartsWith/Program.cs
@@ -0,0 +1,4 @@
+StartsWithComparisonExample.Run();
+StartsWithInvariantExample.Run();
+StartsWithTagsExample.Run();
+Sample.Run();
diff --git a/snippets/csharp/System/String/StartsWith/Project.csproj b/snippets/csharp/System/String/StartsWith/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/StartsWith/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/StartsWith/StartsWith2.cs b/snippets/csharp/System/String/StartsWith/StartsWith2.cs
index 2e3379063b0..08805e435dc 100644
--- a/snippets/csharp/System/String/StartsWith/StartsWith2.cs
+++ b/snippets/csharp/System/String/StartsWith/StartsWith2.cs
@@ -1,23 +1,19 @@
//
using System;
-public class Example
+public class StartsWithInvariantExample
{
- public static void Main()
- {
- String title = "The House of the Seven Gables";
- String searchString = "the";
- StringComparison comparison = StringComparison.InvariantCulture;
- Console.WriteLine("'{0}':", title);
- Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
- searchString, comparison,
- title.StartsWith(searchString, comparison));
+ public static void Run()
+ {
+ string title = "The House of the Seven Gables";
+ string searchString = "the";
+ StringComparison comparison = StringComparison.InvariantCulture;
+ Console.WriteLine($"'{title}':");
+ Console.WriteLine($" Starts with '{searchString}' ({comparison:G} comparison): {title.StartsWith(searchString, comparison)}");
- comparison = StringComparison.InvariantCultureIgnoreCase;
- Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
- searchString, comparison,
- title.StartsWith(searchString, comparison));
- }
+ comparison = StringComparison.InvariantCultureIgnoreCase;
+ Console.WriteLine($" Starts with '{searchString}' ({comparison:G} comparison): {title.StartsWith(searchString, comparison)}");
+ }
}
// The example displays the following output:
// 'The House of the Seven Gables':
diff --git a/snippets/csharp/System/String/StartsWith/startswith1.cs b/snippets/csharp/System/String/StartsWith/startswith1.cs
index ff9556bea64..e80576269b4 100644
--- a/snippets/csharp/System/String/StartsWith/startswith1.cs
+++ b/snippets/csharp/System/String/StartsWith/startswith1.cs
@@ -1,30 +1,27 @@
//
using System;
-public class Example
+public class StartsWithComparisonExample
{
- public static void Main()
- {
- string[,] strings = { {"ABCdef", "abc" },
- {"ABCdef", "abc" },
+ public static void Run()
+ {
+ string[,] strings = { {"ABCdef", "abc" },
+ {"ABCdef", "abc" },
{"œil","oe" },
{ "læring}", "lae" } };
- for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++)
- {
+ for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++)
+ {
foreach (string cmpName in Enum.GetNames(typeof(StringComparison)))
- {
- StringComparison strCmp = (StringComparison) Enum.Parse(typeof(StringComparison),
- cmpName);
- string instance = strings[ctr1, 0];
- string value = strings[ctr1, 1];
- Console.WriteLine("{0} starts with {1}: {2} ({3} comparison)",
- instance, value,
- instance.StartsWith(value, strCmp),
- strCmp);
+ {
+ StringComparison strCmp = (StringComparison)Enum.Parse(typeof(StringComparison),
+ cmpName);
+ string instance = strings[ctr1, 0];
+ string value = strings[ctr1, 1];
+ Console.WriteLine($"{instance} starts with {value}: {instance.StartsWith(value, strCmp)} ({strCmp} comparison)");
}
- Console.WriteLine();
- }
- }
+ Console.WriteLine();
+ }
+ }
}
// The example displays the following output:
// ABCdef starts with abc: False (CurrentCulture comparison)
@@ -33,25 +30,25 @@ public static void Main()
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
-//
+//
// ABCdef starts with abc: False (CurrentCulture comparison)
// ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
// ABCdef starts with abc: False (InvariantCulture comparison)
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
-//
+//
// œil starts with oe: True (CurrentCulture comparison)
// œil starts with oe: True (CurrentCultureIgnoreCase comparison)
// œil starts with oe: True (InvariantCulture comparison)
// œil starts with oe: True (InvariantCultureIgnoreCase comparison)
// œil starts with oe: False (Ordinal comparison)
// œil starts with oe: False (OrdinalIgnoreCase comparison)
-//
+//
// læring} starts with lae: True (CurrentCulture comparison)
// læring} starts with lae: True (CurrentCultureIgnoreCase comparison)
// læring} starts with lae: True (InvariantCulture comparison)
// læring} starts with lae: True (InvariantCultureIgnoreCase comparison)
// læring} starts with lae: False (Ordinal comparison)
// læring} starts with lae: False (OrdinalIgnoreCase comparison)
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/StartsWith/stringstartswith.cs b/snippets/csharp/System/String/StartsWith/stringstartswith.cs
index 26240f86501..37c6f275cef 100644
--- a/snippets/csharp/System/String/StartsWith/stringstartswith.cs
+++ b/snippets/csharp/System/String/StartsWith/stringstartswith.cs
@@ -1,46 +1,49 @@
//
using System;
-public class Example
+public class StartsWithTagsExample
{
- public static void Main() {
- string [] strSource = { "This is bold text", "This is large Text
",
+ public static void Run()
+ {
+ string[] strSource = [ "This is bold text", "This is large Text
",
"This has multiple tags",
"This has embedded tags.",
- "" );
- // Remove the tag.
- if (lastLocation >= 0) {
- item = item.Substring( lastLocation + 1 );
+ private static string StripStartTags(string item)
+ {
+ // Determine whether a tag begins the string.
+ if (item.Trim().StartsWith("<"))
+ {
+ // Find the closing tag.
+ int lastLocation = item.IndexOf(">");
+ // Remove the tag.
+ if (lastLocation >= 0)
+ {
+ item = item.Substring(lastLocation + 1);
- // Remove any additional starting tags.
- item = StripStartTags(item);
- }
- }
+ // Remove any additional starting tags.
+ item = StripStartTags(item);
+ }
+ }
- return item;
- }
+ return item;
+ }
}
// The example displays the following output:
// The original strings:
@@ -58,4 +61,4 @@ private static string StripStartTags(string item)
// This has multiple tags
// This has embedded tags.
//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/StartsWith/swci.cs b/snippets/csharp/System/String/StartsWith/swci.cs
index a99f88de7ae..84c89bef219 100644
--- a/snippets/csharp/System/String/StartsWith/swci.cs
+++ b/snippets/csharp/System/String/StartsWith/swci.cs
@@ -1,66 +1,66 @@
//
-// This code example demonstrates the
+// This code example demonstrates the
// System.String.StartsWith(String, ..., CultureInfo) method.
using System;
-using System.Threading;
+
using System.Globalization;
-class Sample
+class Sample
{
- public static void Main()
+ public static void Run()
{
- string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
- string msg2 = "Using the {0} - \"{1}\" culture:";
- string msg3 = " The string to search ends with the target string: {0}";
- bool result = false;
- CultureInfo ci;
-
-// Define a target string to search for.
-// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
- string capitalARing = "\u00c5";
-
-// Define a string to search.
-// The result of combining the characters LATIN SMALL LETTER A and COMBINING
-// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
-// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
- string aRingXYZ = "\u0061\u030a" + "xyz";
-
-// Clear the screen and display an introduction.
- Console.Clear();
-
-// Display the string to search for and the string to search.
- Console.WriteLine(msg1, capitalARing, aRingXYZ);
-
-// Search using English-United States culture.
- ci = new CultureInfo("en-US");
- Console.WriteLine(msg2, ci.DisplayName, ci.Name);
-
- Console.WriteLine("Case sensitive:");
- result = aRingXYZ.StartsWith(capitalARing, false, ci);
- Console.WriteLine(msg3, result);
-
- Console.WriteLine("Case insensitive:");
- result = aRingXYZ.StartsWith(capitalARing, true, ci);
- Console.WriteLine(msg3, result);
- Console.WriteLine();
-
-// Search using Swedish-Sweden culture.
- ci = new CultureInfo("sv-SE");
- Console.WriteLine(msg2, ci.DisplayName, ci.Name);
-
- Console.WriteLine("Case sensitive:");
- result = aRingXYZ.StartsWith(capitalARing, false, ci);
- Console.WriteLine(msg3, result);
-
- Console.WriteLine("Case insensitive:");
- result = aRingXYZ.StartsWith(capitalARing, true, ci);
- Console.WriteLine(msg3, result);
+ string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
+ string msg2 = "Using the {0} - \"{1}\" culture:";
+ string msg3 = " The string to search ends with the target string: {0}";
+ bool result = false;
+ CultureInfo ci;
+
+ // Define a target string to search for.
+ // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
+ string capitalARing = "\u00c5";
+
+ // Define a string to search.
+ // The result of combining the characters LATIN SMALL LETTER A and COMBINING
+ // RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
+ // LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
+ string aRingXYZ = "\u0061\u030a" + "xyz";
+
+ // Clear the screen and display an introduction.
+ Console.Clear();
+
+ // Display the string to search for and the string to search.
+ Console.WriteLine(msg1, capitalARing, aRingXYZ);
+
+ // Search using English-United States culture.
+ ci = new("en-US");
+ Console.WriteLine(msg2, ci.DisplayName, ci.Name);
+
+ Console.WriteLine("Case sensitive:");
+ result = aRingXYZ.StartsWith(capitalARing, false, ci);
+ Console.WriteLine(msg3, result);
+
+ Console.WriteLine("Case insensitive:");
+ result = aRingXYZ.StartsWith(capitalARing, true, ci);
+ Console.WriteLine(msg3, result);
+ Console.WriteLine();
+
+ // Search using Swedish-Sweden culture.
+ ci = new("sv-SE");
+ Console.WriteLine(msg2, ci.DisplayName, ci.Name);
+
+ Console.WriteLine("Case sensitive:");
+ result = aRingXYZ.StartsWith(capitalARing, false, ci);
+ Console.WriteLine(msg3, result);
+
+ Console.WriteLine("Case insensitive:");
+ result = aRingXYZ.StartsWith(capitalARing, true, ci);
+ Console.WriteLine(msg3, result);
}
}
/*
-Note: This code example was executed on a console whose user interface
+Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
Search for the target string "Å" in the string "a°xyz".
@@ -78,4 +78,4 @@ Using the Swedish (Sweden) - "sv-SE" culture:
The string to search ends with the target string: False
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/Substring/Program.cs b/snippets/csharp/System/String/Substring/Program.cs
new file mode 100644
index 00000000000..19753f5314c
--- /dev/null
+++ b/snippets/csharp/System/String/Substring/Program.cs
@@ -0,0 +1,6 @@
+Sample.Run();
+SubstringPairsExample.Run();
+SubStringTest.Run();
+SubstringRangeExample.Run();
+SubstringMarkupExample.Run();
+SubstringLengthExample.Run();
diff --git a/snippets/csharp/System/String/Substring/Project.csproj b/snippets/csharp/System/String/Substring/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/Substring/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/Substring/Substring1.cs b/snippets/csharp/System/String/Substring/Substring1.cs
index 402eb41815e..fea8525f5f9 100644
--- a/snippets/csharp/System/String/Substring/Substring1.cs
+++ b/snippets/csharp/System/String/Substring/Substring1.cs
@@ -1,21 +1,19 @@
using System;
-public class Example
+public class SubstringPairsExample
{
- public static void Main()
+ public static void Run()
{
//
- String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
- "Title=Code Repository" };
- foreach (var pair in pairs)
+ string[] pairs = [ "Color1=red", "Color2=green", "Color3=blue",
+ "Title=Code Repository" ];
+ foreach (string pair in pairs)
{
int position = pair.IndexOf("=");
if (position < 0)
continue;
- Console.WriteLine("Key: {0}, Value: '{1}'",
- pair.Substring(0, position),
- pair.Substring(position + 1));
- }
+ Console.WriteLine($"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'");
+ }
// The example displays the following output:
// Key: Color1, Value: 'red'
diff --git a/snippets/csharp/System/String/Substring/Substring10.cs b/snippets/csharp/System/String/Substring/Substring10.cs
index 506c299b6a9..b842eee94ea 100644
--- a/snippets/csharp/System/String/Substring/Substring10.cs
+++ b/snippets/csharp/System/String/Substring/Substring10.cs
@@ -1,23 +1,23 @@
using System;
-public class SubStringTest
+public class SubStringTest
{
- public static void Main()
+ public static void Run()
{
//
- string [] info = { "Name: Felica Walker", "Title: Mz.",
- "Age: 47", "Location: Paris", "Gender: F"};
+ string[] info = [ "Name: Felica Walker", "Title: Mz.",
+ "Age: 47", "Location: Paris", "Gender: F"];
int found = 0;
Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
Console.WriteLine(s);
- Console.WriteLine("\nWe want to retrieve only the key information. That is:");
- foreach (string s in info)
+ Console.WriteLine("\nWe want to retrieve only the key information. That is:");
+ foreach (string s in info)
{
found = s.IndexOf(": ");
- Console.WriteLine(" {0}", s.Substring(found + 2));
+ Console.WriteLine($" {s.Substring(found + 2)}");
}
// The example displays the following output:
@@ -27,7 +27,7 @@ public static void Main()
// Age: 47
// Location: Paris
// Gender: F
- //
+ //
// We want to retrieve only the key information. That is:
// Felica Walker
// Mz.
diff --git a/snippets/csharp/System/String/Substring/Substring2.cs b/snippets/csharp/System/String/Substring/Substring2.cs
index acd79845e84..0421cf41a7a 100644
--- a/snippets/csharp/System/String/Substring/Substring2.cs
+++ b/snippets/csharp/System/String/Substring/Substring2.cs
@@ -1,18 +1,16 @@
using System;
-public class Example
+public class SubstringRangeExample
{
- public static void Main()
+ public static void Run()
{
//
- String s = "aaaaabbbcccccccdd";
- Char charRange = 'b';
+ string s = "aaaaabbbcccccccdd";
+ char charRange = 'b';
int startIndex = s.IndexOf(charRange);
int endIndex = s.LastIndexOf(charRange);
int length = endIndex - startIndex + 1;
- Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
- s, startIndex, length,
- s.Substring(startIndex, length));
+ Console.WriteLine($"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}");
// The example displays the following output:
// aaaaabbbcccccccdd.Substring(5, 3) = bbb
diff --git a/snippets/csharp/System/String/Substring/Substring3.cs b/snippets/csharp/System/String/Substring/Substring3.cs
index 416aec100d2..21c73e29168 100644
--- a/snippets/csharp/System/String/Substring/Substring3.cs
+++ b/snippets/csharp/System/String/Substring/Substring3.cs
@@ -1,18 +1,18 @@
using System;
-public class Example
+public class SubstringMarkupExample
{
- public static void Main()
+ public static void Run()
{
//
- String s = "extantstill in existence";
- String searchString = "";
+ string s = "extantstill in existence";
+ string searchString = "";
int startIndex = s.IndexOf(searchString);
searchString = "" + searchString.Substring(1);
int endIndex = s.IndexOf(searchString);
- String substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex);
- Console.WriteLine("Original string: {0}", s);
- Console.WriteLine("Substring; {0}", substring);
+ string substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex);
+ Console.WriteLine($"Original string: {s}");
+ Console.WriteLine($"Substring; {substring}");
// The example displays the following output:
// Original string: extantstill in existence
diff --git a/snippets/csharp/System/String/Substring/Substring4.cs b/snippets/csharp/System/String/Substring/Substring4.cs
index 2e53ac13007..9ab1084956c 100644
--- a/snippets/csharp/System/String/Substring/Substring4.cs
+++ b/snippets/csharp/System/String/Substring/Substring4.cs
@@ -1,14 +1,14 @@
using System;
-public class Example
+public class SubstringLengthExample
{
- public static void Main()
+ public static void Run()
{
//
- String value = "This is a string.";
+ string value = "This is a string.";
int startIndex = 5;
int length = 2;
- String substring = value.Substring(startIndex, length);
+ string substring = value.Substring(startIndex, length);
Console.WriteLine(substring);
// The example displays the following output:
diff --git a/snippets/csharp/System/String/Substring/source.cs b/snippets/csharp/System/String/Substring/source.cs
index 9d0c99d6bd4..704c7b40266 100644
--- a/snippets/csharp/System/String/Substring/source.cs
+++ b/snippets/csharp/System/String/Substring/source.cs
@@ -1,30 +1,30 @@
-using System;
+using System;
public class Sample
{
- public static void Main()
- {
- //
- string myString = "abc";
- bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.
- Console.WriteLine(test1);
- bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true.
- Console.WriteLine(test2);
- try
- {
- string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
- Console.WriteLine(str3);
- }
- catch (ArgumentOutOfRangeException e)
- {
- Console.WriteLine(e.Message);
- }
+ public static void Run()
+ {
+ //
+ string myString = "abc";
+ bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.
+ Console.WriteLine(test1);
+ bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true.
+ Console.WriteLine(test2);
+ try
+ {
+ string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
+ Console.WriteLine(str3);
+ }
+ catch (ArgumentOutOfRangeException e)
+ {
+ Console.WriteLine(e.Message);
+ }
- // The example displays the following output:
- // True
- // True
- // Index and length must refer to a location within the string.
- // Parameter name: length
- //
- }
+ // The example displays the following output:
+ // True
+ // True
+ // Index and length must refer to a location within the string.
+ // Parameter name: length
+ //
+ }
}
diff --git a/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs b/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs
index eaa4a9ac086..1889b89b6fc 100644
--- a/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs
+++ b/snippets/csharp/System/String/ToCharArray/ToCharArray1.cs
@@ -3,17 +3,17 @@
public class Example
{
- public static void Main()
- {
- string s = "AaBbCcDd";
- char[] chars = s.ToCharArray();
- Console.WriteLine("Original string: {0}", s);
- Console.WriteLine("Character array:");
- for (int ctr = 0; ctr < chars.Length; ctr++)
- {
- Console.WriteLine(" {0}: {1}", ctr, chars[ctr]);
- }
- }
+ public static void Main()
+ {
+ string s = "AaBbCcDd";
+ char[] chars = s.ToCharArray();
+ Console.WriteLine($"Original string: {s}");
+ Console.WriteLine("Character array:");
+ for (int ctr = 0; ctr < chars.Length; ctr++)
+ {
+ Console.WriteLine($" {ctr}: {chars[ctr]}");
+ }
+ }
}
// The example displays the following output:
diff --git a/snippets/csharp/System/String/ToCharArray/tocharry1.cs b/snippets/csharp/System/String/ToCharArray/tocharry1.cs
index f35b6d2385c..eeb7f76b7ee 100644
--- a/snippets/csharp/System/String/ToCharArray/tocharry1.cs
+++ b/snippets/csharp/System/String/ToCharArray/tocharry1.cs
@@ -2,18 +2,20 @@
// Sample for String.ToCharArray(Int32, Int32)
using System;
-class Sample {
- public static void Main() {
- string str = "012wxyz789";
- char[] arr;
+class Sample
+{
+ public static void Main()
+ {
+ string str = "012wxyz789";
+ char[] arr;
- arr = str.ToCharArray(3, 4);
- Console.Write("The letters in '{0}' are: '", str);
- Console.Write(arr);
- Console.WriteLine("'");
- Console.WriteLine("Each letter in '{0}' is:", str);
- foreach (char c in arr)
- Console.WriteLine(c);
+ arr = str.ToCharArray(3, 4);
+ Console.Write($"The letters in '{str}' are: '");
+ Console.Write(arr);
+ Console.WriteLine("'");
+ Console.WriteLine($"Each letter in '{str}' is:");
+ foreach (char c in arr)
+ Console.WriteLine(c);
}
}
/*
@@ -25,4 +27,4 @@ public static void Main() {
y
z
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/ToLower/stringtolower.cs b/snippets/csharp/System/String/ToLower/stringtolower.cs
index 29ef7208e9d..2adee0fd49c 100644
--- a/snippets/csharp/System/String/ToLower/stringtolower.cs
+++ b/snippets/csharp/System/String/ToLower/stringtolower.cs
@@ -1,21 +1,23 @@
//
using System;
-public class ToLowerTest {
- public static void Main() {
+public class ToLowerTest
+{
+ public static void Main()
+ {
- string [] info = {"Name", "Title", "Age", "Location", "Gender"};
+ string[] info = ["Name", "Title", "Age", "Location", "Gender"];
Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
Console.WriteLine(s);
- Console.WriteLine("{0}The lowercase of these values is:", Environment.NewLine);
+ Console.WriteLine($"{Environment.NewLine}The lowercase of these values is:");
foreach (string s in info)
Console.WriteLine(s.ToLower());
- Console.WriteLine("{0}The uppercase of these values is:", Environment.NewLine);
+ Console.WriteLine($"{Environment.NewLine}The uppercase of these values is:");
foreach (string s in info)
Console.WriteLine(s.ToUpper());
diff --git a/snippets/csharp/System/String/ToLower/tolower.cs b/snippets/csharp/System/String/ToLower/tolower.cs
index bbb29b0fb76..4c08e859d75 100644
--- a/snippets/csharp/System/String/ToLower/tolower.cs
+++ b/snippets/csharp/System/String/ToLower/tolower.cs
@@ -8,43 +8,41 @@ class Sample
{
public static void Main()
{
- String str1 = "INDIGO";
- // str2 = str1, except each 'I' is '\u0130' (Unicode LATIN CAPITAL I WITH DOT ABOVE).
- String str2 = new String(new Char[] {'\u0130', 'N', 'D', '\u0130', 'G', 'O'});
- String str3, str4;
-
- Console.WriteLine();
- Console.WriteLine("str1 = '{0}'", str1);
-
- Console.WriteLine();
- Console.WriteLine("str1 is {0} to str2.",
- ((0 == String.CompareOrdinal(str1, str2)) ? "equal" : "not equal"));
- CodePoints("str1", str1);
- CodePoints("str2", str2);
-
- Console.WriteLine();
- // str3 is a lower case copy of str2, using English-United States culture.
- Console.WriteLine("str3 = Lower case copy of str2 using English-United States culture.");
- str3 = str2.ToLower(new CultureInfo("en-US", false));
-
- // str4 is a lower case copy of str2, using Turkish-Turkey culture.
- Console.WriteLine("str4 = Lower case copy of str2 using Turkish-Turkey culture.");
- str4 = str2.ToLower(new CultureInfo("tr-TR", false));
-
- // Compare the code points in str3 and str4.
- Console.WriteLine();
- Console.WriteLine("str3 is {0} to str4.",
- ((0 == String.CompareOrdinal(str3, str4)) ? "equal" : "not equal"));
- CodePoints("str3", str3);
- CodePoints("str4", str4);
+ string str1 = "INDIGO";
+ // str2 = str1, except each 'I' is '\u0130' (Unicode LATIN CAPITAL I WITH DOT ABOVE).
+ string str2 = new(['\u0130', 'N', 'D', '\u0130', 'G', 'O']);
+ string str3, str4;
+
+ Console.WriteLine();
+ Console.WriteLine($"str1 = '{str1}'");
+
+ Console.WriteLine();
+ Console.WriteLine($"str1 is {((0 == string.CompareOrdinal(str1, str2)) ? "equal" : "not equal")} to str2.");
+ CodePoints("str1", str1);
+ CodePoints("str2", str2);
+
+ Console.WriteLine();
+ // str3 is a lower case copy of str2, using English-United States culture.
+ Console.WriteLine("str3 = Lower case copy of str2 using English-United States culture.");
+ str3 = str2.ToLower(new CultureInfo("en-US", false));
+
+ // str4 is a lower case copy of str2, using Turkish-Turkey culture.
+ Console.WriteLine("str4 = Lower case copy of str2 using Turkish-Turkey culture.");
+ str4 = str2.ToLower(new CultureInfo("tr-TR", false));
+
+ // Compare the code points in str3 and str4.
+ Console.WriteLine();
+ Console.WriteLine($"str3 is {((0 == string.CompareOrdinal(str3, str4)) ? "equal" : "not equal")} to str4.");
+ CodePoints("str3", str3);
+ CodePoints("str4", str4);
}
- public static void CodePoints(String title, String s)
+ public static void CodePoints(string title, string s)
{
- Console.Write("{0}The code points in {1} are: {0}", Environment.NewLine, title);
- foreach (ushort u in s)
- Console.Write("{0:x4} ", u);
- Console.WriteLine();
+ Console.Write("{0}The code points in {1} are: {0}", Environment.NewLine, title);
+ foreach (ushort u in s)
+ Console.Write($"{u:x4} ");
+ Console.WriteLine();
}
}
/*
@@ -71,4 +69,4 @@ 0069 006e 0064 0069 0067 006f
The code points in str4 are:
0069 006e 0064 0069 0067 006f
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs b/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs
index 6ecbc70c5dc..17689075c97 100644
--- a/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs
+++ b/snippets/csharp/System/String/ToLowerInvariant/tolowerinvariant.cs
@@ -3,28 +3,28 @@
public class Example
{
- public static void Main()
- {
- string[] words = { "Tuesday", "Salı", "Вторник", "Mardi",
- "Τρίτη", "Martes", "יום שלישי",
- "الثلاثاء", "วันอังคาร" };
- // Display array in unsorted order.
- foreach (string word in words)
- Console.WriteLine(word);
- Console.WriteLine();
+ public static void Main()
+ {
+ string[] words = [ "Tuesday", "Salı", "Вторник", "Mardi",
+ "Τρίτη", "Martes", "יום שלישי",
+ "الثلاثاء", "วันอังคาร" ];
+ // Display array in unsorted order.
+ foreach (string word in words)
+ Console.WriteLine(word);
+ Console.WriteLine();
- // Create parallel array of words by calling ToLowerInvariant.
- string[] lowerWords = new string[words.Length];
- for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++)
- lowerWords[ctr] = words[ctr].ToLowerInvariant();
-
- // Sort the words array based on the order of lowerWords.
- Array.Sort(lowerWords, words, StringComparer.InvariantCulture);
-
- // Display the sorted array.
- foreach (string word in words)
- Console.WriteLine(word);
- }
+ // Create parallel array of words by calling ToLowerInvariant.
+ string[] lowerWords = new string[words.Length];
+ for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++)
+ lowerWords[ctr] = words[ctr].ToLowerInvariant();
+
+ // Sort the words array based on the order of lowerWords.
+ Array.Sort(lowerWords, words, StringComparer.InvariantCulture);
+
+ // Display the sorted array.
+ foreach (string word in words)
+ Console.WriteLine(word);
+ }
}
// The example displays the following output:
// Tuesday
@@ -36,7 +36,7 @@ public static void Main()
// יום שלישי
// الثلاثاء
// วันอังคาร
-//
+//
// Mardi
// Martes
// Salı
diff --git a/snippets/csharp/System/String/ToString/string.tostring.cs b/snippets/csharp/System/String/ToString/string.tostring.cs
index b5a903fb20d..e8776a2d65f 100644
--- a/snippets/csharp/System/String/ToString/string.tostring.cs
+++ b/snippets/csharp/System/String/ToString/string.tostring.cs
@@ -1,19 +1,21 @@
//
using System;
-class stringToString {
- public static void Main() {
- String str1 = "123";
- String str2 = "abc";
+class stringToString
+{
+ public static void Main()
+ {
+ string str1 = "123";
+ string str2 = "abc";
- Console.WriteLine("Original str1: {0}", str1);
- Console.WriteLine("Original str2: {0}", str2);
- Console.WriteLine("str1 same as str2?: {0}", Object.ReferenceEquals(str1, str2));
+ Console.WriteLine($"Original str1: {str1}");
+ Console.WriteLine($"Original str2: {str2}");
+ Console.WriteLine($"str1 same as str2?: {object.ReferenceEquals(str1, str2)}");
- str2 = str1.ToString();
- Console.WriteLine();
- Console.WriteLine("New str2: {0}", str2);
- Console.WriteLine("str1 same as str2?: {0}", Object.ReferenceEquals(str1, str2));
+ str2 = str1.ToString();
+ Console.WriteLine();
+ Console.WriteLine($"New str2: {str2}");
+ Console.WriteLine($"str1 same as str2?: {object.ReferenceEquals(str1, str2)}");
}
}
/*
@@ -25,4 +27,4 @@ public static void Main() {
New str2: 123
str1 same as str2?: True
*/
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System/String/ToUpper/Program.cs b/snippets/csharp/System/String/ToUpper/Program.cs
new file mode 100644
index 00000000000..a41aa44bd7f
--- /dev/null
+++ b/snippets/csharp/System/String/ToUpper/Program.cs
@@ -0,0 +1,2 @@
+ToUpperCultureExample.Run();
+ToUpperRangeExample.Run();
diff --git a/snippets/csharp/System/String/ToUpper/Project.csproj b/snippets/csharp/System/String/ToUpper/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/ToUpper/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/ToUpper/ToUpperEx.cs b/snippets/csharp/System/String/ToUpper/ToUpperEx.cs
index cf55d2f9448..9579fc4a815 100644
--- a/snippets/csharp/System/String/ToUpper/ToUpperEx.cs
+++ b/snippets/csharp/System/String/ToUpper/ToUpperEx.cs
@@ -1,25 +1,23 @@
//
using System;
-public class Example
+public class ToUpperRangeExample
{
- public static void Main()
- {
- int n = 0;
- for (int ctr = 0x20; ctr <= 0x017F; ctr++) {
- string string1 = ((char)ctr).ToString();
- string upperString = string1.ToUpper();
- if (string1 != upperString) {
- Console.Write(@"{0} (\u+{1}) --> {2} (\u+{3}) ",
- string1,
- Convert.ToUInt16(string1[0]).ToString("X4"),
- upperString,
- Convert.ToUInt16(upperString[0]).ToString("X4"));
- n++;
- if (n % 2 == 0) Console.WriteLine();
- }
- }
- }
+ public static void Run()
+ {
+ int n = 0;
+ for (int ctr = 0x20; ctr <= 0x017F; ctr++)
+ {
+ string string1 = ((char)ctr).ToString();
+ string upperString = string1.ToUpper();
+ if (string1 != upperString)
+ {
+ Console.Write($"{string1} (\\u+{Convert.ToUInt16(string1[0]):X4}) --> {upperString} (\\u+{Convert.ToUInt16(upperString[0]):X4}) ");
+ n++;
+ if (n % 2 == 0) Console.WriteLine();
+ }
+ }
+ }
}
// The example displays the following output:
// a (\u+0061) --> A (\u+0041) b (\u+0062) --> B (\u+0042)
diff --git a/snippets/csharp/System/String/ToUpper/toupper.cs b/snippets/csharp/System/String/ToUpper/toupper.cs
index 1e92fd80243..bd17eb38918 100644
--- a/snippets/csharp/System/String/ToUpper/toupper.cs
+++ b/snippets/csharp/System/String/ToUpper/toupper.cs
@@ -2,33 +2,32 @@
using System;
using System.Globalization;
-class Example
+class ToUpperCultureExample
{
- public static void Main()
+ public static void Run()
{
- string str1 = "indigo";
- string str2, str3;
+ string str1 = "indigo";
+ string str2, str3;
- // str2 is an uppercase copy of str1, using English-United States culture.
- str2 = str1.ToUpper(new CultureInfo("en-US", false));
+ // str2 is an uppercase copy of str1, using English-United States culture.
+ str2 = str1.ToUpper(new CultureInfo("en-US", false));
- // str3 is an uppercase copy of str1, using Turkish-Turkey culture.
- str3 = str1.ToUpper(new CultureInfo("tr-TR", false));
+ // str3 is an uppercase copy of str1, using Turkish-Turkey culture.
+ str3 = str1.ToUpper(new CultureInfo("tr-TR", false));
- // Compare the code points and compare the uppercase strings.
- ShowCodePoints("str1", str1);
- ShowCodePoints("str2", str2);
- ShowCodePoints("str3", str3);
- Console.WriteLine("str2 is {0} to str3.",
- String.CompareOrdinal(str2, str3) == 0 ? "equal" : "not equal");
+ // Compare the code points and compare the uppercase strings.
+ ShowCodePoints("str1", str1);
+ ShowCodePoints("str2", str2);
+ ShowCodePoints("str3", str3);
+ Console.WriteLine($"str2 is {(string.CompareOrdinal(str2, str3) == 0 ? "equal" : "not equal")} to str3.");
}
public static void ShowCodePoints(string varName, string s)
{
- Console.Write("{0} = {1}: ", varName, s);
- foreach (ushort u in s)
- Console.Write("{0:x4} ", u);
- Console.WriteLine();
+ Console.Write($"{varName} = {s}: ");
+ foreach (ushort u in s)
+ Console.Write($"{u:x4} ");
+ Console.WriteLine();
}
}
// This example displays the following output:
diff --git a/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs b/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs
index 9dce95d3ae0..e7257e08f70 100644
--- a/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs
+++ b/snippets/csharp/System/String/ToUpperInvariant/toupperinvariant.cs
@@ -4,33 +4,33 @@
public class Example
{
- public static void Main()
- {
- string[] words = { "Tuesday", "Salı", "Вторник", "Mardi",
- "Τρίτη", "Martes", "יום שלישי",
- "الثلاثاء", "วันอังคาร" };
- StreamWriter sw = new StreamWriter(@".\output.txt");
-
- // Display array in unsorted order.
- foreach (string word in words)
- sw.WriteLine(word);
+ public static void Main()
+ {
+ string[] words = [ "Tuesday", "Salı", "Вторник", "Mardi",
+ "Τρίτη", "Martes", "יום שלישי",
+ "الثلاثاء", "วันอังคาร" ];
+ StreamWriter sw = new(@".\output.txt");
- sw.WriteLine();
+ // Display array in unsorted order.
+ foreach (string word in words)
+ sw.WriteLine(word);
- // Create parallel array of words by calling ToUpperInvariant.
- string[] upperWords = new string[words.Length];
- for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++)
- upperWords[ctr] = words[ctr].ToUpperInvariant();
-
- // Sort the words array based on the order of upperWords.
- Array.Sort(upperWords, words, StringComparer.InvariantCulture);
-
- // Display the sorted array.
- foreach (string word in words)
- sw.WriteLine(word);
+ sw.WriteLine();
- sw.Close();
- }
+ // Create parallel array of words by calling ToUpperInvariant.
+ string[] upperWords = new string[words.Length];
+ for (int ctr = words.GetLowerBound(0); ctr <= words.GetUpperBound(0); ctr++)
+ upperWords[ctr] = words[ctr].ToUpperInvariant();
+
+ // Sort the words array based on the order of upperWords.
+ Array.Sort(upperWords, words, StringComparer.InvariantCulture);
+
+ // Display the sorted array.
+ foreach (string word in words)
+ sw.WriteLine(word);
+
+ sw.Close();
+ }
}
// The example produces the following output:
// Tuesday
@@ -42,7 +42,7 @@ public static void Main()
// יום שלישי
// الثلاثاء
// วันอังคาร
-//
+//
// Mardi
// Martes
// Salı
diff --git a/snippets/csharp/System/String/Trim/Program.cs b/snippets/csharp/System/String/Trim/Program.cs
new file mode 100644
index 00000000000..66a3b1a9e9b
--- /dev/null
+++ b/snippets/csharp/System/String/Trim/Program.cs
@@ -0,0 +1,2 @@
+TrimCharactersExample.Run();
+TrimWhitespaceExample.Run();
diff --git a/snippets/csharp/System/String/Trim/Project.csproj b/snippets/csharp/System/String/Trim/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/Trim/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/Trim/Trim1.cs b/snippets/csharp/System/String/Trim/Trim1.cs
index 26691f7a314..9d426873d8b 100644
--- a/snippets/csharp/System/String/Trim/Trim1.cs
+++ b/snippets/csharp/System/String/Trim/Trim1.cs
@@ -1,14 +1,14 @@
using System;
-public class Example
+public class TrimCharactersExample
{
- public static void Main()
+ public static void Run()
{
//
- char[] charsToTrim = { '*', ' ', '\''};
+ char[] charsToTrim = ['*', ' ', '\''];
string banner = "*** Much Ado About Nothing ***";
string result = banner.Trim(charsToTrim);
- Console.WriteLine("Trimmed\n {0}\nto\n '{1}'", banner, result);
+ Console.WriteLine($"Trimmed\n {banner}\nto\n '{result}'");
// The example displays the following output:
// Trimmed
diff --git a/snippets/csharp/System/String/Trim/Trim2.cs b/snippets/csharp/System/String/Trim/Trim2.cs
index 0bdc80fa401..71c9db9e2a5 100644
--- a/snippets/csharp/System/String/Trim/Trim2.cs
+++ b/snippets/csharp/System/String/Trim/Trim2.cs
@@ -1,24 +1,23 @@
//
using System;
-public class Example
+public class TrimWhitespaceExample
{
- public static void Main()
+ public static void Run()
{
Console.Write("Enter your first name: ");
string firstName = Console.ReadLine();
-
+
Console.Write("Enter your middle name or initial: ");
string middleName = Console.ReadLine();
-
+
Console.Write("Enter your last name: ");
string lastName = Console.ReadLine();
-
+
Console.WriteLine();
- Console.WriteLine("You entered '{0}', '{1}', and '{2}'.",
- firstName, middleName, lastName);
-
- string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " +
+ Console.WriteLine($"You entered '{firstName}', '{middleName}', and '{lastName}'.");
+
+ string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " +
lastName.Trim()).Trim();
Console.WriteLine("The result is " + name + ".");
@@ -26,7 +25,7 @@ public static void Main()
// Enter your first name: John
// Enter your middle name or initial:
// Enter your last name: Doe
- //
+ //
// You entered ' John ', '', and ' Doe'.
// The result is John Doe.
}
diff --git a/snippets/csharp/System/String/TrimEnd/sample.cs b/snippets/csharp/System/String/TrimEnd/sample.cs
index b2afd221a1d..cb6f273dfd9 100644
--- a/snippets/csharp/System/String/TrimEnd/sample.cs
+++ b/snippets/csharp/System/String/TrimEnd/sample.cs
@@ -10,14 +10,14 @@ public static void Main()
// Create a string that will be trimmed.
string path = "c:/temp//";
- // Create an array of characters
+ // Create an array of characters
// that represent characters to trim.
- char[] charsToTrim = {'/'};
+ char[] charsToTrim = ['/'];
// Thim the string.
string trimmedPath = path.TrimEnd(charsToTrim);
- Console.WriteLine("The trimmed value is: {0}.", trimmedPath);
+ Console.WriteLine($"The trimmed value is: {trimmedPath}.");
// Create a string that will be trimmed.
string pathWhitespace = "c:/temp/ ";
@@ -25,7 +25,7 @@ public static void Main()
// Trim white spaces by passing null.
string trimmedWhiteSpace = pathWhitespace.TrimEnd(null);
- Console.WriteLine("The trimmed value is: {0}.", trimmedWhiteSpace);
+ Console.WriteLine($"The trimmed value is: {trimmedWhiteSpace}.");
// This code example displays the following
// to the console:
diff --git a/snippets/csharp/System/String/TrimEnd/sample2.cs b/snippets/csharp/System/String/TrimEnd/sample2.cs
index 5633c27b470..b8a12116816 100644
--- a/snippets/csharp/System/String/TrimEnd/sample2.cs
+++ b/snippets/csharp/System/String/TrimEnd/sample2.cs
@@ -2,26 +2,26 @@
public class TrimEnd
{
- public static void Main()
- {
- //
- string sentence = "The dog had a bone, a ball, and other toys.";
- char[] charsToTrim = {',', '.', ' '};
- string[] words = sentence.Split();
- foreach (string word in words)
- Console.WriteLine(word.TrimEnd(charsToTrim));
+ public static void Main()
+ {
+ //
+ string sentence = "The dog had a bone, a ball, and other toys.";
+ char[] charsToTrim = [',', '.', ' '];
+ string[] words = sentence.Split();
+ foreach (string word in words)
+ Console.WriteLine(word.TrimEnd(charsToTrim));
- // The example displays the following output:
- // The
- // dog
- // had
- // a
- // bone
- // a
- // ball
- // and
- // other
- // toys
- //
- }
+ // The example displays the following output:
+ // The
+ // dog
+ // had
+ // a
+ // bone
+ // a
+ // ball
+ // and
+ // other
+ // toys
+ //
+ }
}
diff --git a/snippets/csharp/System/String/TrimStart/Program.cs b/snippets/csharp/System/String/TrimStart/Program.cs
new file mode 100644
index 00000000000..ec639d3a19d
--- /dev/null
+++ b/snippets/csharp/System/String/TrimStart/Program.cs
@@ -0,0 +1,2 @@
+TrimExample.Run();
+TrimExample.Run(args);
diff --git a/snippets/csharp/System/String/TrimStart/Project.csproj b/snippets/csharp/System/String/TrimStart/Project.csproj
new file mode 100644
index 00000000000..a15a29bf12c
--- /dev/null
+++ b/snippets/csharp/System/String/TrimStart/Project.csproj
@@ -0,0 +1,8 @@
+
+
+
+ Exe
+ net10.0
+
+
+
diff --git a/snippets/csharp/System/String/TrimStart/sample.cs b/snippets/csharp/System/String/TrimStart/sample.cs
index a6ad6c030c5..77e49547fef 100644
--- a/snippets/csharp/System/String/TrimStart/sample.cs
+++ b/snippets/csharp/System/String/TrimStart/sample.cs
@@ -4,9 +4,9 @@
public class TrimExample
{
//
- public static void Main()
+ public static void Run()
{
- string[] lines = {"using System;",
+ string[] lines = ["using System;",
"",
"public class HelloWorld",
"{",
@@ -16,20 +16,20 @@ public static void Main()
" // to the console.",
" Console.WriteLine(\"Hello, World.\");",
" }",
- "}"};
+ "}"];
Console.WriteLine("Before call to StripComments:");
foreach (string line in lines)
- Console.WriteLine(" {0}", line);
+ Console.WriteLine($" {line}");
string[] strippedLines = StripComments(lines);
Console.WriteLine("After call to StripComments:");
foreach (string line in strippedLines)
- Console.WriteLine(" {0}", line);
+ Console.WriteLine($" {line}");
}
// This code produces the following output to the console:
// Before call to StripComments:
// using System;
- //
+ //
// public class HelloWorld
// {
// public static void Main()
@@ -38,7 +38,7 @@ public static void Main()
// // to the console.
// Console.WriteLine("Hello, World.");
// }
- // }
+ // }
// After call to StripComments:
// This code displays a simple greeting
// to the console.
@@ -47,17 +47,17 @@ public static void Main()
//
public static string[] StripComments(string[] lines)
{
- List lineList = new List();
+ List lineList = new();
foreach (string line in lines)
{
if (line.TrimStart(' ').StartsWith("//"))
lineList.Add(line.TrimStart(' ', '/'));
}
- return lineList.ToArray();
+ return [.. lineList];
}
//
- public static void Main(string[] args)
+ public static void Run(string[] args)
{
//
// TrimStart examples
@@ -68,9 +68,9 @@ public static void Main(string[] args)
string lineAfterTrimStart = string.Empty;
// Make it easy to print out and work with all of the examples
- string[] lines = { lineWithLeadingSpaces, lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters };
+ string[] lines = [lineWithLeadingSpaces, lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters];
- foreach (var line in lines)
+ foreach (string line in lines)
{
Console.WriteLine($"This line has leading characters: {line}");
}
@@ -83,19 +83,19 @@ public static void Main(string[] args)
// A basic demonstration of TrimStart in action
lineAfterTrimStart = lineWithLeadingSpaces.TrimStart(' ');
Console.WriteLine($"This is the result after calling TrimStart: {lineAfterTrimStart}");
- // This is the result after calling TrimStart: Hello World!
+ // This is the result after calling TrimStart: Hello World!
// Since TrimStart accepts a character array of leading items to be removed as an argument,
- // it's possible to do things like trim multiple pieces of data that each have different
+ // it's possible to do things like trim multiple pieces of data that each have different
// leading characters,
- foreach (var lineToEdit in lines)
+ foreach (string lineToEdit in lines)
{
Console.WriteLine(lineToEdit.TrimStart(' ', '$', '_', 'x'));
}
// Result for each: Hello World!
- // or handle pieces of data that have multiple kinds of leading characters
- var lineToBeTrimmed = "__###__ John Smith";
+ // or handle pieces of data that have multiple kinds of leading characters
+ string lineToBeTrimmed = "__###__ John Smith";
lineAfterTrimStart = lineToBeTrimmed.TrimStart('_', '#', ' ');
Console.WriteLine(lineAfterTrimStart);
// Result: John Smith
diff --git a/snippets/csharp/System/String/op_Equality/equalityop.cs b/snippets/csharp/System/String/op_Equality/equalityop.cs
index 774547302c4..7eb30304a97 100644
--- a/snippets/csharp/System/String/op_Equality/equalityop.cs
+++ b/snippets/csharp/System/String/op_Equality/equalityop.cs
@@ -2,31 +2,29 @@
// Example for the String Equality operator.
using System;
-class EqualityOp
+class EqualityOp
{
- public static void Main()
+ public static void Main()
{
- Console.WriteLine(
+ Console.WriteLine(
"This example of the String Equality operator\n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
- CompareAndDisplay( "ijkl" );
- CompareAndDisplay( "ABCD" );
- CompareAndDisplay( "abcd" );
+ CompareAndDisplay("ijkl");
+ CompareAndDisplay("ABCD");
+ CompareAndDisplay("abcd");
}
- static void CompareAndDisplay( string Comparand )
+ static void CompareAndDisplay(string Comparand)
{
- String Lower = "abcd";
+ string Lower = "abcd";
- Console.WriteLine(
- "\"{0}\" == \"{1}\" ? {2}",
- Lower, Comparand, Lower == Comparand );
+ Console.WriteLine($"\"{Lower}\" == \"{Comparand}\" ? {Lower == Comparand}");
}
}
/*
-This example of the String Equality operator
+This example of the String Equality operator
generates the following output.
"abcd" == "ijkl" ? False
diff --git a/snippets/csharp/System/String/op_Inequality/inequalityop.cs b/snippets/csharp/System/String/op_Inequality/inequalityop.cs
index af9df24bc50..41f5fd78572 100644
--- a/snippets/csharp/System/String/op_Inequality/inequalityop.cs
+++ b/snippets/csharp/System/String/op_Inequality/inequalityop.cs
@@ -2,26 +2,24 @@
// Example for the String Inequality operator.
using System;
-class InequalityOp
+class InequalityOp
{
- public static void Main()
+ public static void Main()
{
- Console.WriteLine(
+ Console.WriteLine(
"This example of the String Inequality operator\n" +
- "generates the following output.\n" );
+ "generates the following output.\n");
- CompareAndDisplay( "ijkl" );
- CompareAndDisplay( "ABCD" );
- CompareAndDisplay( "abcd" );
+ CompareAndDisplay("ijkl");
+ CompareAndDisplay("ABCD");
+ CompareAndDisplay("abcd");
}
- static void CompareAndDisplay( String Comparand )
+ static void CompareAndDisplay(string Comparand)
{
- String Lower = "abcd";
+ string Lower = "abcd";
- Console.WriteLine(
- "\"{0}\" != \"{1}\" ? {2}",
- Lower, Comparand, Lower != Comparand );
+ Console.WriteLine($"\"{Lower}\" != \"{Comparand}\" ? {Lower != Comparand}");
}
}
diff --git a/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs b/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs
index 3bfc91e491d..d740f2bb442 100644
--- a/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs
+++ b/snippets/csharp/System/StringComparer/CurrentCulture/CompareObjects.cs
@@ -2,33 +2,33 @@
public class StringComparerTest
{
- public static void Main()
- {
- StringComparerTest test = new StringComparerTest();
- test.CompareCurrentCultureStringComparer();
- test.CompareCurrentCultureInsensitiveStringComparer();
- }
+ public static void Main()
+ {
+ StringComparerTest test = new();
+ test.CompareCurrentCultureStringComparer();
+ test.CompareCurrentCultureInsensitiveStringComparer();
+ }
- //
- private void CompareCurrentCultureStringComparer()
- {
- StringComparer stringComparer1 = StringComparer.CurrentCulture;
- StringComparer stringComparer2 = StringComparer.CurrentCulture;
- // Displays false
- Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1,
- stringComparer2));
- }
- //
+ //
+ private void CompareCurrentCultureStringComparer()
+ {
+ StringComparer stringComparer1 = StringComparer.CurrentCulture;
+ StringComparer stringComparer2 = StringComparer.CurrentCulture;
+ // Displays false
+ Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1,
+ stringComparer2));
+ }
+ //
- //
- private void CompareCurrentCultureInsensitiveStringComparer()
- {
- StringComparer stringComparer1, stringComparer2;
- stringComparer1 = StringComparer.CurrentCultureIgnoreCase;
- stringComparer2 = StringComparer.CurrentCultureIgnoreCase;
- // Displays false
- Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1,
- stringComparer2));
- }
- //
+ //
+ private void CompareCurrentCultureInsensitiveStringComparer()
+ {
+ StringComparer stringComparer1, stringComparer2;
+ stringComparer1 = StringComparer.CurrentCultureIgnoreCase;
+ stringComparer2 = StringComparer.CurrentCultureIgnoreCase;
+ // Displays false
+ Console.WriteLine(StringComparer.ReferenceEquals(stringComparer1,
+ stringComparer2));
+ }
+ //
}
diff --git a/snippets/csharp/System/StringComparer/Overview/omni.cs b/snippets/csharp/System/StringComparer/Overview/omni.cs
index c008dab1a26..d4d49884848 100644
--- a/snippets/csharp/System/StringComparer/Overview/omni.cs
+++ b/snippets/csharp/System/StringComparer/Overview/omni.cs
@@ -1,28 +1,28 @@
//
-// This example demonstrates members of the
+// This example demonstrates members of the
// System.StringComparer class.
using System;
-using System.Collections;
+
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
-class Sample
+class Sample
{
- public static void Main()
+ public static void Main()
{
// Create a list of string.
- List list = new List();
+ List list = new();
// Get the tr-TR (Turkish-Turkey) culture.
- CultureInfo turkish = new CultureInfo("tr-TR");
+ CultureInfo turkish = new("tr-TR");
// Get the culture that is associated with the current thread.
CultureInfo thisCulture = Thread.CurrentThread.CurrentCulture;
// Get the standard StringComparers.
- StringComparer invCmp = StringComparer.InvariantCulture;
+ StringComparer invCmp = StringComparer.InvariantCulture;
StringComparer invICCmp = StringComparer.InvariantCultureIgnoreCase;
StringComparer currCmp = StringComparer.CurrentCulture;
StringComparer currICCmp = StringComparer.CurrentCultureIgnoreCase;
@@ -34,10 +34,10 @@ public static void Main()
// Define three strings consisting of different versions of the letter I.
// LATIN CAPITAL LETTER I (U+0049)
- string capitalLetterI = "I";
+ string capitalLetterI = "I";
// LATIN SMALL LETTER I (U+0069)
- string smallLetterI = "i";
+ string smallLetterI = "i";
// LATIN SMALL LETTER DOTLESS I (U+0131)
string smallLetterDotlessI = "\u0131";
@@ -57,7 +57,7 @@ public static void Main()
Display(list, "Invariant culture, ignore case...");
// Sort the list using the current culture.
- Console.WriteLine("The current culture is \"{0}\".", thisCulture.Name);
+ Console.WriteLine($"The current culture is \"{thisCulture.Name}\".");
list.Sort(currCmp);
Display(list, "Current culture...");
list.Sort(currICCmp);
@@ -69,7 +69,7 @@ public static void Main()
list.Sort(ordICCmp);
Display(list, "Ordinal, ignore case...");
- // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER
+ // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER
// DOTLESS I differently than LATIN SMALL LETTER I.
list.Sort(turkICComp);
Display(list, "Turkish culture, ignore case...");
@@ -77,14 +77,14 @@ public static void Main()
public static void Display(List lst, string title)
{
- Char c;
- int codePoint;
+ char c;
+ int codePoint;
Console.WriteLine(title);
foreach (string s in lst)
{
c = s[0];
codePoint = Convert.ToInt32(c);
- Console.WriteLine("0x{0:x}", codePoint);
+ Console.WriteLine($"0x{codePoint:x}");
}
Console.WriteLine();
}
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