-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathChapter08.dib
878 lines (592 loc) · 20.3 KB
/
Chapter08.dib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
#!markdown
# Chapter 8 - Working with Common .NET Types
Execute the following code cell to make `Console` methods available in every code cell in this notebook.
#!csharp
using static System.Console;
#!markdown
# Working with numbers
One of the most common types of data is numbers.
#!csharp
using System.Numerics;
#!markdown
## Working with big integers
#!csharp
WriteLine("Working with large integers:");
WriteLine("----------------------------------------");
ulong big = ulong.MaxValue;
WriteLine($"{big,40:N0}");
BigInteger bigger =
BigInteger.Parse("123456789012345678901234567890");
WriteLine($"{bigger,40:N0}");
#!markdown
## Working with complex numbers
#!csharp
WriteLine("Working with complex numbers:");
Complex c1 = new(real: 4, imaginary: 2);
Complex c2 = new(real: 3, imaginary: 7);
Complex c3 = c1 + c2;
// output using default ToString implementation
WriteLine($"{c1} added to {c2} is {c3}"); // output using custom format
WriteLine("{0} + {1}i added to {2} + {3}i is {4} + {5}i",
c1.Real, c1.Imaginary,
c2.Real, c2.Imaginary,
c3.Real, c3.Imaginary);
#!markdown
# Working with text
One of the other most common types of data for variables is text.
#!csharp
string city = "London";
#!markdown
## Getting the length of a string
#!csharp
WriteLine($"{city} is {city.Length} characters long.");
#!markdown
## Getting the characters of a string
#!csharp
WriteLine($"First char is {city[0]} and third is {city[2]}.");
#!markdown
## Splitting a string
#!csharp
string cities = "Paris,Tehran,Chennai,Sydney,New York,Medellín";
string[] citiesArray = cities.Split(',');
WriteLine($"There are {citiesArray.Length} items in the array.");
foreach (string item in citiesArray)
{
WriteLine(item);
}
#!markdown
## Getting part of a string
Sometimes, you need to get part of some text. The `IndexOf` method has nine overloads that return the index position of a specified `char` or `string` within a `string`. The `Substring` method has two overloads, as shown in the following list:
- `Substring(startIndex, length)`: returns a substring starting at startIndex and containing the next length characters.
- `Substring(startIndex)`: returns a substring starting at startIndex and containing all characters up to the end of the string.
#!csharp
string fullName = "Alan Jones";
int indexOfTheSpace = fullName.IndexOf(' ');
string firstName = fullName.Substring(
startIndex: 0, length: indexOfTheSpace);
string lastName = fullName.Substring(
startIndex: indexOfTheSpace + 1);
WriteLine($"Original: {fullName}");
WriteLine($"Swapped: {lastName}, {firstName}");
#!markdown
## Checking a string for content
Sometimes, you need to check whether a piece of text starts or ends with some characters or contains some characters. You can achieve this with methods named `StartsWith`, `EndsWith`, and `Contains`:
#!csharp
string company = "Microsoft";
bool startsWithM = company.StartsWith("M");
bool containsN = company.Contains("N");
WriteLine($"Text: {company}");
WriteLine($"Starts with M: {startsWithM}, contains an N: {containsN}");
#!markdown
## Joining, formatting, and other string members
#!csharp
string recombined = string.Join(" => ", citiesArray);
WriteLine(recombined);
#!csharp
string fruit = "Apples";
decimal price = 0.39M;
DateTime when = DateTime.Today;
WriteLine($"Interpolated: {fruit} cost {price:C} on {when:dddd}.");
WriteLine(string.Format("string.Format: {0} cost {1:C} on {2:dddd}.",
arg0: fruit, arg1: price, arg2: when));
#!markdown
# Working with dates and times
After numbers and text, the next most popular types of data to work with are dates and times.
#!markdown
## Specifying date and time values
#!csharp
WriteLine("Earliest date/time value is: {0}",
arg0: DateTime.MinValue);
WriteLine("UNIX epoch date/time value is: {0}",
arg0: DateTime.UnixEpoch);
WriteLine("Date/time value Now is: {0}",
arg0: DateTime.Now);
WriteLine("Date/time value Today is: {0}",
arg0: DateTime.Today);
#!csharp
DateTime christmas = new(year: 2021, month: 12, day: 25);
WriteLine("Christmas: {0}",
arg0: christmas); // default format
WriteLine("Christmas: {0:dddd, dd MMMM yyyy}",
arg0: christmas); // custom format
WriteLine("Christmas is in month {0} of the year.",
arg0: christmas.Month);
WriteLine("Christmas is day {0} of the year.",
arg0: christmas.DayOfYear);
WriteLine("Christmas {0} is on a {1}.",
arg0: christmas.Year,
arg1: christmas.DayOfWeek);
#!csharp
DateTime beforeXmas = christmas.Subtract(TimeSpan.FromDays(12));
DateTime afterXmas = christmas.AddDays(12);
WriteLine("12 days before Christmas is: {0}",
arg0: beforeXmas);
WriteLine("12 days after Christmas is: {0}",
arg0: afterXmas);
TimeSpan untilChristmas = christmas - DateTime.Now;
WriteLine("There are {0} days and {1} hours until Christmas.",
arg0: untilChristmas.Days,
arg1: untilChristmas.Hours);
WriteLine("There are {0:N0} hours until Christmas.",
arg0: untilChristmas.TotalHours);
#!csharp
DateTime kidsWakeUp = new(
year: 2021, month: 12, day: 25,
hour: 6, minute: 30, second: 0);
WriteLine("Kids wake up on Christmas: {0}",
arg0: kidsWakeUp);
WriteLine("The kids woke me up at {0}",
arg0: kidsWakeUp.ToShortTimeString());
#!markdown
## Globalization with dates and times
The current culture controls how dates and times are parsed:
#!csharp
using System.Globalization;
#!csharp
// use the following line to switch to British culture
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
WriteLine("Current culture is: {0}",
arg0: CultureInfo.CurrentCulture.Name);
string textDate = "4 July 2021";
DateTime independenceDay = DateTime.Parse(textDate);
WriteLine("Text: {0}, DateTime: {1:d MMMM}",
arg0: textDate,
arg1: independenceDay);
textDate = "7/4/2021";
independenceDay = DateTime.Parse(textDate);
WriteLine("Text: {0}, DateTime: {1:d MMMM}",
arg0: textDate,
arg1: independenceDay);
independenceDay = DateTime.Parse(textDate,
provider: CultureInfo.GetCultureInfo("en-US"));
WriteLine("Text: {0}, DateTime: {1:d MMMM}",
arg0: textDate,
arg1: independenceDay);
#!csharp
for (int year = 2020; year < 2026; year++)
{
Write($"{year} is a leap year: {DateTime.IsLeapYear(year)}. ");
WriteLine("There are {0} days in February {1}.",
arg0: DateTime.DaysInMonth(year: year, month: 2), arg1: year);
}
WriteLine("Is Christmas daylight saving time? {0}",
arg0: christmas.IsDaylightSavingTime());
WriteLine("Is July 4th daylight saving time? {0}",
arg0: independenceDay.IsDaylightSavingTime());
#!markdown
## Working with only a date or a time
.NET 6 introduces some new types for working with only a date value or only a time value named DateOnly and TimeOnly.
#!csharp
DateOnly queensBirthday = new(year: 2022, month: 4, day: 21);
WriteLine($"The Queen's next birthday is on {queensBirthday}.");
TimeOnly partyStarts = new(hour: 20, minute: 30);
WriteLine($"The Queen's party starts at {partyStarts}.");
DateTime calendarEntry = queensBirthday.ToDateTime(partyStarts);
WriteLine($"Add to your calendar: {calendarEntry}.");
#!markdown
# Pattern matching with regular expressions
Regular expressions are useful for validating input from the user.
#!csharp
using System.Text.RegularExpressions;
#!markdown
## Checking for digits entered as text
#!csharp
#nullable enable // required to support string?
// Write("Enter your age: ");
string? input = "34"; // ReadLine();
Regex ageChecker = new(@"^\d+$");
if (ageChecker.IsMatch(input))
{
WriteLine("Thank you!");
}
else
{
WriteLine($"This is not a valid age: {input}");
}
#!markdown
## Splitting a complex comma-separated string
Earlier in this chapter, you learned how to split a simple comma-separated `string` variable. But what about the following example of film titles?
```
"Monsters, Inc.","I, Tonya","Lock, Stock and Two Smoking Barrels"
```
#!csharp
string films = "\"Monsters, Inc.\",\"I, Tonya\",\"Lock, Stock and Two Smoking Barrels\"";
WriteLine($"Films to split: {films}");
string[] filmsDumb = films.Split(',');
WriteLine("Splitting with string.Split method:");
foreach (string film in filmsDumb)
{
WriteLine(film);
}
#!csharp
WriteLine();
Regex csv = new(
"(?:^|,)(?=[^\"]|(\")?)\"?((?(1)[^\"]*|[^,\"]*))\"?(?=,|$)");
MatchCollection filmsSmart = csv.Matches(films);
WriteLine("Splitting with regular expression:");
foreach (Match film in filmsSmart)
{
WriteLine(film.Groups[2].Value);
}
#!markdown
# Storing multiple objects in collections
Another of the most common types of data is collections. If you need to store multiple values in a variable, then you can use a collection.
#!csharp
static void Output(string title, IEnumerable<string> collection)
{
WriteLine(title);
foreach (string item in collection)
{
WriteLine($" {item}");
}
}
#!markdown
## Working with lists
#!csharp
static void WorkingWithLists()
{
// Simple syntax for creating a list and adding three items
List<string> cities = new();
cities.Add("London");
cities.Add("Paris");
cities.Add("Milan");
/* Alternative syntax that is converted by the compiler into
the three Add method calls above
List<string> cities = new()
{ "London", "Paris", "Milan" };
*/
/* Alternative syntax that passes an
array of string values to AddRange method
List<string> cities = new();
cities.AddRange(new[] { "London", "Paris", "Milan" });
*/
Output("Initial list", cities);
WriteLine($"The first city is {cities[0]}.");
WriteLine($"The last city is {cities[cities.Count - 1]}.");
cities.Insert(0, "Sydney");
Output("After inserting Sydney at index 0", cities);
cities.RemoveAt(1);
cities.Remove("Milan");
Output("After removing two cities", cities);
}
#!csharp
WorkingWithLists();
#!markdown
## Working with dictionaries
#!csharp
static void WorkingWithDictionaries()
{
Dictionary<string, string> keywords = new();
// add using named parameters
keywords.Add(key: "int", value: "32-bit integer data type");
// add using positional parameters
keywords.Add("long", "64-bit integer data type");
keywords.Add("float", "Single precision floating point number");
/* Alternative syntax; compiler converts this to calls to Add method
Dictionary<string, string> keywords = new()
{
{ "int", "32-bit integer data type" },
{ "long", "64-bit integer data type" },
{ "float", "Single precision floating point number" },
}; */
/* Alternative syntax; compiler converts this to calls to Add method
Dictionary<string, string> keywords = new()
{
["int"] = "32-bit integer data type",
["long"] = "64-bit integer data type",
["float"] = "Single precision floating point number"
}; */
Output("Dictionary keys:", keywords.Keys);
Output("Dictionary values:", keywords.Values);
WriteLine("Keywords and their definitions");
foreach (KeyValuePair<string, string> item in keywords)
{
WriteLine($" {item.Key}: {item.Value}");
}
// lookup a value using a key
string key = "long";
WriteLine($"The definition of {key} is {keywords[key]}");
}
#!csharp
WorkingWithDictionaries();
#!markdown
## Working with queues
#!csharp
static void WorkingWithQueues()
{
Queue<string> coffee = new();
coffee.Enqueue("Damir"); // front of queue
coffee.Enqueue("Andrea");
coffee.Enqueue("Ronald");
coffee.Enqueue("Amin");
coffee.Enqueue("Irina"); // back of queue
Output("Initial queue from front to back", coffee);
// server handles next person in queue
string served = coffee.Dequeue();
WriteLine($"Served: {served}.");
// server handles next person in queue
served = coffee.Dequeue();
WriteLine($"Served: {served}.");
Output("Current queue from front to back", coffee);
WriteLine($"{coffee.Peek()} is next in line.");
Output("Current queue from front to back", coffee);
}
#!csharp
WorkingWithQueues();
#!csharp
static void OutputPQ<TElement, TPriority>(string title,
IEnumerable<(TElement Element, TPriority Priority)> collection)
{
WriteLine(title);
foreach ((TElement, TPriority) item in collection)
{
WriteLine($" {item.Item1}: {item.Item2}");
}
}
#!csharp
static void WorkingWithPriorityQueues()
{
PriorityQueue<string, int> vaccine = new();
// add some people
// 1 = high priority people in their 70s or poor health
// 2 = medium priority e.g. middle aged
// 3 = low priority e.g. teens and twenties
vaccine.Enqueue("Pamela", 1); // my mum (70s)
vaccine.Enqueue("Rebecca", 3); // my niece (teens)
vaccine.Enqueue("Juliet", 2); // my sister (40s)
vaccine.Enqueue("Ian", 1); // my dad (70s)
OutputPQ("Current queue for vaccination:", vaccine.UnorderedItems);
WriteLine($"{vaccine.Dequeue()} has been vaccinated.");
WriteLine($"{vaccine.Dequeue()} has been vaccinated.");
OutputPQ("Current queue for vaccination:", vaccine.UnorderedItems);
WriteLine($"{vaccine.Dequeue()} has been vaccinated.");
vaccine.Enqueue("Mark", 2); // me (40s)
WriteLine($"{vaccine.Peek()} will be next to be vaccinated.");
OutputPQ("Current queue for vaccination:", vaccine.UnorderedItems);
}
#!csharp
WorkingWithPriorityQueues();
#!markdown
## Using immutable collections
#!csharp
using System.Collections.Immutable;
#!csharp
static void WorkingWithLists2()
{
// Simple syntax for creating a list and adding three items
List<string> cities = new();
cities.Add("London");
cities.Add("Paris");
cities.Add("Milan");
/* Alternative syntax that is converted by the compiler into
the three Add method calls above
List<string> cities = new()
{ "London", "Paris", "Milan" };
*/
/* Alternative syntax that passes an
array of string values to AddRange method
List<string> cities = new();
cities.AddRange(new[] { "London", "Paris", "Milan" });
*/
Output("Initial list", cities);
WriteLine($"The first city is {cities[0]}.");
WriteLine($"The last city is {cities[cities.Count - 1]}.");
cities.Insert(0, "Sydney");
Output("After inserting Sydney at index 0", cities);
cities.RemoveAt(1);
cities.Remove("Milan");
Output("After removing two cities", cities);
ImmutableList<string> immutableCities = cities.ToImmutableList();
ImmutableList<string> newList = immutableCities.Add("Rio");
Output("Immutable list of cities:", immutableCities);
Output("New list of cities:", newList);
}
#!csharp
WorkingWithLists2();
#!markdown
# Working with spans, indexes, and ranges
C# 8.0 introduced two features for identifying an item's index within an array and a range of items using two indexes.
#!markdown
## Identifying ranges with the Range type
#!csharp
Range r1 = new(start: new Index(3), end: new Index(7));
Range r2 = new(start: 3, end: 7); // using implicit int conversion
Range r3 = 3..7; // using C# 8.0 or later syntax
Range r4 = Range.StartAt(3); // from index 3 to last index
Range r5 = 3..; // from index 3 to last index
Range r6 = Range.EndAt(3); // from index 0 to index 3
Range r7 = ..3; // from index 0 to index 3
#!markdown
## Using indexes, ranges, and spans
#!csharp
string name = "Samantha Jones";
// Using Substring
int lengthOfFirst = name.IndexOf(' ');
int lengthOfLast = name.Length - lengthOfFirst - 1;
string firstName = name.Substring(
startIndex: 0,
length: lengthOfFirst);
string lastName = name.Substring(
startIndex: name.Length - lengthOfLast,
length: lengthOfLast);
WriteLine($"First name: {firstName}, Last name: {lastName}");
// Using spans
ReadOnlySpan<char> nameAsSpan = name.AsSpan();
ReadOnlySpan<char> firstNameSpan = nameAsSpan[0..lengthOfFirst];
ReadOnlySpan<char> lastNameSpan = nameAsSpan[^lengthOfLast..^0];
WriteLine("First name: {0}, Last name: {1}",
arg0: firstNameSpan.ToString(),
arg1: lastNameSpan.ToString());
#!markdown
# Working with network resources
Sometimes you will need to work with network resources.
#!markdown
## Working with URIs, DNS, and IP addresses
#!csharp
using System.Net; // IPHostEntry, Dns, IPAddress
#!csharp
#nullable enable
// Write("Enter a valid web address: ");
string? url = "http://google.com"; // ReadLine();
if (string.IsNullOrWhiteSpace(url))
{
url = "https://stackoverflow.com/search?q=securestring";
}
Uri uri = new(url);
WriteLine($"URL: {url}");
WriteLine($"Scheme: {uri.Scheme}");
WriteLine($"Port: {uri.Port}");
WriteLine($"Host: {uri.Host}");
WriteLine($"Path: {uri.AbsolutePath}");
WriteLine($"Query: {uri.Query}");
#!csharp
IPHostEntry entry = Dns.GetHostEntry(uri.Host);
WriteLine($"{entry.HostName} has the following IP addresses:");
foreach (IPAddress address in entry.AddressList)
{
WriteLine($" {address} ({address.AddressFamily})");
}
#!markdown
## Pinging a server
#!csharp
using System.Net.NetworkInformation; // Ping, PingReply, IPStatus
#!csharp
try
{
Ping ping = new();
WriteLine("Pinging server. Please wait...");
PingReply reply = ping.Send(uri.Host);
WriteLine($"{uri.Host} was pinged and replied: {reply.Status}.");
if (reply.Status == IPStatus.Success)
{
WriteLine("Reply from {0} took {1:N0}ms",
arg0: reply.Address,
arg1: reply.RoundtripTime);
}
}
catch (Exception ex)
{
WriteLine($"{ex.GetType().ToString()} says {ex.Message}");
}
#!markdown
# Working with reflection and attributes
Reflection is a programming feature that allows code to understand and manipulate itself.
#!csharp
using System.Reflection; // Assembly
#!markdown
## Reading assembly metadata
Note: This example works best in a console application. In a .NET Interactive notebook, the assembly is `Microsoft.DotNet.Interactive.App`.
#!csharp
#nullable enable
WriteLine("Assembly metadata:");
Assembly? assembly = Assembly.GetEntryAssembly();
if (assembly is null)
{
WriteLine("Failed to get entry assembly.");
return;
}
WriteLine($" Full name: {assembly.FullName}");
WriteLine($" Location: {assembly.Location}");
IEnumerable<Attribute> attributes = assembly.GetCustomAttributes();
WriteLine($" Assembly-level attributes:");
foreach (Attribute a in attributes)
{
WriteLine($" {a.GetType()}");
}
#!csharp
#nullable enable
AssemblyInformationalVersionAttribute? version = assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
WriteLine($" Version: {version?.InformationalVersion}");
AssemblyCompanyAttribute? company = assembly
.GetCustomAttribute<AssemblyCompanyAttribute>();
WriteLine($" Company: {company?.Company}");
#!markdown
## Creating custom attributes
This section should only be tried in a console application.
#!markdown
# Working with images
ImageSharp is a third-party cross-platform 2D graphics library.
#!csharp
#r "nuget:SixLabors.ImageSharp,1.0.3"
#!csharp
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using System.IO;
#!csharp
string imagesFolder = Path.Combine(
Environment.CurrentDirectory, "images");
IEnumerable<string> images =
Directory.EnumerateFiles(imagesFolder);
foreach (string imagePath in images)
{
string thumbnailPath = Path.Combine(
Environment.CurrentDirectory, "images",
Path.GetFileNameWithoutExtension(imagePath)
+ "-thumbnail" + Path.GetExtension(imagePath));
using (Image image = Image.Load(imagePath))
{
image.Mutate(x => x.Resize(image.Width / 10, image.Height / 10));
image.Mutate(x => x.Grayscale());
image.Save(thumbnailPath);
}
}
WriteLine("Image processing complete. View the images folder.");
#!markdown
# Internationalizing your code
#!csharp
using System.Globalization; // CultureInfo
#!csharp
#nullable enable
CultureInfo globalization = CultureInfo.CurrentCulture;
CultureInfo localization = CultureInfo.CurrentUICulture;
WriteLine("The current globalization culture is {0}: {1}",
globalization.Name, globalization.DisplayName);
WriteLine("The current localization culture is {0}: {1}",
localization.Name, localization.DisplayName);
WriteLine();
WriteLine("en-US: English (United States)");
WriteLine("da-DK: Danish (Denmark)");
WriteLine("fr-CA: French (Canada)");
// Write("Enter an ISO culture code: ");
string? newCulture = "da-DK"; // ReadLine();
if (!string.IsNullOrEmpty(newCulture))
{
CultureInfo ci = new(newCulture);
// change the current cultures
CultureInfo.CurrentCulture = ci;
CultureInfo.CurrentUICulture = ci;
}
WriteLine();
// Write("Enter your name: ");
string? name = "Mikkel"; // ReadLine();
// Write("Enter your date of birth: ");
string? dob = "12/3/1980"; // ReadLine();
// Write("Enter your salary: ");
string? salary = "340000"; // ReadLine();
DateTime date = DateTime.Parse(dob);
int minutes = (int)DateTime.Today.Subtract(date).TotalMinutes;
decimal earns = decimal.Parse(salary);
WriteLine(
"{0} was born on a {1:dddd}, is {2:N0} minutes old, and earns {3:C}",
name, date, minutes, earns);